Input: 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 . [CODESPLIT] public void setId ( long id ) { // 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 ) ; } }


Input: Gets the string value of a string attribute . [CODESPLIT] public String getStringValue ( ) { // 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 ; } }


Input: 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 . [CODESPLIT] public void setStringValue ( String value ) throws IllegalArgumentException { 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 ; }


Input: Parses the next sentence from the current token source . [CODESPLIT] public Sentence < Term > parse ( ) throws SourceCodeException { try { return new SentenceImpl < Term > ( parser . termSentence ( ) ) ; } catch ( SourceCodeException e ) { throw new IllegalStateException ( e ) ; } }


Input: Reads a Lojix term and invoked appropriate methods on the content handler to describe its structure and contents to it . [CODESPLIT] private void read ( Term term ) { 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 ) ; } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public final MicrodataItem getItem ( String type ) { List < MicrodataItem > items = getItems ( type ) ; if ( items . isEmpty ( ) ) { throw new MicrodataItemNotFoundException ( newUrl ( type ) ) ; } return items . get ( 0 ) ; }


Input: Checks if the named class exists and is loadable . [CODESPLIT] public static boolean classExistsAndIsLoadable ( String className ) { try { Class . forName ( className ) ; return true ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored. e = null ; return false ; } }


Input: Checks if the named class exists and is loadable and is a sub - type of the specified class . [CODESPLIT] public static boolean isSubTypeOf ( Class parent , String className ) { try { Class cls = Class . forName ( className ) ; return parent . isAssignableFrom ( cls ) ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored. e = null ; return false ; } }


Input: Checks that the named child class is the same type or a sub - type of the named parent class . [CODESPLIT] public static boolean isSubTypeOf ( String parent , String child ) { try { return isSubTypeOf ( Class . forName ( parent ) , Class . forName ( child ) ) ; } catch ( ClassNotFoundException e ) { // Exception noted so can be ignored. e = null ; return false ; } }


Input: Checks that the child class is the same type or a sub - type of the parent class . [CODESPLIT] public static boolean isSubTypeOf ( Class parentClass , Class childClass ) { 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 ; } }


Input: Gets the Class object for a named class . [CODESPLIT] public static Class < ? > forName ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new ReflectionUtilsException ( "ClassNotFoundException whilst finding class: " + className + "." , e ) ; } }


Input: Creates an instance of a Class instantiated through its no - args constructor . [CODESPLIT] public static < T > T newInstance ( Class < T > cls ) { 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 ) ; } }


Input: Calls a constuctor with the specified arguments . [CODESPLIT] public static < T > T newInstance ( Constructor < T > constructor , Object [ ] args ) { 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 ) ; } }


