Input: Search until a goal state is found or the maximum allowed number of steps is reached . [CODESPLIT] public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Initialize the queue with the start states set up in search nodes if this has not already been done. // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is // done. Subsequent searches continue from where the previous search left off. Have to call reset on // the search method to really start the search again from the start states. Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process. UnaryPredicate < T > goalPredicate = initSearch . getGoalPredicate ( ) ; // Keep running until the queue becomes empty or a goal state is found. while ( ! queue . isEmpty ( ) ) { // Extract or peek at the head element from the queue. SearchNode < O , T > headNode = peekAtHead ? queue . peek ( ) : queue . remove ( ) ; // Expand the successors into the queue whether the current node is a goal state or not. // This prepares the queue for subsequent searches, ensuring that goal states do not block // subsequent goal states that exist beyond them. if ( ! headNode . isExpanded ( ) ) { headNode . expandSuccessors ( queue , reverseEnqueue ) ; } // Get the node to be goal checked, either the head node or the new top of queue, depending on the // peek at head flag. Again this is only a peek, the node is only to be removed if it is to be // goal checked. SearchNode < O , T > currentNode = peekAtHead ? queue . peek ( ) : headNode ; // Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway). if ( currentNode . isExpanded ( ) ) { // If required, remove the node to goal check from the queue. currentNode = peekAtHead ? queue . remove ( ) : headNode ; // Check if the current node is a goal state. if ( goalPredicate . evaluate ( currentNode . getState ( ) ) ) { return currentNode ; } } // Check if there is a maximum number of steps limit and increase the step count and check the limit if so. if ( maxSteps > 0 ) { searchSteps ++ ; // Update the search state with the number of steps taken so far. initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached, however if the queue is now empty then the search // has just completed within the maximum. Check if the queue is empty and return null if so. if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still // more states in the queue then raise a search failure exception. else { throw new SearchNotExhaustiveException ( "Maximum number of steps reached." , null ) ; } } } } // No goal state was found so return null return null ; }