Input:
Calls a named method on an object with a specified set of parameters any Java access modifier are overridden . [CODESPLIT] public static Object callMethodOverridingIllegalAccess ( Object o , String method , Object [ ] params , Class [ ] paramClasses ) { // 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 ) ; } }


Input: Calls a named method on an object with a specified set of parameters . [CODESPLIT] public static Object callMethod ( Object o , String method , Object [ ] params ) { // 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 ) ; } }


Input: Calls a named static method on a class with a specified set of parameters . [CODESPLIT] public static Object callStaticMethod ( Method method , Object [ ] params ) { try { return method . invoke ( null , params ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }


Input: 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 . [CODESPLIT] public static < T > Constructor < T > getConstructor ( Class < T > cls , Class [ ] args ) { try { return cls . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } }


Input:
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 . [CODESPLIT] public static Set < Class > findMatchingSetters ( Class obClass , String propertyName ) { /*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 ; }


Input: Renders the table . [CODESPLIT] public void renderTable ( ) { 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 ; } } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private URL getAction ( ) { String action = element . getAttribute ( "action" ) ; if ( action . isEmpty ( ) ) { action = driver . getCurrentUrl ( ) ; } return newUrlOrNull ( action ) ; }


Input: Wraps a java . util . concurrent . BlockingQueue as a { @link com . thesett . common . util . concurrent . BlockingQueue } implementation . [CODESPLIT] public static < E > BlockingQueue < E > getBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , false , false ) ; }


Input: Wraps a java . util . concurrent . BlockingQueue as a { @link com . thesett . common . util . concurrent . BlockingQueue } implementation . [CODESPLIT] public static < E > SizeableBlockingQueue < E > getSizeableBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , false , false ) ; }


Input: Wraps queue as a sizeable atomically counted queue as per the { @link #getSizeableQueue } and { @link #getAtomicCountedQueue } methods . [CODESPLIT] public static < E extends Sizeable > SizeableQueue < E > getAtomicCountedSizeableQueue ( java . util . Queue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , true , true ) ; }


Input: Provides a transactional queue that delays all queue manipulation operations until the transaction is committed or erases them if it is rolled back . [CODESPLIT] public static < E > Queue < E > getTransactionalQueue ( java . util . Queue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , true , false , false ) ; }


Input: 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 . [CODESPLIT] public static < E > Queue < E > getTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , false , false ) ; }


Input: Wraps queue as a sizeable transactional requeue as per the { @link #getSizeableQueue } and { @link #getTransactionalReQueue } methods . [CODESPLIT] public static < E extends Sizeable > SizeableQueue < E > getSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , true , false ) ; }


Input: Wraps queue as a sizeable atomically counted queue transactional requeue as per the { @link #getSizeableQueue } { @link #getAtomicCountedQueue } and { @link #getTransactionalReQueue } methods . [CODESPLIT] public static < E extends Sizeable > Queue < E > getAtomicCountedSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , true , true ) ; }


Input: Gets the type of a specified object . [CODESPLIT] public static Type getTypeFromObject ( Object o ) { // 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 ) ; }


Input: Resets the search clearing out the queue and setting it to contain just the start state node . [CODESPLIT] public void reset ( ) { // 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 ( ) ; }


Input: 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 . [CODESPLIT] public Queue < SearchNode < O , T > > enqueueStartStates ( Collection < T > startStates ) { // 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 ; }


Input: 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 . [CODESPLIT] public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { // Delegate the search to the pluggable search algorithm. return searchAlgorithm . search ( this , startStates , maxSteps , searchSteps ) ; }


Input: 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 . [CODESPLIT] public T search ( ) throws SearchNotExhaustiveException { SearchNode < O , T > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; } }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { 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 ; }


Input: Creates a new int range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , int min , int max ) { // Ensure that min is less than or equal to max. if ( min > max ) { throw new IllegalArgumentException ( "'min' must be less than or equal to 'max'." ) ; } synchronized ( 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 ; } } }


Input: { @inheritDoc } [CODESPLIT] public Set < Integer > getAllPossibleValuesSet ( ) throws InfiniteValuesException { Set < Integer > results = new HashSet < Integer > ( ) ; for ( int i = minValue ; i <= maxValue ; i ++ ) { results . add ( i ) ; } return results ; }


Input: { [CODESPLIT] public Iterator < Integer > getAllPossibleValuesIterator ( ) throws InfiniteValuesException { return new Iterator < Integer > ( ) { int current = minValue ; /** {@inheritDoc} */ public boolean hasNext ( ) { return current <= maxValue ; } /** {@inheritDoc} */ public Integer next ( ) { if ( hasNext ( ) ) { int result = current ; current ++ ; return result ; } else { throw new NoSuchElementException ( "No more elements less than or equal to max." ) ; } } /** {@inheritDoc} */ public void remove ( ) { throw new UnsupportedOperationException ( "This iterator does not support 'remove'." ) ; } } ; }


Input: Evaluates the arithmetic operator on its two numeric arguments . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber , NumericType secondNumber ) { // 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 ( ) ) ) ; } }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { // 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 ; }


Input: { [CODESPLIT] public void createContinuationStates ( ResolutionState state ) { for ( Functor disjunct : disjuncts ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( disjunct ) ; newGoal . setParentChoicePointState ( state ) ; state . createContinuationStatesForGoal ( newGoal ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public boolean areLinked ( SqlTable table1 , SqlTable table2 ) { return predecessorRelation . get ( table1 . getTableName ( ) ) . containsKey ( table2 . getTableName ( ) ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public DimensionTable getDimensionByName ( String dimensionName , String tzNameAlias ) { 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 ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public List < AbstractSqlColumn > getMeasuresColumn ( ) { return Collections . unmodifiableList ( Lists . newArrayList ( factTable . getMeasuresColumn ( ) . values ( ) ) ) ; }


Input: { [CODESPLIT] @ Override public Optional < AbstractSqlColumn > getMeasuresByName ( String informationName ) { for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equalsIgnoreCase ( informationName ) ) { return Optional . of ( column ) ; } } return Optional . absent ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public AbstractSqlColumn getInformationColumn ( DimensionTable dimension , String informationName ) { final AbstractSqlColumn sqlTableColumn = dimension . getSqlTableColumnByInformationName ( informationName ) ; if ( sqlTableColumn == null ) { throw new IllegalArgumentException ( "Invalid sqlTableColumn for the informationName: " + informationName ) ; } return sqlTableColumn ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isValidDimension ( String dimensionName , String informationName ) { 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 ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isMandatoryDimension ( String dimensionName ) { if ( isValidDimension ( dimensionName , null ) ) { return mandatoryDimensionNames . contains ( dimensionName . toUpperCase ( Locale . ENGLISH ) ) ; } return false ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public ColumnDataType getInformationType ( String dimensionName , String informationName ) { 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" ) ; }


Input: Add a new supported tz . Add one aliase with the same name [CODESPLIT] public void addSupportedTZ ( String tzName ) { 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 ) ; } } }


Input: Timezone is case sensitive [CODESPLIT] public void addTZAlternateDimension ( String orignalDimensionName , DimensionTable alternateDimension , String tzName ) { 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 ) ; } }


Input: Add a dimension as mandatory . Mandatory dimension names are stored in upper case . [CODESPLIT] public void addDimension ( DimensionTable table , boolean mandatory ) { sqlTables . put ( table . getTableName ( ) , table ) ; dimensions . put ( table . getDimensionName ( ) . toUpperCase ( ) , table ) ; if ( mandatory ) { mandatoryDimensionNames . add ( table . getDimensionName ( ) . toUpperCase ( Locale . ENGLISH ) ) ; } }


Input: Build the configuration links ( ie Foreigns key ) . Checks the validity of the configuration . [CODESPLIT] public Collection < Error > buildAndValidateConfig ( ) { 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 ; }


Input: { [CODESPLIT] @ Override public boolean isValidMeasure ( String name ) { for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equals ( name ) ) { return true ; } } return false ; }


Input: Calculates the set of free variables in a term . [CODESPLIT] public static Set < Variable > findFreeVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }


Input: 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 . [CODESPLIT] public static Set < Variable > findFreeNonAnonymousVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeNonAnonymousVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }


Input: 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 . [CODESPLIT] public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , String symbolToFlattenOn , VariableAndFunctorInterner interner ) throws SourceCodeException { 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 ; }


Input: 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 . [CODESPLIT] public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , int internedName ) { 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 ; }


Input: 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 . [CODESPLIT] public static Clause convertToClause ( Term term , VariableAndFunctorInterner interner ) throws SourceCodeException { // 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 ( ) ) ; } }


Input: Compares two heuristic search nodes by their heuristic values . [CODESPLIT] public int compare ( SearchNode object1 , SearchNode object2 ) { float h1 = ( ( HeuristicSearchNode ) object1 ) . getH ( ) ; float h2 = ( ( HeuristicSearchNode ) object2 ) . getH ( ) ; return ( h1 > h2 ) ? 1 : ( ( h1 < h2 ) ? - 1 : 0 ) ; }


Input: Reads a text file as a string . [CODESPLIT] public static String readFileAsString ( String filename ) { BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( filename ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ; }


Input: Reads a text file as a string . [CODESPLIT] public static String readFileAsString ( File file ) { BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( file ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ; }


Input: Writes an object using its toString method to the named file . The object may optionally be appended to the file or may overwrite it . [CODESPLIT] public static void writeObjectToFile ( String outputFileName , Object toWrite , boolean append ) { // 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 ) ; } }


Input: 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 . [CODESPLIT] private static String readStreamAsString ( BufferedInputStream is ) { 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 ) ; } }


Input: Appends the specified element to the end of this list ( optional operation ) . [CODESPLIT] public boolean add ( T o ) { boolean result = super . add ( o ) ; sizeOf += ( result ) ? o . sizeof ( ) : 0 ; return result ; }


Input: 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 ) . [CODESPLIT] public boolean remove ( Object o ) { boolean result = super . remove ( o ) ; sizeOf -= ( ( o instanceof Sizeable ) && result ) ? ( ( Sizeable ) o ) . sizeof ( ) : 0 ; return result ; }


Input: Inserts the specified element at the specified position in this list ( optional operation ) . Shifts the element currently at that position ( if any ) and any subsequent elements to the right ( adds one to their indices ) . [CODESPLIT] public void add ( int index , T element ) { super . add ( index , element ) ; sizeOf += element . sizeof ( ) ; }


Input: Removes the element at the specified position in this list ( optional operation ) . Shifts any subsequent elements to the left ( subtracts one from their indices ) . Returns the element that was removed from the list . [CODESPLIT] public T remove ( int index ) { T result = super . remove ( index ) ; sizeOf += ( result != null ) ? result . sizeof ( ) : 0 ; return result ; }


Input: Appends all of the elements in the specified collection to the end of this list in the order that they are returned by the specified collection s iterator ( optional operation ) . The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress . ( Note that this will occur if the specified collection is this list and it s nonempty . ) [CODESPLIT] public boolean addAll ( Collection < ? extends T > c ) { if ( c instanceof Sizeable ) { sizeOf += ( ( Sizeable ) c ) . sizeof ( ) ; } return super . addAll ( c ) ; }


Input: { [CODESPLIT] protected void enterClause ( Clause clause ) { if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } } }


Input: { [CODESPLIT] protected void enterPredicate ( Predicate predicate ) { if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } } }


Input: Creates the correct type of search nodes for this search . This search uses heuristic search nodes . [CODESPLIT] public SearchNode < O , T > createSearchNode ( T state ) { return new HeuristicSearchNode < O , T > ( state , heuristic ) ; }


Input: Applies a built - in replacement transformation to functors . If the functor matches built - in a { @link BuiltInFunctor } is created with a mapping to the functors built - in implementation and the functors arguments are copied into this new functor . If the functor does not match a built - in it is returned unmodified . [CODESPLIT] public BuiltInFunctor apply ( Functor functor ) { FunctorName functorName = interner . getFunctorFunctorName ( functor ) ; Class < ? extends BuiltInFunctor > builtInClass ; if ( builtIns . containsKey ( functorName ) ) { builtInClass = builtIns . get ( functorName ) ; } else { builtInClass = DefaultBuiltIn . class ; } return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInClass , new Class [ ] { Functor . class } ) , new Object [ ] { functor } ) ; }


Input: Generates a sequence of spaces to indent debugging output with . [CODESPLIT] public String generateTraceIndent ( int delta ) { if ( ! useIndent ) { return "" ; } else { if ( delta >= 1 ) { indentStack . push ( delta ) ; } else if ( delta < 0 ) { indentStack . pop ( ) ; } StringBuffer result = new StringBuffer ( ) ; traceIndent += ( delta < 0 ) ? delta : 0 ; for ( int i = 0 ; i < traceIndent ; i ++ ) { result . append ( " " ) ; } traceIndent += ( delta > 0 ) ? delta : 0 ; return result . toString ( ) ; } }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Generate the call or tail-call instructions, followed by the call address, which is f_n of the // called program. if ( isLastBody ) { // Deallocate the stack frame at the end of the clause, but prior to calling the last // body predicate. // This is not required for chain rules, as they do not need a stack frame. if ( ! chainRule ) { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , interner . getFunctorFunctorName ( expression ) ) ) ; } else { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Call , ( byte ) ( permVarsRemaining & 0xff ) , interner . getFunctorFunctorName ( expression ) ) ) ; } return instructions ; }


Input:
{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { // 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. /*if (!isFirstBody)
        {
            lastAllocatedRegister = 0;
        }*/ allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Loop over all of the arguments to the outermost functor. int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; j < numOutermostArgs ; j ++ ) { Term nextOutermostArg = expression . getArgument ( j ) ; int allocation = ( Integer ) symbolTable . get ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // On the first occurrence of a variable output a put_var. // On a subsequent variable occurrence output a put_val. if ( nextOutermostArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; // The variable has been moved into an argument register. //varNames.remove((byte) allocation); //varNames.put((byte) j, ((Variable) nextOutermostArg).getName()); /*log.fine("PUT_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Put ) ; } else if ( nextOutermostArg . isVar ( ) ) { // Check if this is the last body functor in which this variable appears, it does so only in argument // position, and this is the first occurrence of these conditions. In which case, an unsafe put is to // be used. if ( isLastBodyTermInArgPositionOnly ( ( Variable ) nextOutermostArg , expression ) && ( addrMode == WAMInstruction . STACK_ADDR ) ) { /*log.fine("PUT_UNSAFE_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" +
                        j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutUnsafeVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , null ) ; } else { /*log.fine("PUT_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; } } // When a functor is encountered, output a put_struc. else if ( nextOutermostArg . isFunctor ( ) ) { Term nextFunctorArg = ( Functor ) nextOutermostArg ; // Heap cells are to be created in an order such that no heap cell can appear before other cells that it // refers to. A postfix traversal of the functors in the term to compile is used to achieve this, as // child functors in a head will be visited first. // Walk over the query term in post-fix order, picking out just the functors. QueueBasedSearchMethod < Term , Term > postfixSearch = new PostFixSearch < Term , Term > ( ) ; postfixSearch . reset ( ) ; postfixSearch . addStartState ( nextFunctorArg ) ; postfixSearch . setGoalPredicate ( new FunctorTermPredicate ( ) ) ; Iterator < Term > treeWalker = Searches . allSolutions ( postfixSearch ) ; // For each functor encountered: put_struc. while ( treeWalker . hasNext ( ) ) { Functor nextFunctor = ( Functor ) treeWalker . next ( ) ; allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; // Ouput a put_struc instuction, except on the outermost functor. /*log.fine("PUT_STRUC " + interner.getFunctorName(nextFunctor) + "/" + nextFunctor.getArity() +
                        ((addrMode == REG_ADDR) ? ", X" : ", Y") + address);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutStruc , addrMode , address , interner . getDeinternedFunctorName ( nextFunctor . getName ( ) ) , 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 ) ; // If it is new variable: set_var or put_var. // If it is variable or functor already seen: set_val or put_val. if ( nextArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; /*log.fine("SET_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Set ) ; } 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("SET_LOCAL_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") +
                                    address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /*log.fine("SET_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } } } return instructions ; }


Input: For a predicate of arity n the first n registers are used to receive its arguments in . [CODESPLIT] protected void allocateArgumentRegisters ( Functor expression ) { // Assign argument registers to functors appearing directly in the argument of the outermost functor. // Variables are never assigned directly to argument registers. int reg = 0 ; for ( ; reg < expression . getArity ( ) ; reg ++ ) { Term term = expression . getArgument ( reg ) ; if ( term instanceof Functor ) { /*log.fine("X" + lastAllocatedTempReg + " = " + interner.getFunctorFunctorName((Functor) term));*/ int allocation = ( reg & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } } }


Input: Allocates terms within a functor expression to registers . The outermost functor itself is not assigned to a register in WAM ( only in l0 ) . Functors already directly assigned to argument registers will not be re - assigned by this . Variables as arguments will be assigned but not as argument registers . [CODESPLIT] protected void allocateTemporaryRegisters ( Term expression ) { // Need to assign registers to the whole syntax tree, working in from the outermost functor. The outermost // functor itself is not assigned to a register in l3 (only in l0). Functors already directly assigned to // argument registers will not be re-assigned by this, variables as arguments will be assigned. SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Discard the outermost functor from the variable allocation. treeWalker . next ( ) ; // For each term encountered: set X++ = term. while ( treeWalker . hasNext ( ) ) { Term term = treeWalker . next ( ) ; if ( symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) == null ) { int allocation = ( lastAllocatedTempReg ++ & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } } }


Input: Determines whether a variable is local that is it may only exist on the stack . When variables are introduced into clauses the way in which they are introduced is recorded using the { @link VarIntroduction } enum . When a variable is being written to the heap for the first time this check may be used to see if a local variant of an instruction is needed in order to globalize the variable on the heap . [CODESPLIT] protected boolean isLocalVariable ( VarIntroduction introduction , byte addrMode ) { if ( WAMInstruction . STACK_ADDR == addrMode ) { return ( introduction == VarIntroduction . Get ) || ( introduction == VarIntroduction . Put ) ; } else { return introduction == VarIntroduction . Get ; } }


Input: Checks if a variable is appearing within the last body functor in which it occurs and only does so within argument position . [CODESPLIT] private boolean isLastBodyTermInArgPositionOnly ( Term var , Functor body ) { return body == symbolTable . get ( var . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR ) ; }


Input:
Builds a decision tree by repeatedly selecting the best property of the data examples to split on . The best property is chosen to be the one that reveals the most information about the target property to learn . [CODESPLIT] public ClassifyingMachine learn ( ) throws LearningFailureException { /*log.fine("public ClassifyingMachine learn(): called");*/ // Call the initialize method to ensure that input and output properties are correctly set up. initialize ( ) ; // Check that there is only one output property to learn for. Decision trees can only output a single // property classification (although mutliple trees could be built for multiple properties). if ( outputProperties . size ( ) != 1 ) { throw new LearningFailureException ( "Decision trees can only learn a classification for a single property, " + "but " + outputProperties . size ( ) + " have been set as outputs." , null ) ; } // Extract the single output property to learn for. String outputProperty = outputProperties . iterator ( ) . next ( ) ; // Check that the output property to be learnt is one with a finite number of values. Decision trees // cannot learn infinite valued attributes, such as real numbers etc. int numValues = inputExamples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; if ( numValues < 1 ) { throw new LearningFailureException ( "Decision trees can only learn a classification for a " + "property with a finite number of values. The property, " + outputProperty + " can have an infinite number of values and should be " + "discretized prior to being learned by decision trees." , null ) ; } // Used to queue nodes that are pending construction. Queue < DecisionTree > pendingNodes = new LinkedList < DecisionTree > ( ) ; // Create a pending node,(an empty tree, the examples, the attributes, the default classification). Pending startNode = new Pending ( inputExamples , inputProperties , getMajorityClassification ( outputProperty , inputExamples ) , null ) ; // Create the root of the decision tree out of this start pending node. DecisionTree decisionTree = new DecisionTree ( startNode ) ; // Push this new pending node onto the construction queue. pendingNodes . offer ( decisionTree ) ; // Loop until the queue of nodes pending construction is empty. while ( ! pendingNodes . isEmpty ( ) ) { /*log.fine("Got next pending node.");*/ // Get the tree fragment for the next pending node. The data element should always be safe to cast to a // Pending node as this algorithm only pushes pending nodes onto the queue. DecisionTree currentTreePendingNode = pendingNodes . remove ( ) ; DecisionTreeElement currentTreePendingNodeElement = currentTreePendingNode . getElement ( ) ; Pending currentNode = ( Pending ) currentTreePendingNodeElement ; // Extract the examples, the attributes, the default classification, and the attribute to be matched, // for this pending node. Collection < State > examples = currentNode . getExamples ( ) ; Collection < String > undecidedProperties = currentNode . getUndecidedProperties ( ) ; OrdinalAttribute defaultAttribute = currentNode . getDefault ( ) ; OrdinalAttribute matchingAttribute = currentNode . getAttributeValue ( ) ; /*log.fine("Pending node corresponds to " + examples.size() + " examples.");*/ /*log.fine("Pending node has " + undecidedProperties.size() + " undecided properties left.");*/ // Used to hold the decision tree fragment (decision node, pending node or assignment leaf) that will // be inserted into the decision tree to replace the current pending node. DecisionTree newTreeFragment = null ; // If the set of examples is empty then set the default as the leaf. if ( examples . isEmpty ( ) ) { /*log.fine("Examples is empty.");*/ newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , defaultAttribute , matchingAttribute ) ) ; } // Else if undecided properties is empty then set the majority value of the classification of // examples as the leaf. else if ( undecidedProperties . isEmpty ( ) ) { /*log.fine("No undecided properties left.");*/ // Work out what the majority classification is and create a leaf with that assignment. OrdinalAttribute majority = getMajorityClassification ( outputProperty , inputExamples ) ; newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , majority , matchingAttribute ) ) ; } // Else if all the examples have the same classification then set that classification as the leaf. else if ( allHaveSameClassification ( outputProperty , examples ) ) { /*log.fine("All examples have the same classification.");*/ newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , allClassification , matchingAttribute ) ) ; } // Else choose the best attribute (with the largest estimated information gain) on the classification. else { /*log.fine("Choosing the best property to split on.");*/ String bestProperty = chooseBestPropertyToDecideOn ( outputProperty , examples , inputProperties ) ; // Check if a best property could not be found, in which case behave as if there are no // input properties left to work with. if ( bestProperty == null ) { /*log.fine("Couldn't find a best property to split on.");*/ // Put the pending node back onto the construction queue but with zero input properties. Pending newPendingNode = new Pending ( examples , new ArrayList < String > ( ) , defaultAttribute , matchingAttribute ) ; newTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newTreeFragment ) ; } else { // Extract an attribute with this property name from the first example and use this to get // a listing of all the possible values of that attribute. Attribute bestAttribute = ( OrdinalAttribute ) examples . iterator ( ) . next ( ) . getProperty ( bestProperty ) ; /*log.fine("bestProperty = " + bestProperty);*/ /*log.fine("bestAttribute = " + bestAttribute);*/ // Create a decision node that decides on the best property. New pending nodes will be created // as children of this node and added to it. newTreeFragment = new DecisionTree ( new Decision ( bestProperty , bestAttribute . getType ( ) . getNumPossibleValues ( ) , matchingAttribute ) ) ; // Produce a cut down input property set equal to the old one but with the selected best property // removed as a decision node is to be created for it. Set < String > newInputProperties = new HashSet < String > ( inputProperties ) ; newInputProperties . remove ( bestProperty ) ; // For each possible value of the best attribute. for ( Iterator < ? extends Attribute > i = bestAttribute . getType ( ) . getAllPossibleValuesIterator ( ) ; i . hasNext ( ) ; ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) i . next ( ) ; // Extract just those examples with the current value. To implement this efficiently first sort // the examples by their attribute value for the best property to split on using a range sort // (O(n) time as num possible values is limited and they are already indexed by their order). // Create the new example collection as simply a pair of indexes into the sorted list. Collection < State > matchingExamples = new ArrayList < State > ( ) ; for ( State example : examples ) { // Extract the attribute value for the property to decide on. OrdinalAttribute testAttribute = ( OrdinalAttribute ) example . getProperty ( bestProperty ) ; // Check if it matches the current value being extracted and add it to the collection of // extracted examples if so. if ( nextAttribute . equals ( testAttribute ) ) { matchingExamples . add ( example ) ; } } // Push onto the queue, a child node for this value, the subset of examples (or the value to // select that subset on), attributes without the best one (or an exclusion list of attributes // used so far), default majority-value of classification of these examples. Pending newPendingNode = new Pending ( matchingExamples , newInputProperties , getMajorityClassification ( outputProperty , matchingExamples ) , nextAttribute ) ; DecisionTree newPendingNodeTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newPendingNodeTreeFragment ) ; /*log.fine("Created new pending node below the split, for " + matchingExamples.size() +
                            " examples and " + newInputProperties.size() + " undecided properties.");*/ // Add the new pending node as a child of the parent decision node for the best property. newTreeFragment . addChild ( newPendingNodeTreeFragment ) ; } } } // Remove the current pending node from the decision tree and replace it with the new element that the // algorithm has selected. Tree . Node parentTree = ( DecisionTree ) currentTreePendingNode . getParent ( ) ; // Check if the current pending node has a parent (if not it is the real tree root and the first pending // node created). if ( parentTree != null ) { // Remove the pending node from its parents child list. parentTree . getChildren ( ) . remove ( currentTreePendingNode ) ; // Replace the pending node with the newly built tree fragment in its parent child list. parentTree . addChild ( newTreeFragment ) ; } else { // Update the root tree pointer to point to the newly built tree fragment. decisionTree = newTreeFragment ; } /*log.fine("There are now " + pendingNodes.size() + " pending nodes on the construction queue.");*/ } // Loop over the whole decision tree initializing its quick lookup tables for all the decisions it contains. for ( Iterator < SimpleTree < DecisionTreeElement > > i = decisionTree . iterator ( Tree . IterationOrder . PreOrder ) ; i . hasNext ( ) ; ) { DecisionTree nextTreeFragment = ( DecisionTree ) i . next ( ) ; DecisionTreeElement nextElement = nextTreeFragment . getElement ( ) ; // Check if it is a decision and build its lookup table if so. if ( nextElement instanceof Decision ) { Decision decision = ( Decision ) nextElement ; decision . initializeLookups ( nextTreeFragment ) ; } } // Create a new decisition tree machine out of the fully constructed decision tree. ProtoDTMachine dtMachine = new ProtoDTMachine ( ) ; dtMachine . setDecisionTree ( decisionTree ) ; // Return the trained decision tree classifying machine. return dtMachine ; }


Input: This helper method works out how the majority of the specified examples are classified by the named property . The property should always be the goal property that the algorithm is learning and must always take on a finite number of different values . [CODESPLIT] private OrdinalAttribute getMajorityClassification ( String property , Iterable < State > examples ) throws LearningFailureException { /*log.fine("private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called");*/ /*log.fine("property = " + property);*/ // Flag used to indicate that the map to hold the value counts in has been initialized. Map < OrdinalAttribute , Integer > countMap = null ; // Used to hold the biggest count found so far. int biggestCount = 0 ; // Used to hold the value with the biggest count found so far. OrdinalAttribute biggestAttribute = null ; // Loop over all the examples counting the number of occurences of each possible classification by the // named property. for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; /*log.fine("nextAttribute = " + nextAttribute);*/ // If this is the first attribute then find out how many possible values it can take on. if ( countMap == null ) { // A check has already been performed at the start of the learning method to ensure that the output // property only takes on a finite number of values. countMap = new HashMap < OrdinalAttribute , Integer > ( ) ; } int count ; // Increment the count for the number of occurences of this classification. if ( ! countMap . containsKey ( nextAttribute ) ) { count = 1 ; countMap . put ( nextAttribute , count ) ; } else { count = countMap . get ( nextAttribute ) ; countMap . put ( nextAttribute , count ++ ) ; } // Compare it to the biggest score found so far to see if it is bigger. if ( count > biggestCount ) { // Update the biggest score. biggestCount = count ; // Update the value of the majority classification. biggestAttribute = nextAttribute ; } } // Return the majority classification found. return biggestAttribute ; }


Input: Tests if a property of a set of examples has the same value for all the examples . This algorithm works by iterating through the examples until two different values are found or the end of the collection is reached having found only one value . [CODESPLIT] private boolean allHaveSameClassification ( String property , Iterable < State > examples ) { // Used to hold the value of the first attribute seen. OrdinalAttribute firstAttribute = null ; // Flag used to indicate that the test passed successfully. boolean success = true ; // Loop over all the examples. for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; // If this is the first example just store its attribute value. if ( firstAttribute == null ) { firstAttribute = nextAttribute ; } // Otherwise check if the attribute value does not match the first one in which case the test fails. else if ( ! nextAttribute . equals ( firstAttribute ) ) { success = false ; break ; } } // If the test passed then store the matching classification that all the examples have in a memeber variable // from where it can be accessed. if ( success ) { allClassification = firstAttribute ; } return success ; }


Input:
For a given set of examples input properties and an output property this method chooses the input property that provides the largest information gain on the value of the output property . [CODESPLIT] private String chooseBestPropertyToDecideOn ( String outputProperty , Iterable < State > examples , Iterable < String > inputProperties ) { /*log.fine("private String chooseBestPropertyToDecideOn(String outputProperty, Collection<State> examples, " +
         "Collection<String> inputProperties): called");*/ // for (State e : examples) /*log.fine(e);*/ // Determine how many possible values (symbols) the output property can have. int numOutputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; // Used to hold the largest information gain found so far. double largestGain = 0.0d ; // Used to hold the input property that gives the largest gain found so far. String largestGainProperty = null ; // Loop over all the input properties. for ( String inputProperty : inputProperties ) { // let G = the set of goal property values. // let A = the set of property values that the input property can have. // Determine how many possible values (symbols) the input property can have. int numInputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( inputProperty ) . getNumPossibleValues ( ) ; // Create an array to hold the counts of the output symbols. int [ ] outputCounts = new int [ numOutputValues ] ; // Create arrays to hold the counts of the input symbols and the joint input/output counts. int [ ] inputCounts = new int [ numInputValues ] ; int [ ] [ ] jointCounts = new int [ numInputValues ] [ numOutputValues ] ; // Loop over all the examples. for ( State example : examples ) { // Extract the output property attribute value. OrdinalAttribute outputAttribute = ( OrdinalAttribute ) example . getProperty ( outputProperty ) ; // Extract the input property attribute value. OrdinalAttribute inputAttribute = ( OrdinalAttribute ) example . getProperty ( inputProperty ) ; // Increment the count for the occurence of this value of the output property. outputCounts [ outputAttribute . ordinal ( ) ] ++ ; // Increment the count for the occurence of this value of the input property. inputCounts [ inputAttribute . ordinal ( ) ] ++ ; // Increment the count for the joint occurrence of this input/output value pair. jointCounts [ inputAttribute . ordinal ( ) ] [ outputAttribute . ordinal ( ) ] ++ ; } // Calculate the estimated probability distribution of G from the occurrence counts over the examples. double [ ] pForG = InformationTheory . pForDistribution ( outputCounts ) ; // Calculate the estimated probability distribution of A from the occurrence counts over the examples. double [ ] pForA = InformationTheory . pForDistribution ( inputCounts ) ; // Calculate the estimated probability distribution p(g|a) from the joint occurrence counts over the // examples. double [ ] [ ] pForGGivenA = InformationTheory . pForJointDistribution ( jointCounts ) ; // Calculate the information gain on G by knowing A. double gain = InformationTheory . gain ( pForG , pForA , pForGGivenA ) ; // Check if the gain is larger than the best found so far and update the best if so. if ( gain > largestGain ) { largestGain = gain ; largestGainProperty = inputProperty ; } } return largestGainProperty ; }


Input: Creates a functor . [CODESPLIT] public Functor functor ( String name , Term ... args ) { int internedName = interner . internFunctorName ( name , args . length ) ; return new Functor ( internedName , args ) ; }


Input: Creates an atom ( functor with no arguments ) . [CODESPLIT] public Functor atom ( String name ) { int internedName = interner . internFunctorName ( name , 0 ) ; return new Functor ( internedName , null ) ; }


Input: Creates a variable . If the variable name begins with an underscore _ it will be anonymous otherwise it will be named . [CODESPLIT] public Variable var ( String name ) { boolean isAnonymous = name . startsWith ( "_" ) ; int internedName = interner . internVariableName ( name ) ; return new Variable ( internedName , null , isAnonymous ) ; }


Input: Handles an HTTP request sent to this action by struts . This simply forwards to the location specified by the redirect request parameter . [CODESPLIT] public ActionForward executeWithErrorHandling ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response , ActionErrors errors ) { log . fine ( "public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form," + "HttpServletRequest request, HttpServletResponse response, " + "ActionErrors errors): called" ) ; HttpSession session = request . getSession ( ) ; DynaBean dynaForm = ( DynaActionForm ) form ; // Redirect to the specified location String redirect = ( String ) dynaForm . get ( REDIRECT ) ; log . fine ( "redirect = " + redirect ) ; return new ActionForward ( redirect , true ) ; }


Input:
Extracts the sub - list at the specified page index . The returned list will have size equal to the page size unless it is the last page in which case it may not be a full page . [CODESPLIT] public List < E > get ( int index ) { /*log.fine("public List<E> get(int index): called");*/ // Check that the index is not to large. int originalSize = original . size ( ) ; int size = ( originalSize / pageSize ) + ( ( ( originalSize % pageSize ) == 0 ) ? 0 : 1 ) ; /*log.fine("originalSize = " + originalSize);*/ /*log.fine("size = " + size);*/ // Check if the size of the underlying list is zero, in which case return an empty list, so long as page zero // was requested. if ( ( index == 0 ) && ( originalSize == 0 ) ) { return new ArrayList < E > ( ) ; } // Check if the requested index exceeds the number of pages, or is an illegal negative value. if ( ( index >= size ) || ( index < 0 ) ) { /*log.fine("(index >= size) || (index < 0), throwing out of bounds exception.");*/ throw new IndexOutOfBoundsException ( "Index " + index + " is less than zero or more than the number of pages: " + size ) ; } // Extract the appropriate sub-list. // Note that if this is the last page it may not be a full page. Just up to the last page will be returned. /*log.fine("Requesting sublist from, " + (pageSize * index) + ", to ," +
            (((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1))) + ".");*/ List < E > result = original . subList ( pageSize * index , ( ( pageSize * ( index + 1 ) ) >= originalSize ) ? originalSize : ( pageSize * ( index + 1 ) ) ) ; return result ; }


Input: { [CODESPLIT] protected void paintTrack ( Graphics g , JComponent c , Rectangle bounds ) { g . setColor ( colorScheme . getToolingBackground ( ) ) ; g . fillRect ( bounds . x , bounds . y , bounds . width , bounds . height ) ; }


Input: { [CODESPLIT] protected void paintThumb ( Graphics g , JComponent c , Rectangle thumbBounds ) { if ( thumbBounds . isEmpty ( ) || ! scrollbar . isEnabled ( ) ) { return ; } g . translate ( thumbBounds . x , thumbBounds . y ) ; boolean vertical = isVertical ( ) ; int hgap = vertical ? 2 : 1 ; int vgap = vertical ? 1 : 2 ; int w = thumbBounds . width - ( hgap * 2 ) ; int h = thumbBounds . height - ( vgap * 2 ) ; // leave one pixel between thumb and right or bottom edge if ( vertical ) { h -= 1 ; } else { w -= 1 ; } g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . fillRect ( hgap + 1 , vgap + 1 , w - 1 , h - 1 ) ; g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . drawRoundRect ( hgap , vgap , w , h , 3 , 3 ) ; g . translate ( - thumbBounds . x , - thumbBounds . y ) ; }


Input: { [CODESPLIT] protected Dimension getMinimumThumbSize ( ) { int thickness = THICKNESS ; return isVertical ( ) ? new Dimension ( thickness , thickness * 2 ) : new Dimension ( thickness * 2 , thickness ) ; }


Input: Sets the kind of paint to use . For the image background? [CODESPLIT] public void setTexture ( Paint obj ) { if ( obj instanceof GradientPaint ) { texture = new GradientPaint ( 0 , 0 , Color . white , getSize ( ) . width * 2 , 0 , Color . green ) ; } else { texture = obj ; } }


Input: Immediately repaints the surface . [CODESPLIT] public void paintImmediately ( int x , int y , int w , int h ) { RepaintManager repaintManager = null ; boolean save = true ; if ( ! isDoubleBuffered ( ) ) { repaintManager = RepaintManager . currentManager ( this ) ; save = repaintManager . isDoubleBufferingEnabled ( ) ; repaintManager . setDoubleBufferingEnabled ( false ) ; } super . paintImmediately ( x , y , w , h ) ; if ( repaintManager != null ) { repaintManager . setDoubleBufferingEnabled ( save ) ; } }


Input: Renders the surface . This method will create a buffered image to render in if one does not already exist . If rendering is to be done directly to the screen no buffered image will be generated . If the size of the buffered image does not match the Graphics context size then a new buffered image will be generated of the correct size before rendering . The { @link #render } method will be called to do the actual drawing . [CODESPLIT] public void paint ( Graphics g ) { // Get the size of the surface Dimension d = getSize ( ) ; // Check if direct to screen rendering is to be used if ( imageType == 1 ) { // Use no buffered image for direct rendering bimg = null ; } // Check if no buffered image has been created yet or if the existing one has the wrong size else if ( ( bimg == null ) || ( biw != d . width ) || ( bih != d . height ) ) { // Create a new bufferd image. Note that imageType has two subtracted for it as type 0 stands for auto // selection and type 1 for direct to screen. Subtracting two corresponds to the image types in the // BufferedImage class. bimg = createBufferedImage ( d . width , d . height , imageType - 2 ) ; // Set clear once flag to clear the new image on the first pass clearOnce = true ; } // Build a Graphics2D context for the image Graphics2D g2 = createGraphics2D ( d . width , d . height , bimg , g ) ; // Call the subclass to perform rendering render ( d . width , d . height , g2 ) ; // Clear up the Graphics2D context g2 . dispose ( ) ; // Check if a buffered image was used (and not direct to screen rendering) if ( bimg != null ) { // Copy the buffered image onto the screen g . drawImage ( bimg , 0 , 0 , null ) ; // Ensure screen is up to date toolkit . sync ( ) ; } }


Input: Generates a fresh buffered image of the appropriate type . [CODESPLIT] protected BufferedImage createBufferedImage ( int w , int h , int imgType ) { BufferedImage bi = null ; if ( imgType == 0 ) { bi = ( BufferedImage ) createImage ( w , h ) ; } else if ( ( imgType > 0 ) && ( imgType < 14 ) ) { bi = new BufferedImage ( w , h , imgType ) ; } else if ( imgType == 14 ) { bi = createBinaryImage ( w , h , 2 ) ; } else if ( imgType == 15 ) { bi = createBinaryImage ( w , h , 4 ) ; } else if ( imgType == 16 ) { bi = createSGISurface ( w , h , 32 ) ; } else if ( imgType == 17 ) { bi = createSGISurface ( w , h , 16 ) ; } // Store the buffered image size biw = w ; bih = h ; return bi ; }


Input: Creates a Graphics2D drawing context from a BufferedImage or Graphics context . The graphics context is built using the properties defined for the surface . This method is used to generate the Graphics2D context that subclasses will render in . IF the buffered image is null then the passed in Graphics context will be used to generate the Graphics2D context . This is the case when no buffered image is used and the subclass renders straight to the screen . [CODESPLIT] protected Graphics2D createGraphics2D ( int width , int height , BufferedImage bi , Graphics g ) { Graphics2D g2 = null ; // Check if the buffered image is null if ( bi != null ) { // Create Graphics2D context for the buffered image g2 = bi . createGraphics ( ) ; } else { // The buffered image is null so create Graphics2D context for the Graphics context g2 = ( Graphics2D ) g ; } // @todo what is this for? g2 . setBackground ( getBackground ( ) ) ; // Set the rendering properties of the graphics context g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , antiAlias ) ; g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , rendering ) ; // Check the clear flags to see if the graphics context should be cleared if ( clearSurface || clearOnce ) { // Clear the image g2 . clearRect ( 0 , 0 , width , height ) ; // Reset the clear once flag to show that clearing has been done clearOnce = false ; } // Check if a background fill texture is to be used if ( texture != null ) { // set composite to opaque for texture fills g2 . setComposite ( AlphaComposite . SrcOver ) ; g2 . setPaint ( texture ) ; g2 . fillRect ( 0 , 0 , width , height ) ; } // Check if alpha compositing is to be used if ( composite != null ) { // Set the alpha compositing algorithm g2 . setComposite ( composite ) ; } return g2 ; }


Input: Creates a custom grey - scale binary image format . [CODESPLIT] private BufferedImage createBinaryImage ( int w , int h , int pixelBits ) { int bytesPerRow = w * pixelBits / 8 ; if ( ( w * pixelBits % 8 ) != 0 ) { bytesPerRow ++ ; } byte [ ] imageData = new byte [ h * bytesPerRow ] ; IndexColorModel cm = null ; switch ( pixelBits ) { case 1 : { cm = new IndexColorModel ( pixelBits , lut1Arr . length , lut1Arr , lut1Arr , lut1Arr ) ; break ; } case 2 : { cm = new IndexColorModel ( pixelBits , lut2Arr . length , lut2Arr , lut2Arr , lut2Arr ) ; break ; } case 4 : { cm = new IndexColorModel ( pixelBits , lut4Arr . length , lut4Arr , lut4Arr , lut4Arr ) ; break ; } default : { new Exception ( "Invalid # of bit per pixel" ) . printStackTrace ( ) ; } } DataBuffer db = new DataBufferByte ( imageData , imageData . length ) ; WritableRaster r = Raster . createPackedRaster ( db , w , h , pixelBits , null ) ; return new BufferedImage ( cm , r , false , null ) ; }


Input: Creates a custom colour image format . [CODESPLIT] private BufferedImage createSGISurface ( int w , int h , int pixelBits ) { int rMask32 = 0xFF000000 ; int rMask16 = 0xF800 ; int gMask32 = 0x00FF0000 ; int gMask16 = 0x07C0 ; int bMask32 = 0x0000FF00 ; int bMask16 = 0x003E ; DirectColorModel dcm = null ; DataBuffer db = null ; WritableRaster wr = null ; switch ( pixelBits ) { case 16 : { short [ ] imageDataUShort = new short [ w * h ] ; dcm = new DirectColorModel ( 16 , rMask16 , gMask16 , bMask16 ) ; db = new DataBufferUShort ( imageDataUShort , imageDataUShort . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask16 , gMask16 , bMask16 } , null ) ; break ; } case 32 : { int [ ] imageDataInt = new int [ w * h ] ; dcm = new DirectColorModel ( 32 , rMask32 , gMask32 , bMask32 ) ; db = new DataBufferInt ( imageDataInt , imageDataInt . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask32 , gMask32 , bMask32 } , null ) ; break ; } default : { new Exception ( "Invalid # of bit per pixel" ) . printStackTrace ( ) ; } } return new BufferedImage ( dcm , wr , false , null ) ; }


Input: { [CODESPLIT] public void visit ( Predicate predicate ) { if ( traverser . isEnteringContext ( ) ) { initializePrinters ( ) ; } else if ( traverser . isLeavingContext ( ) ) { printTable ( ) ; } super . visit ( predicate ) ; }


Input: Workaround MockWebServer issue #11 . [CODESPLIT] public static RecordedRequest takeRequest ( MockWebServer server ) throws InterruptedException { RecordedRequest request = server . takeRequest ( ) ; while ( "GET /favicon.ico HTTP/1.1" . equals ( request . getRequestLine ( ) ) ) { request = server . takeRequest ( ) ; } return request ; }


Input: { [CODESPLIT] public boolean isValid ( EnumeratedStringAttribute value , ConstraintValidatorContext context ) { if ( value == null ) { return true ; } return value . getId ( ) != - 1 ; }


Input: <p > Handles requests that accept application / json . < / p > [CODESPLIT] @ RequestMapping ( value = { "/{schema:[^\\.]+}" , "/{schema}.json" } , produces = "application/json" , headers = { "Accept=application/json" } ) @ ResponseBody public Report processJsonRequest ( @ PathVariable String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { LOG . info ( "Processing JSON request for parameters " + request . getQueryString ( ) ) ; return processRequest ( schema , request ) ; }


Input: <p > Generic processor of all types of requests . < / p > <p > Validates schema availability mandatory fields for the specified schema and creates chains of { @link QueryParameterAware } to be processed by the underlying { @link GenericSchemaService } . < / p > [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private Report processRequest ( String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { long begin = System . currentTimeMillis ( ) ; SchemaDefinition config = schemaRepository . getStarSchemaConfig ( schema ) ; if ( config == null ) { LOG . warn ( "Invalid endpoint \"" + schema + "\"" ) ; throw new InvalidSchemaException ( "Invalid endpoint" ) ; } Map < String , String [ ] > params = request . getParameterMap ( ) ; for ( String mandatory : MANDATORY_FIELDS ) { if ( ! params . containsKey ( mandatory ) ) { // mandatory fields are case sensitive LOG . error ( "Mandatory field \"" + mandatory + "\" missing" ) ; throw new InvalidParameterException ( "Missing mandatory field " + mandatory ) ; } } QueryParameterEnvelope queryParameterDto = new QueryParameterEnvelope ( ) ; for ( String key : params . keySet ( ) ) { if ( DOMAIN_PARAMETERS . contains ( key ) ) { String domainParameter = params . get ( key ) [ 0 ] ; final DomainParserAware systemParameter = SystemParameter . valueOf ( key ) ; systemParameter . parseValue ( domainParameter , config , queryParameterDto ) ; } else { Pair < String , String > pair = splitKey ( key ) ; if ( ! config . isValidDimension ( pair . getLeft ( ) , pair . getRight ( ) ) ) { LOG . warn ( "Invalid parameter \"" + key + "\" for endpoint \"" + schema + "\"." ) ; throw new InvalidParameterException ( "Invalid parameter " + key + " for endpoint " + schema + "" ) ; } String [ ] multiParam = request . getParameterValues ( key ) ; for ( String param : multiParam ) { queryParameterDto . addConstraints ( new HttpQueryConstraint ( config , key , param ) ) ; } } } final Report report = schemaService . generateReport ( config , queryParameterDto ) ; report . setRecords ( inMemoryPagination ( report . getRecords ( ) , queryParameterDto ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Query successfully processed for schema " + schema + " in " + ( System . currentTimeMillis ( ) - begin ) + "s." ) ; } return report ; }


Input: <p > Handles { @link ServiceException } generated by the underlying layer . < / p > [CODESPLIT] @ ExceptionHandler ( ServiceException . class ) @ ResponseBody public ResponseEntity < String > handleServiceException ( ServiceException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . INTERNAL_SERVER_ERROR ) ; }


Input: <p > Handles { @link InvalidParameterException } generated by the controller itself when receives an invalid parameter . < / p > [CODESPLIT] @ ExceptionHandler ( InvalidParameterException . class ) @ ResponseBody public ResponseEntity < String > handleControllerException ( InvalidParameterException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . BAD_REQUEST ) ; }


Input: <p > Handles { @link InvalidSchemaException } generated by the controller itself when receives a request to a non existing schema configuration . < / p > [CODESPLIT] @ ExceptionHandler ( InvalidSchemaException . class ) @ ResponseBody public ResponseEntity < String > handleInvalidSchemaException ( InvalidSchemaException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . NOT_FOUND ) ; }


Input: <p > Creates a { @link Pair } composed of Dimension and Information required by the { @link GenericSchemaService } . < / p > [CODESPLIT] private static Pair < String , String > splitKey ( String key ) { String dimension = null ; String info = null ; if ( ! key . contains ( "." ) ) { dimension = key ; } else { dimension = key . substring ( 0 , key . indexOf ( ' ' ) ) ; info = key . substring ( key . indexOf ( ' ' ) + 1 , key . length ( ) ) ; } return Pair . of ( dimension , info ) ; }


Input: TODO to be removed [CODESPLIT] private List < ReportRecord > inMemoryPagination ( final List < ReportRecord > recordList , QueryParameterEnvelope queryParameterEnvelope ) { final QueryParameterAware pageSize = queryParameterEnvelope . getPageSize ( ) ; final QueryParameterAware pageNumber = queryParameterEnvelope . getPageNumber ( ) ; if ( pageSize != null && pageNumber != null ) { final Integer pageSizeValue = ( ( PageSizeConstraint ) pageSize ) . getPageSizeValue ( ) ; final Integer pageValue = ( ( PageNumberConstraint ) pageNumber ) . getPageNumberValue ( ) - 1 ; int offset = pageValue * pageSizeValue ; return recordList . subList ( offset > recordList . size ( ) ? recordList . size ( ) : offset , offset + pageSizeValue > recordList . size ( ) ? recordList . size ( ) : offset + pageSizeValue ) ; } return recordList ; }


Input: { [CODESPLIT] public void restore ( ) { boolean foundSavePoint = false ; while ( ! foundSavePoint && ! undoStack . isEmpty ( ) ) { Undoable undoable = undoStack . poll ( ) ; undoable . undo ( ) ; foundSavePoint = ( undoable instanceof SavePoint ) ; } }


Input: Checks if the give column exist ( by name ) [CODESPLIT] public final boolean containsColumn ( String columnName ) { if ( StringUtils . isNotBlank ( columnName ) ) { return sqlTableColumns . containsKey ( columnName ) ; } return false ; }


Input: { [CODESPLIT] protected void enterClause ( Clause clause ) { if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + ":" ) : "" ) ; nextRow ( ) ; } } }


Input: { [CODESPLIT] protected void enterPredicate ( Predicate predicate ) { if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + ":" ) : "" ) ; nextRow ( ) ; } } }


Input: Allows different queue search algorithms to replace the default one . This overidden method ensures that the peek at head flag is always set on the search algorithm and that it expands it successor nodes in reverse as for depth first searches . [CODESPLIT] protected void setQueueSearchAlgorithm ( QueueSearchAlgorithm < O , T > algorithm ) { algorithm . setPeekAtHead ( true ) ; algorithm . setReverseEnqueueOrder ( true ) ; super . setQueueSearchAlgorithm ( algorithm ) ; }


Input: Search iteratively on increasing maximum bound limits until the search space is exhausted or a goal state is found . [CODESPLIT] public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Iteratively increase the bound until a search succeeds. for ( float bound = startBound ; ; ) { // Set up the maximum bound for this iteration. maxBound = bound ; // Use a try block as the depth bounded search will throw a MaxBoundException if it fails but there // are successors states known to exist beyond the current max depth fringe. try { // Get the number of search steps taken so far and pass this into the underlying depth bounded search // so that the step count limit carries over between successive iterations. int numStepsSoFar = initSearch . getStepsTaken ( ) ; // Call the super class search method to perform a depth bounded search on this maximum bound starting // from the initial search state. initSearch . resetEnqueuedOnceFlag ( ) ; SearchNode node = super . search ( initSearch , startStates , maxSteps , numStepsSoFar ) ; // Check if the current depth found a goal node if ( node != null ) { return node ; } // The depth bounded search returned null, so it has exhausted the search space. Return with null. else { return null ; } } // The depth bounded search failed but it knows that there are more successor states at deeper levels. catch ( MaxBoundException e ) { // Do nothing, no node found at this depth so continue at the next depth level e = null ; } // Check if the bound should be increased by epsilon or to the next smallest bound property value // beyond the fringe and update the bound for the next iteration. if ( useEpsilon ) { bound = bound + epsilon ; } else { bound = getMinBeyondBound ( ) ; } } }


Input: { @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the left position. grid = componentFactory . createTextGrid ( ) ; grid . insertVerticalSeparator ( 9 , 10 ) ; grid . insertVerticalSeparator ( 17 , 10 ) ; grid . insertVerticalSeparator ( 26 , 10 ) ; mainWindow . showConsole ( componentFactory . createTextGridPanel ( grid ) ) ; // Build a table model on the text grid, and construct a register monitor on the table. table = ( EnhancedTextTable ) grid . createTable ( 0 , 0 , 20 , 20 ) ; monitor = new MemoryLayoutMonitor ( table ) ; // Attach a listener for updates to the register table. table . addTextTableListener ( new TableUpdateHandler ( ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getRelWhenAnchorReturnsRelationship ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "x" ) . getRel ( ) ; assertThat ( "link rel" , actual , is ( "x" ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getHrefWhenAnchorAndAbsoluteHrefReturnsUrl ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "r" ) . getHref ( ) ; assertThat ( "link href" , actual , is ( new URL ( "http://x/" ) ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void followWhenAnchorSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "a" + "" ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "r" ) . follow ( ) ; server ( ) . takeRequest ( ) ; assertThat ( "request" , takeRequest ( server ( ) ) . getPath ( ) , is ( "/x" ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; Link link = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "x" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; link . unwrap ( Void . class ) ; }