Input: { @inheritDoc } [CODESPLIT] public void reset ( ) { // Reset the resolver to completely clear out its domain. resolver . reset ( ) ; // Create a token source to load the model rules from. Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( WAMEngine . class . getClassLoader ( ) . getResourceAsStream ( BUILT_IN_LIB ) ) ; // Set up a parser on the token source. Parser < Clause , Token > libParser = new SentenceParser ( interner ) ; libParser . setTokenSource ( tokenSource ) ; // Load the built-ins into the domain. try { while ( true ) { Sentence < Clause > sentence = libParser . parse ( ) ; if ( sentence == null ) { break ; } compiler . compile ( sentence ) ; } compiler . endScope ( ) ; } catch ( SourceCodeException e ) { // There should not be any errors in the built in library, if there are then the prolog engine just // isn't going to work, so report this as a bug. throw new IllegalStateException ( "Got an exception whilst loading the built-in library." , e ) ; } }


Input: Parses statements and print the parse tree to the console for quick interactive testing of the parser . [CODESPLIT] public static void main ( String [ ] args ) { try { SimpleCharStream inputStream = new SimpleCharStream ( System . in , null , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; Source < Token > tokenSource = new TokenSource ( tokenManager ) ; PrologParser parser = new PrologParser ( tokenSource , new VariableAndFunctorInternerImpl ( "Prolog_Variable_Namespace" , "Prolog_Functor_Namespace" ) ) ; while ( true ) { // Parse the next sentence or directive. Object nextParsing = parser . clause ( ) ; console . info ( nextParsing . toString ( ) ) ; } } catch ( Exception e ) { console . log ( Level . SEVERE , e . getMessage ( ) , e ) ; System . exit ( 1 ) ; } }


Input: Parses many consecutive sentences until an <EOF > is reached . This method is intended to aid with consulting files . [CODESPLIT] public List < Clause > sentences ( ) throws SourceCodeException { List < Clause > results = new LinkedList < Clause > ( ) ; // Loop consuming clauses until end of file is encounterd. while ( true ) { if ( peekAndConsumeEof ( ) ) { break ; } else { results . add ( sentence ( ) ) ; } } return results ; }


Input: Parses a single sentence in first order logic . A sentence consists of a term followed by a full stop . [CODESPLIT] public Clause clause ( ) throws SourceCodeException { // Each new sentence provides a new scope in which to make variables unique. variableContext . clear ( ) ; Term term = term ( ) ; Clause clause = TermUtils . convertToClause ( term , interner ) ; if ( clause == null ) { throw new SourceCodeException ( "Only queries and clauses are valid sentences in Prolog, not " + term + "." , null , null , null , term . getSourceCodePosition ( ) ) ; } return clause ; }


Input: Parses multiple sequential terms and if more than one is encountered then the flat list of terms encountered must contain operators in order to be valid Prolog syntax . In that case the flat list of terms is passed to the { @link DynamicOperatorParser#parseOperators ( Term [] ) } method for deferred decision parsing of dynamic operators . [CODESPLIT] public Term term ( ) throws SourceCodeException { List < Term > terms ; terms = terms ( new LinkedList < Term > ( ) ) ; Term [ ] flatTerms = terms . toArray ( new Term [ terms . size ( ) ] ) ; if ( flatTerms . length > 1 ) { return operatorParser . parseOperators ( flatTerms ) ; } else { Term result = flatTerms [ 0 ] ; // If a single candidate op symbol has been parsed, promote it to a constant. if ( result instanceof CandidateOpSymbol ) { CandidateOpSymbol candidate = ( CandidateOpSymbol ) result ; int nameId = interner . internFunctorName ( candidate . getTextName ( ) , 0 ) ; result = new Functor ( nameId , null ) ; } return result ; } }


Input: Recursively parses terms which may be functors atoms variables literals or operators into a flat list in the order in which they are encountered . [CODESPLIT] public List < Term > terms ( List < Term > terms ) throws SourceCodeException { Term term ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case FUNCTOR : term = functor ( ) ; break ; case LSQPAREN : term = listFunctor ( ) ; break ; case VAR : term = variable ( ) ; break ; case INTEGER_LITERAL : term = intLiteral ( ) ; break ; case FLOATING_POINT_LITERAL : term = doubleLiteral ( ) ; break ; case STRING_LITERAL : term = stringLiteral ( ) ; break ; case ATOM : term = atom ( ) ; break ; case LPAREN : consumeToken ( LPAREN ) ; term = term ( ) ; // Mark the term as bracketed to ensure that this is its final parsed form. In particular the // #arglist method will not break it up if it contains commas. term . setBracketed ( true ) ; consumeToken ( RPAREN ) ; break ; default : throw new SourceCodeException ( "Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } terms . add ( term ) ; switch ( tokenSource . peek ( ) . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : terms ( terms ) ; break ; default : } return terms ; }


Input: Parses a single atom in first order logic . If the operator has been set up which has the same name as the atom then the atom may actually be a functor expressed as a prefix postfix or infix operator . If this is the case the value returned by this method will be a { @link CandidateOpSymbol } . Otherwise it will be a { @link Functor } of arity zero . [CODESPLIT] public Term atom ( ) throws SourceCodeException { Token name = consumeToken ( ATOM ) ; Term result ; // Used to build the possible set of operators that this symbol could be parsed as. EnumMap < OpSymbol . Fixity , OpSymbol > possibleOperators = operatorTable . getOperatorsMatchingNameByFixity ( name . image ) ; // Check if the symbol mapped onto any candidate operators and if not create a constant for it. if ( ( possibleOperators == null ) || possibleOperators . isEmpty ( ) ) { int nameId = interner . internFunctorName ( name . image , 0 ) ; result = new Functor ( nameId , null ) ; } else { // Set the possible associativities of the operator on the candidate. result = new CandidateOpSymbol ( name . image , possibleOperators ) ; } // Set the position that the name was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }


Input: Parses a single functor in first order logic with its arguments . [CODESPLIT] public Term functor ( ) throws SourceCodeException { Token name = consumeToken ( FUNCTOR ) ; Term [ ] args = arglist ( ) ; consumeToken ( RPAREN ) ; int nameId = interner . internFunctorName ( ( args == null ) ? name . image : name . image . substring ( 0 , name . image . length ( ) - 1 ) , ( args == null ) ? 0 : args . length ) ; Functor result = new Functor ( nameId , args ) ; SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }


Input: Parses a list expressed as a sequence of functors in first order logic . The empty list consists of the atom nil and a non - empty list consists of the functor cons with arguments the head of the list and the remainder of the list . [CODESPLIT] public Term listFunctor ( ) throws SourceCodeException { // Get the interned names of the nil and cons functors. int nilId = interner . internFunctorName ( "nil" , 0 ) ; int consId = interner . internFunctorName ( "cons" , 2 ) ; // A list always starts with a '['. Token leftDelim = consumeToken ( LSQPAREN ) ; // Check if the list contains any arguments and parse them if so. Term [ ] args = null ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : args = arglist ( ) ; break ; default : } // Work out what the terminal element in the list is. It will be 'nil' unless an explicit cons '|' has // been used to specify a different terminal element. In the case where cons is used explciitly, the // list prior to the cons must not be empty. Term accumulator ; if ( tokenSource . peek ( ) . kind == CONS ) { if ( args == null ) { throw new SourceCodeException ( "Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } consumeToken ( CONS ) ; accumulator = term ( ) ; } else { accumulator = new Nil ( nilId , null ) ; } // A list is always terminated with a ']'. Token rightDelim = consumeToken ( RSQPAREN ) ; // Walk down all of the lists arguments joining them together with cons/2 functors. if ( args != null ) // 'args' will contain one or more elements if not null. { for ( int i = args . length - 1 ; i >= 0 ; i -- ) { Term previousAccumulator = accumulator ; //accumulator = new Functor(consId.ordinal(), new Term[] { args[i], previousAccumulator }); accumulator = new Cons ( consId , new Term [ ] { args [ i ] , previousAccumulator } ) ; } } // Set the position that the list was parsed from, as being the region between the '[' and ']' brackets. SourceCodePosition position = new SourceCodePositionImpl ( leftDelim . beginLine , leftDelim . beginColumn , rightDelim . endLine , rightDelim . endColumn ) ; accumulator . setSourceCodePosition ( position ) ; // The cast must succeed because arglist must return at least one argument, therefore the cons generating // loop must have been run at least once. If arglist is not called at all because an empty list was // encountered, then the accumulator will contain the 'nil' constant which is a functor of arity zero. return ( Functor ) accumulator ; }


Input: Parses a sequence of terms as a comma seperated argument list . The operator in prolog can be used as an operator when it behaves as a functor of arity 2 or it can be used to separate a sequence of terms that are arguments to a functor or list . The sequence of functors must first be parsed as a term using the operator precedence of to form the term . This method takes such a term and flattens it back into a list of terms breaking it only on a sequence of commas . Terms that have been parsed as a bracketed expression will not be broken up . [CODESPLIT] public Term [ ] arglist ( ) throws SourceCodeException { Term term = term ( ) ; List < Term > result = TermUtils . flattenTerm ( term , Term . class , "," , interner ) ; return result . toArray ( new Term [ result . size ( ) ] ) ; }


Input: Parses a variable in first order logic . Variables are scoped within the current sentence being parsed so if the variable has been seen previously in the sentence it is returned rather than a new one being created . [CODESPLIT] public Term variable ( ) throws SourceCodeException { Token name = consumeToken ( VAR ) ; // Intern the variables name. int nameId = interner . internVariableName ( name . image ) ; // Check if the variable already exists in this scope, or create a new one if it does not. // If the variable is the unidentified anonymous variable '_', a fresh one will always be created. Variable var = null ; if ( ! "_" . equals ( name . image ) ) { var = variableContext . get ( nameId ) ; } if ( var != null ) { return var ; } else { var = new Variable ( nameId , null , name . image . equals ( "_" ) ) ; variableContext . put ( nameId , var ) ; return var ; } }


Input: Parses an integer literal . [CODESPLIT] public Term intLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( INTEGER_LITERAL ) ; NumericType result = new IntLiteral ( Integer . parseInt ( valToken . image ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }


Input: Parses a real number literal . [CODESPLIT] public Term doubleLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( FLOATING_POINT_LITERAL ) ; NumericType result = new DoubleLiteral ( Double . parseDouble ( valToken . image ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }


Input: Parses a string literal . [CODESPLIT] public Term stringLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( STRING_LITERAL ) ; String valWithQuotes = valToken . image ; StringLiteral result = new StringLiteral ( valWithQuotes . substring ( 1 , valWithQuotes . length ( ) - 1 ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }


Input: Peeks at the next token to see if it is an { @link #ATOM } which is equal to ; and if it is consumes it . If the symbol is consumed then the return value indicates that this has happened . This is intended to be usefull for interactive interpreters when querying the user to see if they want more solutions to be found . [CODESPLIT] public boolean peekAndConsumeMore ( ) { Token nextToken = tokenSource . peek ( ) ; if ( ( nextToken . kind == ATOM ) && ";" . equals ( nextToken . image ) ) { try { consumeToken ( ATOM ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this // as a bug rather than try to recover from it. throw new IllegalStateException ( e ) ; } return true ; } else { return false ; } }


Input: Peeks and consumes the next interactive system directive . [CODESPLIT] public Directive peekAndConsumeDirective ( ) throws SourceCodeException { if ( peekAndConsumeTrace ( ) ) { return Directive . Trace ; } if ( peekAndConsumeInfo ( ) ) { return Directive . Info ; } if ( peekAndConsumeUser ( ) ) { return Directive . User ; } return null ; }


Input: Interns an operators name as a functor of appropriate arity for the operators fixity and sets the operator in the operator table . [CODESPLIT] public void internOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { int arity ; if ( ( associativity == XFY ) | ( associativity == YFX ) | ( associativity == XFX ) ) { arity = 2 ; } else { arity = 1 ; } int name = interner . internFunctorName ( operatorName , arity ) ; operatorTable . setOperator ( name , operatorName , priority , associativity ) ; }


Input: Interns and inserts into the operator table all of the built in operators and functors in Prolog . [CODESPLIT] protected void initializeBuiltIns ( ) { // Initializes the operator table with the standard ISO prolog built-in operators. internOperator ( ":-" , 1200 , XFX ) ; internOperator ( ":-" , 1200 , FX ) ; internOperator ( "-->" , 1200 , XFX ) ; internOperator ( "?-" , 1200 , FX ) ; internOperator ( ";" , 1100 , XFY ) ; internOperator ( "->" , 1050 , XFY ) ; internOperator ( "," , 1000 , XFY ) ; internOperator ( "\\+" , 900 , FY ) ; internOperator ( "=" , 700 , XFX ) ; internOperator ( "\\=" , 700 , XFX ) ; internOperator ( "==" , 700 , XFX ) ; internOperator ( "\\==" , 700 , XFX ) ; internOperator ( "@<" , 700 , XFX ) ; internOperator ( "@=<" , 700 , XFX ) ; internOperator ( "@>" , 700 , XFX ) ; internOperator ( "@>=" , 700 , XFX ) ; internOperator ( "=.." , 700 , XFX ) ; internOperator ( "is" , 700 , XFX ) ; internOperator ( "=:=" , 700 , XFX ) ; internOperator ( "=\\=" , 700 , XFX ) ; internOperator ( "<" , 700 , XFX ) ; internOperator ( "=<" , 700 , XFX ) ; internOperator ( ">" , 700 , XFX ) ; internOperator ( ">=" , 700 , XFX ) ; internOperator ( "+" , 500 , YFX ) ; internOperator ( "-" , 500 , YFX ) ; internOperator ( "\\/" , 500 , YFX ) ; internOperator ( "/\\" , 500 , YFX ) ; internOperator ( "/" , 400 , YFX ) ; internOperator ( "//" , 400 , YFX ) ; internOperator ( "*" , 400 , YFX ) ; internOperator ( ">>" , 400 , YFX ) ; internOperator ( "<<" , 400 , YFX ) ; internOperator ( "rem" , 400 , YFX ) ; internOperator ( "mod" , 400 , YFX ) ; internOperator ( "-" , 200 , FY ) ; internOperator ( "^" , 200 , YFX ) ; internOperator ( "**" , 200 , YFX ) ; internOperator ( "\\" , 200 , FY ) ; // Intern all built in functors. interner . internFunctorName ( "nil" , 0 ) ; interner . internFunctorName ( "cons" , 2 ) ; interner . internFunctorName ( "true" , 0 ) ; interner . internFunctorName ( "fail" , 0 ) ; interner . internFunctorName ( "!" , 0 ) ; }


Input: Consumes a token of the expected kind from the token sequence . If the next token in the sequence is not of the expected kind an error will be raised . [CODESPLIT] protected Token consumeToken ( int kind ) throws SourceCodeException { Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind != kind ) { throw new SourceCodeException ( "Was expecting " + tokenImage [ kind ] + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } else { nextToken = tokenSource . poll ( ) ; return nextToken ; } }


Input: Peeks ahead for the given token type and if one is foudn with that type it is consumed . [CODESPLIT] private boolean peekAndConsume ( int kind ) { Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind == kind ) { try { consumeToken ( kind ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this // as a bug rather than try to recover from it. throw new IllegalStateException ( e ) ; } return true ; } else { return false ; } }


Input: Binds the session as a transactional context to the current thread if it is not already bound . [CODESPLIT] public void bind ( ) { // If necessary create a fresh transaction id. if ( ( txId == null ) || ! txId . isValid ( ) ) { txId = TxManager . createTxId ( ) ; } // Bind the transaction to the current thread. TxManager . assignTxIdToThread ( txId ) ; // Bind this session to the current thread. threadSession . set ( this ) ; }


Input: Forgets pending operations . [CODESPLIT] public void rollback ( ) { // Rollback all soft resources. for ( Transactional enlist : enlists ) { enlist . rollback ( ) ; } // Clear all of the rolled back resources. enlists . clear ( ) ; // Invalidate the transaction id, so that a fresh transaction is begun. txId = TxManager . removeTxIdFromThread ( ) ; TxManager . invalidateTxId ( txId ) ; bind ( ) ; }


Input: Extracts all elements from an iterator usually created from a filterator and adds them into the target collection returning that collection as the result . [CODESPLIT] public static < T > Collection < T > collectIterator ( Iterator < T > iterator , Collection < T > targetCollection ) { while ( iterator . hasNext ( ) ) { targetCollection . add ( iterator . next ( ) ) ; } return targetCollection ; }


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


Input: Reserves a call point for a block of named callable code . The size of the block of code must be known fully in advance . If the named block already has a call point this will replace it with a new one . [CODESPLIT] public CallPoint reserveCallPoint ( int name , int length ) { // Work out where the code will go and advance the insertion point beyond its end, so that additional code // will be added beyond the reserved space. int address = getCodeInsertionPoint ( ) ; advanceCodeInsertionPoint ( length ) ; // Create a call point for the reserved space. CallPoint callPoint = new CallPoint ( address , length , name ) ; // Add the call point to the symbol table under the interned name. symbolTable . put ( name , getCallPointSymbolField ( ) , callPoint ) ; return callPoint ; }


Input: Converts a field by field timestamp into millisecond ticks . [CODESPLIT] public static long timestampToTicks ( int year , int month , int day , int hours , int minutes , int seconds , int milliseconds ) { boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; long hoursComponent = ( long ) hours * MILLIS_PER_HOUR ; long minutesComponent = ( long ) minutes * MILLIS_PER_MINUTE ; long secondsComponent = ( long ) seconds * MILLIS_PER_SECOND ; return dayComponent + monthComponent + yearComponent + hoursComponent + minutesComponent + secondsComponent + milliseconds ; }


Input: Converts a field by field timestamp into millisecond ticks . [CODESPLIT] public static long timestampToTicks ( int year , int month , int day ) { boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; return dayComponent + monthComponent + yearComponent ; }


Input: Converts a field by field time of day into millisecond ticks . [CODESPLIT] public static long timeOfDayToTicks ( int hour , int minute , int second , int millisecond ) { return millisecond + ( MILLIS_PER_SECOND * second ) + ( MILLIS_PER_MINUTE * minute ) + ( MILLIS_PER_HOUR * hour ) ; }


Input: Extracts the years component of a time in millisecond ticks . [CODESPLIT] public static int ticksToYears ( long ticks ) { // The number of years is ticks floor divided by number of milliseconds in 365 1/4 days. //return flooredDiv(ticks, MILLIS_PER_REAL_YEAR) + 1970; //return flooredDiv(ticks + ((long)DAYS_TO_1970 * MILLIS_PER_DAY), MILLIS_PER_REAL_YEAR); long unitMillis = MILLIS_PER_YEAR / 2 ; long i2 = ( ticks >> 1 ) + ( ( 1970L * MILLIS_PER_YEAR ) / 2 ) ; if ( i2 < 0 ) { i2 = i2 - unitMillis + 1 ; } int year = ( int ) ( i2 / unitMillis ) ; long yearStart = millisToYearStart ( year ) ; long diff = ticks - yearStart ; if ( diff < 0 ) { year -- ; } else if ( diff >= ( MILLIS_PER_DAY * 365L ) ) { // One year may need to be added to fix estimate. long oneYear ; if ( isLeapYear ( year ) ) { oneYear = MILLIS_PER_DAY * 366L ; } else { oneYear = MILLIS_PER_DAY * 365L ; } yearStart += oneYear ; if ( yearStart <= ticks ) { year ++ ; } } return year ; }


Input: Extracts the date ( day in month ) component of a time in millisecond ticks . [CODESPLIT] public static int ticksToDate ( long ticks ) { int year = ticksToYears ( ticks ) ; int month = ticksToMonths ( ticks ) ; long dayOffset = ticks ; dayOffset -= millisToYearStart ( year ) ; dayOffset -= isLeapYear ( year ) ? ( ( long ) LEAP_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) : ( ( long ) USUAL_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) ; return ( int ) ( dayOffset / MILLIS_PER_DAY ) + 1 ; }


Input: Sets the component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithHoursSetTo ( long ticks , int hours ) { long oldHours = ticksToHours ( ticks ) ; return ticks - ( oldHours * MILLIS_PER_HOUR ) + ( hours * MILLIS_PER_HOUR ) ; }


Input: Sets the minutes component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithMinutesSetTo ( long ticks , int minutes ) { long oldMinutes = ticksToMinutes ( ticks ) ; return ticks - ( oldMinutes * MILLIS_PER_MINUTE ) + ( minutes * MILLIS_PER_MINUTE ) ; }


Input: Sets the seconds component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithSecondsSetTo ( long ticks , int seconds ) { long oldSeconds = ticksToSeconds ( ticks ) ; return ticks - ( oldSeconds * MILLIS_PER_SECOND ) + ( seconds * MILLIS_PER_SECOND ) ; }


Input: Sets the year component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithYearSetTo ( long ticks , int year ) { int oldYear = ticksToYears ( ticks ) ; return ticks - millisToYearStart ( oldYear ) + millisToYearStart ( year ) ; }


Input: Sets the month component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithMonthSetTo ( long ticks , int month ) { int year = ticksToYears ( ticks ) ; boolean isLeapYear = isLeapYear ( year ) ; int oldMonth = ticksToMonths ( ticks ) ; return ticks - millisToStartOfMonth ( oldMonth , isLeapYear ) + millisToStartOfMonth ( month , isLeapYear ) ; }


Input: Sets the date component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithDateSetTo ( long ticks , int date ) { int oldDays = ticksToDate ( ticks ) ; return ticks - ( oldDays * MILLIS_PER_DAY ) + ( date * MILLIS_PER_DAY ) ; }


Input: Calculates the number of milliseconds to the start of the specified year taking 1970 as zero . [CODESPLIT] public static long millisToYearStart ( int year ) { // Calculate how many leap years elapsed prior to the year in question. int leapYears = year / 100 ; if ( year < 0 ) { leapYears = ( ( year + 3 ) >> 2 ) - leapYears + ( ( leapYears + 3 ) >> 2 ) - 1 ; } else { leapYears = ( year >> 2 ) - leapYears + ( leapYears >> 2 ) ; if ( isLeapYear ( year ) ) { leapYears -- ; } } return ( ( year * 365L ) + leapYears - DAYS_TO_1970 ) * MILLIS_PER_DAY ; }


Input: Writes a time of day with milliseconds in the format HH : MM : SS [ . sss ] into a byte buffer . The specified buffer will be enlarged if necessary using the specified byte buffer pool . [CODESPLIT] public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value ) { buffer = putTimeOnlyAsString ( buffer , value , true ) ; return buffer ; }


Input: Writes only the time component of a time of day timestamp to a byte array in the following format : HH : MM : SS [ . sss ] . The millisecond value is optional and is only written if requested . If there is insufficient space in the buffer to write the value into then the buffer size is increased using the supplied byte buffer pool . [CODESPLIT] public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value , boolean includeMilliseconds ) { // Ensure there is sufficient space in the buffer for the date. int charsRequired = includeMilliseconds ? TIME_ONLY_LENGTH_WITH_MILLISECONDS : TIME_ONLY_LENGTH_WIHTOUT_MILLISECONDS ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToHours ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMinutes ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToSeconds ( value ) , 2 ) ; if ( includeMilliseconds ) { buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMilliseconds ( value ) , 3 ) ; } return buffer ; }


Input: Given a millisecond timestamp that lands in a specified year calculate what month the timestamp corresponds to . [CODESPLIT] private static int getMonthOfYear ( long ticks , int year ) { int i = ( int ) ( ( ticks - millisToYearStart ( year ) ) >> 10 ) ; return ( isLeapYear ( year ) ) ? ( ( i < ( 182 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 91 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 31 * MILLIS_PER_DAY_OVER_1024 ) ) ? 1 : ( ( i < ( 60 * MILLIS_PER_DAY_OVER_1024 ) ) ? 2 : 3 ) ) : ( ( i < ( 121 * MILLIS_PER_DAY_OVER_1024 ) ) ? 4 : ( ( i < ( 152 * MILLIS_PER_DAY_OVER_1024 ) ) ? 5 : 6 ) ) ) : ( ( i < ( 274 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 213 * MILLIS_PER_DAY_OVER_1024 ) ) ? 7 : ( ( i < ( 244 * MILLIS_PER_DAY_OVER_1024 ) ) ? 8 : 9 ) ) : ( ( i < ( 305 * MILLIS_PER_DAY_OVER_1024 ) ) ? 10 : ( ( i < ( 335 * MILLIS_PER_DAY_OVER_1024 ) ) ? 11 : 12 ) ) ) ) : ( ( i < ( 181 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 90 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 31 * MILLIS_PER_DAY_OVER_1024 ) ) ? 1 : ( ( i < ( 59 * MILLIS_PER_DAY_OVER_1024 ) ) ? 2 : 3 ) ) : ( ( i < ( 120 * MILLIS_PER_DAY_OVER_1024 ) ) ? 4 : ( ( i < ( 151 * MILLIS_PER_DAY_OVER_1024 ) ) ? 5 : 6 ) ) ) : ( ( i < ( 273 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 212 * MILLIS_PER_DAY_OVER_1024 ) ) ? 7 : ( ( i < ( 243 * MILLIS_PER_DAY_OVER_1024 ) ) ? 8 : 9 ) ) : ( ( i < ( 304 * MILLIS_PER_DAY_OVER_1024 ) ) ? 10 : ( ( i < ( 334 * MILLIS_PER_DAY_OVER_1024 ) ) ? 11 : 12 ) ) ) ) ; }


Input: Reads some number of bytes from the input stream and stores them into the buffer array b . The bytes are also returned wrapped in a byte block so that they can be returnd over RMI . [CODESPLIT] public ByteBlock read ( byte [ ] b ) throws IOException { int count = source . read ( b ) ; return new ByteBlock ( b , count ) ; }


Input: Reads up to len bytes of data from the input stream into an array of bytes . [CODESPLIT] public ByteBlock read ( byte [ ] b , int off , int len ) throws IOException { int count = source . read ( b , off , len ) ; return new ByteBlock ( b , count ) ; }


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


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


Input: { [CODESPLIT] public void clear ( ) { count = 0 ; nextSequenceNumber = 0 ; hashTable = ( Entry < K > [ ] ) new Entry [ hashTableSize ] ; length = hashTable . length ; }


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


Input: Checks if the specified key can be found in the set and returns its entry if so . [CODESPLIT] private Entry < K > entryForKey ( K key ) { int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; Entry < K > entry = hashTable [ indexFor ( hash1 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } int hash2 = hash2 ( hash1 , keyHashCode ) ; entry = hashTable [ indexFor ( hash2 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } return null ; }


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


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


Input: Implements Robert Jenkins 32 - bit integer hash function . <a href = http : // www . concentric . net / ~Ttwang / tech / inthash . htm / > http : // www . concentric . net / ~Ttwang / tech / inthash . htm< / a > [CODESPLIT] private int hash1 ( int key ) { key += hash1seed ; key = ( key + 0x7ed55d16 ) + ( key << 12 ) ; key = ( key ^ 0xc761c23c ) ^ ( key >> 19 ) ; key = ( key + 0x165667b1 ) + ( key << 5 ) ; key = ( key + 0xd3a2646c ) ^ ( key << 9 ) ; key = ( key + 0xfd7046c5 ) + ( key << 3 ) ; key = ( key ^ 0xb55a4f09 ) ^ ( key >> 16 ) ; return key ; }


Input: Thomas Wang s 32 - bit shift hash function . <a href = http : // www . concentric . net / ~Ttwang / tech / inthash . htm / > http : // www . concentric . net / ~Ttwang / tech / inthash . htm< / a > [CODESPLIT] private int hash32shift ( int key ) { key += hash2seed ; key = ~ key + ( key << 15 ) ; key = key ^ ( key >>> 12 ) ; key = key + ( key << 2 ) ; key = key ^ ( key >>> 4 ) ; key = key * 2057 ; key = key ^ ( key >>> 16 ) ; return key ; }


Input: Implements a secondary hash . This uses the 32 - bit shift hash implemented by { @link #hash32shift ( int ) } and then successively applies { @link #hash1 ( int ) } if the generated hash code is not different to the hash code generated by running { @link #hash1 ( int ) } on the key . This ensures that the hash code returned by this will be different to the one generated by { @link #hash1 ( int ) } . [CODESPLIT] private int hash2 ( int hash1 , int key ) { key = hash32shift ( key ) ; while ( key == hash1 ) { key = hash32shift ( key ) ; } return key ; }


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


Input: Listens for the button events Ok Cancel and Apply . If the event is Ok or Apply the saveWork method is triggered . If the event is Cancel then the discardWork method is triggered . [CODESPLIT] public void actionPerformed ( ActionEvent event ) { /*log.fine("void actionPerformed(ActionEvent): called");*/ /*log.fine("Action is " + event.getActionCommand());*/ // Check which action was performed String action = event . getActionCommand ( ) ; if ( "OK" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work saveWork ( ) ; } } else if ( "Cancel" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Discard the work discardWork ( ) ; } } else if ( "Apply" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work saveWork ( ) ; } } }


Input: Sets the state of the next available flag and notifies any listeners of this change . [CODESPLIT] public void setNextAvailable ( boolean avail ) { // Check if the state has changed if ( nextAvailable != avail ) { // Keep the new state nextAvailable = avail ; // Notify any listeners fo the change in state firePropertyChange ( new PropertyChangeEvent ( this , "nextAvailable" , ! avail , avail ) ) ; } }


Input: Sets the state of the previous available flag and notifies any listeners of this change . [CODESPLIT] public void setPrevAvailable ( boolean avail ) { // Check if the state has changed if ( prevAvailable != avail ) { // Keep the new state prevAvailable = avail ; // Notify any listeners fo the change in state firePropertyChange ( new PropertyChangeEvent ( this , "prevAvailable" , ! avail , avail ) ) ; } }


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


Input: Creates an instance of this machine loading and checking for availability of the native implementation library as required . [CODESPLIT] public static WAMResolvingNativeMachine getInstance ( SymbolTableImpl < Integer , String , Object > symbolTable ) throws ImplementationUnavailableException { try { if ( ! libraryLoadAttempted ) { libraryLoadAttempted = true ; System . loadLibrary ( "aima_native" ) ; libraryFound = true ; } if ( libraryFound ) { return new WAMResolvingNativeMachine ( symbolTable ) ; } else { throw new ImplementationUnavailableException ( "The native library could not be found." , null , null , null ) ; } } catch ( UnsatisfiedLinkError e ) { libraryFound = false ; throw new ImplementationUnavailableException ( "The native library could not be found." , e , null , null ) ; } }


Input: Provides an iterator that generates all solutions on demand as a sequence of variable bindings . [CODESPLIT] public Iterator < Set < Variable > > iterator ( ) { return new SequenceIterator < Set < Variable > > ( ) { public Set < Variable > nextInSequence ( ) { return resolve ( ) ; } } ; }


Input: For a given set of probabilities of the occurences of symbols this function calculates the expected information content of a set of symbols given its probability distribution . The answer is expressed as a positive number of bits . [CODESPLIT] public static double expectedI ( double [ ] probabilities ) { double result = 0.0d ; // Loop over the probabilities for all the symbols calculating the contribution of each to the expected value. for ( double p : probabilities ) { // Calculate the information in each symbol. I(p) = - ln p and weight this by its probability of occurence // to get that symbols contribution to the expected value over all symbols. if ( p > 0.0d ) { result -= p * Math . log ( p ) ; } } // Convert the result from nats to bits by dividing by ln 2. return result / LN2 ; }


Input: Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of symbols { h1 ... hv } and G ranges over a set of symbols { g1 ... gn } . [CODESPLIT] public static double remainder ( double [ ] pA , double [ ] [ ] pGgivenA ) { double result = 0.0d ; // Loop over the probabilities for all the symbols of A calculating the contribution of each to // the expected value. for ( int v = 0 ; v < pA . length ; v ++ ) { double phv = pA [ v ] ; // Calculate the expected information content of the distribution of the symbols of G given the symbol hv // and scale its contribution to the total by the probability of hv occuring. result += phv * expectedI ( pGgivenA [ v ] ) ; } // There is no need to convert the result from nats to bits and the expected information function is // already in bits. return result ; }


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


Input: Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of symbols { h1 ... hv } and G ranges over a set of symbols { g1 ... gn } . [CODESPLIT] public static double [ ] [ ] pForJointDistribution ( int [ ] [ ] counts ) { double [ ] [ ] results = new double [ counts . length ] [  ] ; // Loop over all the symbols of A for ( int i = 0 ; i < counts . length ; i ++ ) { // Extract the next distribution array of the symbols of G given A. int [ ] countsGgivenA = counts [ i ] ; // Convert the frequency distribution into a probability distribution and add it to the results. results [ i ] = pForDistribution ( countsGgivenA ) ; } return results ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof LiteralTypeVisitor ) { ( ( LiteralTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: { [CODESPLIT] public int compareTo ( DateOnly o ) { if ( year < o . year ) { return - 1 ; } else if ( year > o . year ) { return 1 ; } else if ( month < o . month ) { return - 1 ; } else if ( month > o . month ) { return 1 ; } else if ( day < o . day ) { return - 1 ; } else if ( day > o . day ) { return 1 ; } else { return 0 ; } }


Input: Sets this date from a milliseconds timestamp . [CODESPLIT] void setTicks ( long ticks ) { year = TimeUtils . ticksToYears ( ticks ) ; month = TimeUtils . ticksToMonths ( ticks ) ; day = TimeUtils . ticksToDate ( ticks ) ; }


Input: Recreate internal state before children are cloned . [CODESPLIT] @ Override protected void cloneChildren ( InternalNode node ) { SelectorNode selector = ( SelectorNode ) node ; // Reset internal state selector . setAdditionVisitor ( ) ; super . cloneChildren ( node ) ; }


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


Input: Checks but does not enforce the throttle rate . When this method is called it checks if a length of time greater than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt > true< / tt > . If the length of time still to elapse to the next throttle allow point is zero or less this method will return a negative value if there is still time to pass until the throttle allow point this method will return a positive value indicating the amount of time still to pass . A thread can wait for that period of time before rechecking the throttle condition . [CODESPLIT] public long timeToThrottleNanos ( ) { // Work out how long ago the last throttle query was. long currentTimeNanos = System . nanoTime ( ) ; long delay = currentTimeNanos - lastTimeNanos ; // Regenerate the tokens allowed since the last query. float numTokens = ( delay * 1.0e9f ) * targetRate ; tokenCount -= numTokens ; if ( tokenCount < 0f ) { tokenCount = 0f ; } // Update the last time stamp for next time around. lastTimeNanos = currentTimeNanos ; // Check if there are tokens available to consume, and consume one if so. if ( tokenCount <= ( depth - 1.0 ) ) { tokenCount += 1.0 ; return 0 ; } else { // There are no tokens to consume, so return an estimate of how long it will take to generate one token. return ( long ) ( 1.0e9 / targetRate ) ; } }


Input: Creates a URL for the specified string representation . [CODESPLIT] public static URL newUrl ( String spec ) { try { return new URL ( spec ) ; } catch ( MalformedURLException exception ) { throw new IllegalArgumentException ( "Invalid URL: " + spec ) ; } }


Input: Returns a String with all basic request information in an HTML table . [CODESPLIT] public String getRequestInfo ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; info . put ( "authType" , nullToString ( req . getAuthType ( ) ) ) ; info . put ( "characterEncoding" , nullToString ( req . getCharacterEncoding ( ) ) ) ; info . put ( "contentLength" , Integer . toString ( req . getContentLength ( ) ) ) ; info . put ( "contentType" , nullToString ( req . getContentType ( ) ) ) ; info . put ( "contextPath" , nullToString ( req . getContextPath ( ) ) ) ; info . put ( "pathInfo" , nullToString ( req . getPathInfo ( ) ) ) ; info . put ( "protocol" , nullToString ( req . getProtocol ( ) ) ) ; info . put ( "queryString" , nullToString ( req . getQueryString ( ) ) ) ; info . put ( "remoteAddr" , nullToString ( req . getRemoteAddr ( ) ) ) ; info . put ( "remoteHost" , nullToString ( req . getRemoteHost ( ) ) ) ; info . put ( "remoteUser" , nullToString ( req . getRemoteUser ( ) ) ) ; info . put ( "requestURI" , nullToString ( req . getRequestURI ( ) ) ) ; info . put ( "scheme" , nullToString ( req . getScheme ( ) ) ) ; info . put ( "serverName" , nullToString ( req . getServerName ( ) ) ) ; info . put ( "serverPort" , Integer . toString ( req . getServerPort ( ) ) ) ; info . put ( "servletPath" , nullToString ( req . getServletPath ( ) ) ) ; return toHTMLTable ( "request properties" , info ) ; }


Input: Returns a String with all header information as an HTML table . [CODESPLIT] public String getHeaders ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getHeaderNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Enumeration values = req . getHeaders ( name ) ; StringBuffer sb = new StringBuffer ( ) ; boolean first = true ; while ( values . hasMoreElements ( ) ) { if ( ! first ) { sb . append ( " | " ) ; } first = false ; sb . append ( values . nextElement ( ) ) ; } info . put ( name , sb . toString ( ) ) ; } return toHTMLTable ( "headers" , info ) ; }


Input: Returns a String with all cookie information as an HTML table . [CODESPLIT] public String getCookies ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Cookie [ ] cookies = req . getCookies ( ) ; // check that cookies is not null which it may be if there are no cookies if ( cookies != null ) { for ( int i = 0 ; i < cookies . length ; i ++ ) { Cookie cooky = cookies [ i ] ; info . put ( cooky . getName ( ) , cooky . getValue ( ) ) ; } } return toHTMLTable ( "cookies" , info ) ; }


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


Input: Returns a String with all request scope variables . [CODESPLIT] public String getRequestScope ( ) { Map info = new TreeMap ( ) ; ServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = req . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "request scope" , info ) ; }


Input: Returns a String with all page scope variables . [CODESPLIT] public String getPageScope ( ) { Map info = new TreeMap ( ) ; Enumeration names = pageContext . getAttributeNamesInScope ( PageContext . PAGE_SCOPE ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = pageContext . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "page scope" , info ) ; }


Input: Returns a String with all session scope variables . [CODESPLIT] public String getSessionScope ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; HttpSession session = req . getSession ( ) ; Enumeration names = session . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = session . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "session scope" , info ) ; }


Input: Returns a String with all application scope variables . [CODESPLIT] public String getApplicationScope ( ) { Map info = new TreeMap ( ) ; ServletContext context = pageContext . getServletContext ( ) ; Enumeration names = context . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = context . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "application scope" , info ) ; }


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


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


Input:
Returns an HTML table with all the values of the specified property . [CODESPLIT] private String toHTMLTable ( String propName , Map values ) { StringBuffer tableSB = new StringBuffer ( ) ; tableSB . append ( "
" ) . append ( propName ) . append ( "
" ) ; for ( Iterator it = values . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Object o = it . next ( ) ; String key = ( String ) o ; tableSB . append ( "
" ) . append ( key ) . append ( "	" ) . append ( values . get ( key ) ) . append ( "
" ) ; } return tableSB . toString ( ) ; }


Input: Returns a string representation of the specified object in a format suitable for debug output . If the object is an array all its elements are extracted and displayed seperated by commas . Other objects are converted to strings by their toString methods . [CODESPLIT] private String toStringValue ( Object value ) { // Check if the value is null if ( value == null ) { return "null" ; } StringBuffer sb = new StringBuffer ( ) ; Class type = value . getClass ( ) ; if ( type . isArray ( ) ) { Class componentType = type . getComponentType ( ) ; sb . append ( componentType . getName ( ) ) ; sb . append ( "[]: {" ) ; if ( ! componentType . isPrimitive ( ) ) { Object [ ] arr = ( Object [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Boolean . TYPE ) { boolean [ ] arr = ( boolean [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Byte . TYPE ) { byte [ ] arr = ( byte [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Character . TYPE ) { char [ ] arr = ( char [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Double . TYPE ) { double [ ] arr = ( double [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Float . TYPE ) { float [ ] arr = ( float [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Integer . TYPE ) { int [ ] arr = ( int [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Long . TYPE ) { long [ ] arr = ( long [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Short . TYPE ) { short [ ] arr = ( short [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } sb . append ( "}" ) ; } else { // Obtain the objects value using toString, but protect this against null pointer exceptions, to harden // this implementation. String stringValue = null ; try { stringValue = value . toString ( ) ; } catch ( NullPointerException e ) { stringValue = "" ; } sb . append ( value . getClass ( ) . getName ( ) ) . append ( ": " ) . append ( stringValue ) ; } return sb . toString ( ) ; }


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


Input: Sets the new current screen state and notifies all listeners of the change in screen state . [CODESPLIT] public void setCurrentScreenState ( WorkFlowScreenState state ) { /*log.fine("void setCurrentScreenState(WorkFlowScreenState): called");*/ WorkFlowScreenState oldState = currentScreenState ; // Keep the new state. currentScreenState = state ; // Notify all listeners of the change of current screen. firePropertyChange ( new PropertyChangeEvent ( this , "currentScreenState" , oldState , state ) ) ; }


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


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


Input: Updates the register file with a new set of registers . [CODESPLIT] public void updateRegisters ( WAMInternalRegisters registers ) { List < PropertyChangeEvent > changes = delta ( this , registers ) ; ip = registers . ip ; hp = registers . hp ; hbp = registers . hbp ; sp = registers . sp ; up = registers . up ; ep = registers . ep ; bp = registers . bp ; b0 = registers . b0 ; trp = registers . trp ; writeMode = registers . writeMode ; notifyChanges ( changes ) ; }


Input: Compares the current register file with a new set and creates a list property change notifications for any that have changed value . [CODESPLIT] private List < PropertyChangeEvent > delta ( WAMInternalRegisters oldRegisters , WAMInternalRegisters newRegisters ) { List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . ip != newRegisters . ip ) { result . add ( new PropertyChangeEvent ( this , "IP" , oldRegisters . ip , newRegisters . ip ) ) ; } if ( oldRegisters . hp != newRegisters . hp ) { result . add ( new PropertyChangeEvent ( this , "HP" , oldRegisters . hp , newRegisters . hp ) ) ; } if ( oldRegisters . hbp != newRegisters . hbp ) { result . add ( new PropertyChangeEvent ( this , "HBP" , oldRegisters . hbp , newRegisters . hbp ) ) ; } if ( oldRegisters . sp != newRegisters . sp ) { result . add ( new PropertyChangeEvent ( this , "SP" , oldRegisters . sp , newRegisters . sp ) ) ; } if ( oldRegisters . up != newRegisters . up ) { result . add ( new PropertyChangeEvent ( this , "UP" , oldRegisters . up , newRegisters . up ) ) ; } if ( oldRegisters . ep != newRegisters . ep ) { result . add ( new PropertyChangeEvent ( this , "EP" , oldRegisters . ep , newRegisters . ep ) ) ; } if ( oldRegisters . bp != newRegisters . bp ) { result . add ( new PropertyChangeEvent ( this , "BP" , oldRegisters . bp , newRegisters . bp ) ) ; } if ( oldRegisters . b0 != newRegisters . b0 ) { result . add ( new PropertyChangeEvent ( this , "B0" , oldRegisters . b0 , newRegisters . b0 ) ) ; } if ( oldRegisters . trp != newRegisters . trp ) { result . add ( new PropertyChangeEvent ( this , "TRP" , oldRegisters . trp , newRegisters . trp ) ) ; } if ( oldRegisters . writeMode != newRegisters . writeMode ) { result . add ( new PropertyChangeEvent ( this , "writeMode" , oldRegisters . writeMode , newRegisters . writeMode ) ) ; } return result ; }


Input: Fires off a list of property change events to any interested listeners . [CODESPLIT] private void notifyChanges ( Iterable < PropertyChangeEvent > changes ) { List < PropertyChangeListener > activeListeners = listeners . getActiveListeners ( ) ; if ( activeListeners != null ) { for ( PropertyChangeListener listener : activeListeners ) { for ( PropertyChangeEvent event : changes ) { listener . propertyChange ( event ) ; } } } }


Input: { [CODESPLIT] public void insert ( char character , int c , int r ) { parent . insert ( character , c + column , r + row ) ; }


Input: { [CODESPLIT] public void insert ( String string , int c , int r ) { parent . insert ( string , c + column , r + row ) ; }


Input: { [CODESPLIT] public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { return parent . createInnerGrid ( c + column , r + row , w , h ) ; }


Input: { [CODESPLIT] public TextTableModel createTable ( int c , int r , int w , int h ) { return parent . createTable ( c + column , r + row , w , h ) ; }


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


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


Input: Upon leaving the clause sets the nonArgPosition flag on any constants that need it . [CODESPLIT] protected void leaveClause ( Clause clause ) { // Remove the set of constants appearing in argument positions, from the set of all constants, to derive // the set of constants that appear in non-argument positions only. constants . keySet ( ) . removeAll ( argumentConstants ) ; // Set the nonArgPosition flag on all symbol keys for all constants that only appear in non-arg positions. for ( List < SymbolKey > symbolKeys : constants . values ( ) ) { for ( SymbolKey symbolKey : symbolKeys ) { symbolTable . put ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG , true ) ; } } }


Input: Checks if the current position is immediately within a top - level functor . [CODESPLIT] private boolean inTopLevelFunctor ( PositionalContext context ) { PositionalContext parentContext = context . getParentContext ( ) ; return parentContext . isTopLevel ( ) || isTopLevel ( parentContext ) ; }


Input: Functors are considered top - level when they appear at the top - level within a clause or directly beneath a parent conjunction or disjunction that is considered to be top - level . [CODESPLIT] private boolean isTopLevel ( PositionalContext context ) { Term term = context . getTerm ( ) ; if ( term . getSymbolKey ( ) == null ) { return false ; } Boolean isTopLevel = ( Boolean ) symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ; }


Input: Adds all of the elements in the specified collection to this heap . Attempts to addAll of a queue to itself result in <tt > IllegalArgumentException< / tt > . Further the behavior of this operation is undefined if the specified collection is modified while the operation is in progress . [CODESPLIT] public boolean addAll ( Collection < ? extends E > collection ) { if ( collection == null ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be null." ) ; } if ( collection == this ) { throw new IllegalArgumentException ( ) ; } boolean modified = false ; for ( E aC : collection ) { if ( add ( aC ) ) { modified = true ; } } return modified ; }


Input: Removes a single instance of the specified element from this heap if it is present . ( optional operation ) . More formally removes an element <tt > e< / tt > such that <tt > ( o == null ? e == null : o . equals ( e )) < / tt > if the collection contains one or more such elements . Returns <tt > true< / tt > if the collection contained the specified element ( or equivalently if the collection changed as a result of the call ) . [CODESPLIT] public boolean remove ( Object o ) { Iterator < E > e = iterator ( ) ; if ( o == null ) { while ( e . hasNext ( ) ) { if ( e . next ( ) == null ) { e . remove ( ) ; return true ; } } } else { while ( e . hasNext ( ) ) { if ( o . equals ( e . next ( ) ) ) { e . remove ( ) ; return true ; } } } return false ; }


Input: Returns an array containing all of the elements in this heap . If the collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order . The returned array will be safe in that no references to it are maintained by the collection . ( In other words this method must allocate a new array even if the collection is backed by an Array ) . The caller is thus free to modify the returned array . [CODESPLIT] public Object [ ] toArray ( ) { Object [ ] result = new Object [ size ( ) ] ; Iterator < E > e = iterator ( ) ; for ( int i = 0 ; e . hasNext ( ) ; i ++ ) { result [ i ] = e . next ( ) ; } return result ; }


Input: Returns an array containing all of the elements in this heap ; the runtime type of the returned array is that of the specified array . If the collection fits in the specified array it is returned therein . Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection . [CODESPLIT] public < T > T [ ] toArray ( T [ ] a ) { int size = size ( ) ; if ( a . length < size ) { a = ( T [ ] ) java . lang . reflect . Array . newInstance ( a . getClass ( ) . getComponentType ( ) , size ) ; } Iterator < E > it = iterator ( ) ; Object [ ] result = a ; for ( int i = 0 ; i < size ; i ++ ) { result [ i ] = it . next ( ) ; } if ( a . length > size ) { a [ size ] = null ; } return a ; }


Input: Provides a look at the last object placed on the stack since it will be the first one out . This method does not change the contents of the stack . Because this class is unsynchronized applications using this class are responsible for making sure that a <CODE > peek () < / CODE > followed by a <CODE > pop () < / CODE > returns the same value . [CODESPLIT] public E peek ( ) { int last = size ( ) - 1 ; E ob ; if ( last == - 1 ) { return null ; } ob = get ( last ) ; return ob ; }


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


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof PredicateVisitor ) { ( ( PredicateVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


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


Input: Sets the arguments of this operator . It can be convenient to be able to set the outside of the constructor for example when parsing may want to create the operator first and fill in its arguments later . [CODESPLIT] public void setArguments ( Term [ ] arguments ) { // Check that there is at least one and at most two arguments. if ( ( arguments == null ) || ( arguments . length < 1 ) || ( arguments . length > 2 ) ) { throw new IllegalArgumentException ( "An operator has minimum 1 and maximum 2 arguments." ) ; } this . arguments = arguments ; this . arity = arguments . length ; }


Input: Provides the symbols fixity derived from its associativity . [CODESPLIT] public Fixity getFixity ( ) { switch ( associativity ) { case FX : case FY : return Fixity . Pre ; case XF : case YF : return Fixity . Post ; case XFX : case XFY : case YFX : return Fixity . In ; default : throw new IllegalStateException ( "Unknown associativity." ) ; } }


Input: Reports whether this operator is an infix operator . [CODESPLIT] public boolean isInfix ( ) { return ( ( associativity == Associativity . XFY ) || ( associativity == Associativity . YFX ) || ( associativity == Associativity . XFX ) ) ; }


Input: Compares this object with the specified object for order providing a negative integer zero or a positive integer as this symbols priority is less than equal to or greater than the comparator . If this symbol is less than another that means that it has a lower priority value which means that it binds more tightly . [CODESPLIT] public int compareTo ( Object o ) { OpSymbol opSymbol = ( OpSymbol ) o ; return ( priority < opSymbol . priority ) ? - 1 : ( ( priority > opSymbol . priority ) ? 1 : 0 ) ; }


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


Input: Updates the buttons enabled / disabled status to reflect the current screen state . [CODESPLIT] public void updateButtonsForScreen ( WorkFlowScreenState state ) { // Check if it is in the READY or NOT_SAVED state if ( state . getState ( ) . equals ( WorkFlowScreenState . READY ) || state . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { backButton . setEnabled ( state . isPrevAvailable ( ) ) ; nextButton . setEnabled ( state . isNextAvailable ( ) ) ; finishButton . setEnabled ( state . isFinished ( ) ) ; } // Check if it is in the NOT_INITIALIZED state if ( state . getState ( ) . equals ( WorkFlowScreenState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; } }


Input: Updates the buttons enabled / disabled status to reflect the current work flow state . [CODESPLIT] public void updateButtonsForWorkFlow ( WorkFlowState state ) { // Check if it is in the NOT_INITIALIZED state if ( state . getState ( ) . equals ( WorkFlowState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( false ) ; } // Check if it is in the READY state if ( state . getState ( ) . equals ( WorkFlowState . READY ) ) { finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( true ) ; // Update buttons for the current screen state updateButtonsForScreen ( state . getCurrentScreenState ( ) ) ; } // Check if it is in the NOT_SAVED state if ( state . getState ( ) . equals ( WorkFlowState . NOT_SAVED ) ) { finishButton . setEnabled ( true ) ; cancelButton . setEnabled ( true ) ; } }


Input: Registers the work flow button panel with the specified work flow controller . This will cause the work flow controller to receive button press events from the panel and register the button panel to receive state changes from the underlying work flow model . [CODESPLIT] public void registerWorkFlowController ( WorkFlowController controller ) { // Set the work flow controller to listen for button events backButton . addActionListener ( controller ) ; nextButton . addActionListener ( controller ) ; finishButton . addActionListener ( controller ) ; cancelButton . addActionListener ( controller ) ; // Register this to listen for changes to the work flow state controller . getWorkFlowState ( ) . addPropertyChangeListener ( this ) ; // Register this to listen for changes to the state for the current screen if it is not null WorkFlowScreenState currentScreenState = controller . getWorkFlowState ( ) . getCurrentScreenState ( ) ; if ( currentScreenState != null ) { currentScreenState . addPropertyChangeListener ( this ) ; } }


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


Input: Generates a factory for building enum attributes of the specified enum class . [CODESPLIT] public static EnumAttributeFactory getFactoryForClass ( Class cls ) { // Check that the requested class is actually an enum. if ( ! cls . isEnum ( ) ) { throw new IllegalArgumentException ( "Can only create enum attribute factories for classes that are enums." ) ; } return EnumClassImpl . getInstance ( cls ) ; }


Input: { @inheritDoc } [CODESPLIT] public void changeColor ( C color ) { AttributeSet aset = new AttributeSet ( ) ; aset . put ( AttributeSet . BACKGROUND_COLOR , color ) ; grid . insertRowAttribute ( aset , row ) ; }


Input: Creates an instance of the named component factory . [CODESPLIT] public static ComponentFactory createComponentFactory ( String className ) { return ( ComponentFactory ) ReflectionUtils . newInstance ( ReflectionUtils . forName ( className ) ) ; }


Input: Provides the storage cell for the specified variable . Some types of variable may defer their storage onto a storage cell other than themselves other variable types may simply return themselves as their own storage cells . [CODESPLIT] public Variable getStorageCell ( Variable variable ) { VariableBindingContext < Variable > context = getBindingContext ( ) ; if ( context == null ) { return null ; } else { return context . getStorageCell ( this ) ; } }


Input: Reports whether or not this variable is bound to a value . [CODESPLIT] public boolean isBound ( ) { VariableBindingContext < Variable > context = getBindingContext ( ) ; // The variable can only be bound if it has a binding context and is bound in that context. return ( context != null ) && context . getStorageCell ( this ) . isBound ( ) ; }


Input: { [CODESPLIT] public AttributeSet getAttributeAt ( int c , int r ) { AttributeSet attributeSet = cellAttributes . get ( ( long ) c , ( long ) r ) ; attributeSet = ( attributeSet == null ) ? getColumnAttributeOrNull ( c ) : attributeSet ; attributeSet = ( attributeSet == null ) ? getRowAttributeOrNull ( r ) : attributeSet ; return attributeSet ; }


Input: Sets a column attribute adding padding to the underlying array as necessary to ensure it is large enough to hold the attribute at the requested position . [CODESPLIT] private void setColumnAttribute ( AttributeSet attributes , int c ) { if ( c >= columnAttributes . size ( ) ) { for ( int i = columnAttributes . size ( ) ; i <= c ; i ++ ) { columnAttributes . add ( null ) ; } } columnAttributes . set ( c , attributes ) ; }


Input: Sets a row attribute adding padding to the underlying array as necessary to ensure it is large enough to hold the attribute at the requested position . [CODESPLIT] private void setRowAttribute ( AttributeSet attributes , int r ) { if ( r >= rowAttributes . size ( ) ) { for ( int i = rowAttributes . size ( ) ; i <= r ; i ++ ) { rowAttributes . add ( null ) ; } } rowAttributes . set ( r , attributes ) ; }


Input: Gets a columns attribute if possible without overflowing the underlying array . [CODESPLIT] private AttributeSet getColumnAttributeOrNull ( int c ) { if ( ( c >= 0 ) && ( c < columnAttributes . size ( ) ) ) { return columnAttributes . get ( c ) ; } else { return null ; } }


Input: Gets a rows attribute if possible without overflowing the underlying array . [CODESPLIT] private AttributeSet getRowAttributeOrNull ( int r ) { if ( ( r >= 0 ) && ( r < rowAttributes . size ( ) ) ) { return rowAttributes . get ( r ) ; } else { return null ; } }


Input: Inserts a set of attributes into the grid at the specified location . This is a private insert method that does not notify model listeners so that the public insert methods can do that as a separate step . [CODESPLIT] private void internalInsert ( AttributeSet attributes , int c , int r ) { cellAttributes . put ( ( long ) c , ( long ) r , attributes ) ; }


Input: Gets the actual value of a term which is a numeric type equal in value to the arithmetic operator applied to its argument . This method checks that the argument produces a value which is fully instantiated and numeric when its { @link Term#getValue () } methods is invoked . [CODESPLIT] public NumericType getValue ( ) { Term firstArgValue = arguments [ 0 ] . getValue ( ) ; // Check that the argument to operate on is a numeric values. if ( ! firstArgValue . isNumber ( ) ) { throw new IllegalStateException ( "instantiation_error, 'arithmetic/2' expects numeric arguments, but the first argument is non-numeric." ) ; } return evaluate ( ( NumericType ) firstArgValue ) ; }


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


Input: { [CODESPLIT] public JComponent createGripPanel ( MotionDelta motionDelta , boolean vertical ) { JPanel vbar = new JPanel ( ) ; vbar . setBackground ( toolingColorScheme . getToolingBackground ( ) ) ; GripComponentMouseMover resizer = new GripComponentMouseMover ( vbar , motionDelta , vertical ? VERTICAL_RESIZE_CURSOR : HORIZONTAL_RESIZE_CURSOR , GRIP_CURSOR ) ; vbar . addMouseMotionListener ( resizer ) ; vbar . addMouseListener ( resizer ) ; return vbar ; }


Input: { [CODESPLIT] public JComponent createBlankPanel ( ) { JPanel vbar = new JPanel ( ) ; vbar . setBackground ( colorScheme . getBackground ( ) ) ; vbar . setForeground ( colorScheme . getDisabledText ( ) ) ; return vbar ; }