signature: public class GemFireNetworking { private static int parseLocatorPort ( String locator ) { } }

implementation: int start = locator . indexOf ( "[" ) ; String text = null ; if ( start > 0 ) { String results = locator . substring ( start + 1 ) ; int end = results . indexOf ( "]" ) ; if ( end > 0 ) { text = results . substring ( 0 , end ) . trim ( ) ; return Integer . parseInt ( text ) ; } } throw new IllegalArgumentException ( "Expected format host[port] but provided with:" + locator ) ;


signature: public class SplitGfdFile { @ Override public void run ( ) { } }

implementation:
if ( ! outDirectory . exists ( ) ) { throw new IllegalArgumentException ( outDirectory + " does not exist" ) ; } // read
try ( SnapshotRecordReader reader = new SnapshotRecordReader ( inFile ) ) { SnapshotRecord record = null ; // create writer
int batchCount = 1 ; File out = createFile ( batchCount ++ ) ; SnapshotRecordWriter writer = null ; try { writer = new SnapshotRecordWriter ( out , regionName ) ; int cnt = 0 ; while ( ( record = reader . readSnapshotRecord ( ) ) != null ) { writer . writeSnapshotEntry ( record ) ; cnt ++ ; if ( cnt >= batchSize ) { out = createFile ( batchCount ++ ) ; writer . close ( ) ; writer = new SnapshotRecordWriter ( out , regionName ) ; } } } finally { if ( writer != null ) writer . close ( ) ; } } catch ( ClassNotFoundException | IOException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; }


signature: public class PrintExampleJsonFunction { private Class < ? > forClassName ( String className ) throws ClassNotFoundException { } }

implementation: if ( className == null || className . length ( ) == 0 ) throw new FunctionException ( "class name string is empty: " ) ; return Class . forName ( className ) ;


signature:
public class BitSeries { /** * Returns the amount of memory used to implement this series . */
protected int getMemoryUsed ( ) { } }

implementation: int result = 4 + 8 + 8 + 8 + 4 + 4 + 4 ; if ( intervals != null ) { result += 4 * intervals . length ; for ( int i = 0 ; i <= intervalIdx ; i ++ ) { result += intervals [ i ] . getMemoryUsed ( ) ; } } return result ;


signature:
public class BitSeries { /** * Gets the first " resultSize " values of this series skipping over the first
 * " samplesToSkip " ones . The first value in a series is at index 0 . The
 * maximum result size can be obtained by calling " getSize ( ) " . */
public double [ ] getValuesEx ( int typeCode , int samplesToSkip , int resultSize ) { } }

implementation:
double [ ] result = new double [ resultSize ] ; int firstInterval = 0 ; int idx = 0 ; while ( samplesToSkip > 0 && firstInterval <= intervalIdx && intervals [ firstInterval ] . getSampleCount ( ) <= samplesToSkip ) { samplesToSkip -= intervals [ firstInterval ] . getSampleCount ( ) ; firstInterval ++ ; } for ( int i = firstInterval ; i <= intervalIdx ; i ++ ) { idx += intervals [ i ] . fill ( result , idx , typeCode , samplesToSkip ) ; samplesToSkip = 0 ; } if ( currentCount != 0 ) { idx += BitInterval . create ( currentStartBits , currentInterval , currentCount ) . fill ( result , idx , typeCode , samplesToSkip ) ; } // assert
if ( idx != resultSize ) { throw new RuntimeException ( "GetValuesEx didn't fill the last " + ( resultSize - idx ) + " entries of its result" ) ; } return result ;


signature:
public class BitSeries { /** * Free up any unused memory */
void shrink ( ) { } }

implementation: if ( intervals != null ) { int currentSize = intervalIdx + 1 ; if ( currentSize < intervals . length ) { BitInterval [ ] tmp = new BitInterval [ currentSize ] ; System . arraycopy ( intervals , 0 , tmp , 0 , currentSize ) ; intervals = tmp ; } }


signature:
public class GfdExportFunction { /** * Export region data in JSON format
 * @ param fc the function context */
public void execute ( FunctionContext < Object > fc ) { } }

implementation:
ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { didExport = exportOnRegion ( ( RegionFunctionContext ) fc ) ; } else { // get region name from argument
String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( "Region name argument required" ) ; String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; if ( region != null ) didExport = exportRegion ( region ) ; else didExport = false ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; FunctionException functionException = new FunctionException ( stackTrace ) ; LogManager . getLogger ( getClass ( ) ) . error ( stackTrace ) ; rs . sendException ( functionException ) ; throw functionException ; }


signature: public class GfdExportFunction { protected boolean exportRegion ( Region < Object , Object > region ) { } }

implementation:
if ( region == null ) return false ; if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } Logger logger = LogManager . getLogger ( getClass ( ) ) ; logger . info ( "Exporting region" + region . getName ( ) ) ; // get name
String regionName = region . getName ( ) ; File resultFile = DataOpsSecretary . determineFile ( ExportFileType . gfd , regionName ) ; // delete previous
logger . info ( "deleting file:" + resultFile . getAbsolutePath ( ) ) ; boolean wasDeleted = resultFile . delete ( ) ; logger . info ( "delete:" + wasDeleted ) ; try { // write data
RegionSnapshotService < ? , ? > regionSnapshotService = region . getSnapshotService ( ) ; SnapshotOptionsImpl < ? , ? > options = ( SnapshotOptionsImpl < ? , ? > ) regionSnapshotService . createOptions ( ) ; // setting parallelMode = true will cause only the local region data to export
options . setParallelMode ( true ) ; regionSnapshotService . save ( resultFile , SnapshotFormat . GEMFIRE ) ; return true ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new FunctionException ( "Error exporting ERROR:" + e . getMessage ( ) + " " + Debugger . stackTrace ( e ) ) ; }


signature:
public class ExportCsvFunction { /** * Export region data in JSON format
 * @ param fc the function context */
public void execute ( FunctionContext < String [ ] > fc ) { } }

implementation: ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { String [ ] args = fc . getArguments ( ) ; didExport = this . exportRegion ( ( ( RegionFunctionContext ) fc ) . getDataSet ( ) , Organizer . at ( 0 , args ) ) ; } else { didExport = exportRegionByArg ( fc ) ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; }


signature: public class ExportCsvFunction { private boolean exportRegionByArg ( FunctionContext < String [ ] > fc ) { } }

implementation:
String [ ] args = fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( "Argument not provided" ) ; } // Get region name from arguments
String regionName = Organizer . at ( 0 , args ) ; if ( regionName == null || regionName . length ( ) == 0 ) throw new FunctionException ( "regionName is required at argumeng index 0" ) ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return exportRegion ( region , Organizer . at ( 1 , args ) ) ;


signature: public class GeodeLuceneSearch { public Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , Region < String , Collection < ? > > pageKeysRegion ) { } }

implementation:
if ( criteria == null ) return null ; if ( criteria . getQuery ( ) == null || criteria . getQuery ( ) . length ( ) == 0 ) return null ; if ( criteria . getIndexName ( ) == null || criteria . getIndexName ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( "Default criteria's indexName is required" ) ; if ( criteria . getId ( ) == null || criteria . getId ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( "Default criteria's id is required" ) ; if ( criteria . getDefaultField ( ) == null || criteria . getDefaultField ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( "Default criteria's defaultField is required" ) ; try { LuceneQuery < Object , Object > luceneQuery = luceneService . createLuceneQueryFactory ( ) . create ( criteria . getIndexName ( ) , criteria . getRegionName ( ) , criteria . getQuery ( ) , criteria . getDefaultField ( ) ) ; List < LuceneResultStruct < Object , Object > > list = luceneQuery . findResults ( ) ; luceneQuery . findPages ( ) ; if ( list == null || list . isEmpty ( ) ) return null ; String sortField = criteria . getSortField ( ) ; BeanComparator beanComparator = null ; Collection < Map . Entry < Object , Object > > results = null ; if ( sortField != null && sortField . trim ( ) . length ( ) > 0 ) { beanComparator = new BeanComparator ( sortField , criteria . isSortDescending ( ) ) ; Collection < Map . Entry < Object , Object > > set = new TreeSet < Map . Entry < Object , Object > > ( beanComparator ) ; list . parallelStream ( ) . forEach ( e -> set . add ( new MapEntry < Object , Object > ( e . getKey ( ) , e . getValue ( ) ) ) ) ; results = set ; } else { results = list . stream ( ) . map ( e -> new MapEntry < > ( e . getKey ( ) , e . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; } // add to pages
List < Collection < Object > > pagesCollection = Organizer . toKeyPages ( results , criteria . getEndIndex ( ) - criteria . getBeginIndex ( ) ) ; int pageIndex = 0 ; String key = null ; ArrayList < String > keys = new ArrayList < String > ( 10 ) ; for ( Collection < Object > page : pagesCollection ) { // store in region
key = new StringBuilder ( ) . append ( criteria . getId ( ) ) . append ( "-" ) . append ( pageIndex ++ ) . toString ( ) ; pageKeysRegion . put ( key , page ) ; keys . add ( key ) ; } keys . trimToSize ( ) ; return keys ; } catch ( LuceneQueryException e ) { throw new SystemException ( e ) ; }


signature: public class GeodeLuceneSearch { public Collection < String > clearSearchResultsByPage ( TextPageCriteria criteria , Region < String , Collection < ? > > pageRegion ) { } }

implementation: Collection < String > pageKeys = Querier . query ( "select * from /" + criteria . getPageRegionName ( ) + ".keySet() k where k like '" + criteria . getId ( ) + "%'" ) ; pageRegion . removeAll ( pageKeys ) ; return pageKeys ;


signature: public class GeodeLuceneSearch { @ SuppressWarnings ( "unchecked" ) public < T > Collection < T > search ( String indexName , String regionName , String queryString , String defaultField ) throws Exception { } }

implementation: Region < ? , ? > region = GeodeClient . connect ( ) . getRegion ( regionName ) ; String [ ] args = { indexName , regionName , queryString , defaultField } ; return GemFireIO . exeWithResults ( FunctionService . onRegion ( region ) . setArguments ( args ) . setArguments ( args ) , new SimpleLuceneSearchFunction ( ) ) ;


signature: public class ImportJsonFunction { public void execute ( FunctionContext < Object > fc ) { } }

implementation: ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean results = false ; if ( fc instanceof RegionFunctionContext ) { results = importOnRegion ( ( RegionFunctionContext ) fc ) ; } else { results = importAllRegions ( fc ) ; } rs . lastResult ( results ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; }


signature: public class ImportJsonFunction { private boolean importAllRegions ( FunctionContext < Object > fc ) throws Exception { } }

implementation:
String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( "Argument not provided" ) ; } // Get region name from arguments
String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return importRegion ( region ) ;


signature: public class ImportJsonFunction { private boolean importRegion ( Region < Object , Object > region ) throws Exception { } }

implementation:
JsonNode node , keyNode , valueNode , keyClassName , valueClassName ; Object key , value ; if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } // get first
ObjectMapper mapper = new ObjectMapper ( ) ; // Configure to be very forgiving
// mapper . configure ( Feature . FAIL _ ON _ INVALID _ SUBTYPE , false ) ;
// mapper . configure ( Feature . FAIL _ ON _ UNKNOWN _ PROPERTIES , false ) ;
// mapper . configure ( Feature . FAIL _ ON _ NULL _ FOR _ PRIMITIVES , false ) ;
// mapper . configure ( Feature . FAIL _ ON _ NUMBERS _ FOR _ ENUMS , false ) ;
// KeyDeserializers keyDeserializers = new KeyDeserializers ( )
// @ Override
// public KeyDeserializer findKeyDeserializer ( JavaType javatype ,
// DeserializationConfig deserializationconfig ,
// BeanDescription beandescription , BeanProperty beanproperty )
// throws JsonMappingException
// return new DefaultKeyDeserializer ( ) ;
// mapper . setDeserializerProvider ( mapper . getDeserializerProvider ( )
// . withAdditionalKeyDeserializers ( keyDeserializers ) ) ;
// read JSON file
String filePath = new StringBuilder ( this . directoryPath ) . append ( fileSeparator ) . append ( region . getName ( ) ) . append ( suffix ) . toString ( ) ; File file = new File ( filePath ) ; if ( ! file . exists ( ) ) { LogManager . getLogger ( getClass ( ) ) . info ( file . getAbsolutePath ( ) + " does not exists" ) ; return false ; } try ( Reader reader = Files . newBufferedReader ( file . toPath ( ) , StandardCharsets . UTF_8 ) ) { // TokenBuffer buffer = new TokenBuffer
JsonNode tree = mapper . readTree ( reader ) ; Iterator < JsonNode > children = tree . elements ( ) ; if ( children == null || ! children . hasNext ( ) ) { return false ; } while ( children . hasNext ( ) ) { node = children . next ( ) ; keyNode = node . get ( "key" ) ; valueNode = node . get ( "value" ) ; keyClassName = node . get ( "keyClassName" ) ; valueClassName = node . get ( "valueClassName" ) ; key = mapper . readValue ( keyNode . traverse ( ) , forClassName ( keyClassName ) ) ; value = mapper . readValue ( valueNode . traverse ( ) , forClassName ( valueClassName ) ) ; region . put ( key , value ) ; } return true ; }


signature:
public class GUnit { /** * < pre >
 * This method will start a single locator and cache server .
 * The location will be " locator " .
 * The cache server name will be " server "
 * This particular method starts the member using Gfsh .
 * The Gfsh script location can be configured with configuration property named
 * gfsh _ location
 * export gfsh _ location = . . . .
 * or JVM property
 * - Dgfsh _ location = . . .
 * or add to a file named " config . properties " in the CLASSPATH .
 * Alternatively you could use org . apache . geode . distributed . LocatorLauncher
 * or org . apache . geode . distributed . ServerLauncher to start the process .
 * Since there can only be a single Cache instance , these process should be
 * started external of the current JVM .
 * < / pre >
 * @ throws Exception when an unknown exception occurs */
public void startCluster ( ) throws Exception { } }

implementation: IO . mkdir ( Paths . get ( runtimeDir + "/locator" ) . toFile ( ) ) ; IO . mkdir ( Paths . get ( runtimeDir + "/server" ) . toFile ( ) ) ; Shell shell = new Shell ( ) ; ProcessInfo pi = shell . execute ( location + "/gfsh" , "-e" , "start locator  --dir=runtime/locator --bind-address=localhost --J=-D=gemfire.jmx-manager-hostname-for-clients=localhost --J=-D=gemfire.jmx-manager-bind-address=localhost --J=-D=gemfire.http-service-bind-address=localhost --http-service-port=0  --name=locator  --port=10334" ) ; System . out . println ( pi . exitValue ) ; System . out . println ( pi . output ) ; System . out . println ( pi . error ) ; pi = shell . execute ( location + "/gfsh" , "-e" , "start server --name=server --dir=" + runtimeDir + "/server --bind-address=localhost  --server-bind-address=localhost --locators=localhost[10334]" ) ; System . out . println ( pi . exitValue ) ; System . out . println ( "OUTPUT:" + pi . output ) ; System . out . println ( "ERROR:" + pi . error ) ;


signature: public class GUnit { public void shutdown ( ) { } }

implementation: try ( JMX jmx = JMX . connect ( "localhost" , 1099 ) ) { String [ ] members = GemFireMgmt . shutDown ( jmx ) ; Debugger . println ( "members:" + Debugger . toString ( members ) ) ; GemFireMgmt . stopLocator ( jmx , "locator" ) ; } try { IO . delete ( Paths . get ( runtimeDir + "/server" ) . toFile ( ) ) ; } catch ( IOException e ) { Debugger . printWarn ( e ) ; } try { IO . delete ( Paths . get ( runtimeDir + "/locator" ) . toFile ( ) ) ; } catch ( IOException e ) { Debugger . printWarn ( e ) ; }


signature:
public class GUnit { /** * Wait for a given member to startup
 * @ param jmx the JMX connection
 * @ param member the member to wait for */
public void waitForMemberStart ( String member , JMX jmx ) { } }

implementation: boolean isRunning = false ; boolean printedStartMember = false ; int count = 0 ; while ( ! isRunning ) { try { isRunning = GemFireInspector . checkMemberStatus ( member , jmx ) ; } catch ( Exception e ) { Debugger . printWarn ( e ) ; } if ( ! printedStartMember ) { Debugger . println ( "Waiting for member:" + member + ".  Starting member to continue. " + " You can perform a gfsh status command to confirm whether the member is running" ) ; printedStartMember = true ; } try { delay ( ) ; } catch ( Exception e ) { } if ( count > retryCount ) { throw new RuntimeException ( "member:" + member + " did not start after " + retryCount + " checks with a delay of " + sleepDelay + " milliseconds" ) ; } count ++ ; }


signature:
public class GUnit { /** * Wait for a given member to startup
 * @ param jmx the JMX connection
 * @ param member the member to wait for
 * @ throws InterruptedException when an communication error occurs */
public void waitForMemberStop ( String member , JMX jmx ) throws InterruptedException { } }

implementation: boolean isRunning = true ; boolean printedStartMember = false ; int count = 0 ; while ( isRunning && count < retryCount ) { isRunning = GemFireInspector . checkMemberStatus ( member , jmx ) ; if ( ! printedStartMember ) { Debugger . println ( "Waiting for member:" + member + " to stop." ) ; printedStartMember = true ; } delay ( ) ; count ++ ; } if ( isRunning ) { throw new RuntimeException ( "member:" + member + " failed to stop after " + retryCount + " checks with a delay of " + sleepDelay + " milliseconds" ) ; }


signature: public class TextPolicySearchStrategy { public < K , V > Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , LuceneQueryProvider queryProvider , Predicate < LuceneResultStruct < K , V > > filter , Region < String , Collection < K > > pageKeysRegion ) { } }

implementation: return saveSearchResultsWithPageKeys ( criteria , queryProvider . toString ( ) , filter , pageKeysRegion ) ;


signature: public class TextPolicySearchStrategy { public < K , V > Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , String query , Predicate < LuceneResultStruct < K , V > > filter , Region < String , Collection < K > > pageKeysRegion ) { } }

implementation:
if ( criteria == null ) return null ; if ( criteria . getId ( ) == null || criteria . getId ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( "Default criteria's id is required" ) ; try { // clearing asynchronously
GeodePagination pagination = new GeodePagination ( ) ; pagination . clearSearchResultsByPage ( criteria , pageKeysRegion ) ; List < Map . Entry < K , V > > results = executeQuery ( criteria , query , filter ) ; List < String > keys = pagination . storePaginationMap ( criteria . getId ( ) , criteria . getEndIndex ( ) - criteria . getBeginIndex ( ) , pageKeysRegion , results ) ; return keys ; } catch ( LuceneQueryException e ) { throw new FunctionException ( e ) ; }


signature:
public class GetEntriesChecksumFunction { /** * This function gets HashMap key = Serializable value = BigInteger
 * @ param functionContext contains an argument String [ ] where the first contains the regionName */
@ Override public void execute ( FunctionContext < Object > functionContext ) { } }

implementation: try { String [ ] args = ( String [ ] ) functionContext . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( "region argument required" ) ; String regionName = args [ 0 ] ; if ( regionName == null || regionName . length ( ) == 0 ) throw new IllegalArgumentException ( "region name argument required" ) ; Region < Serializable , Object > region = CacheFactory . getAnyInstance ( ) . getRegion ( regionName ) ; if ( region == null ) throw new IllegalArgumentException ( "region:" + regionName + " not found" ) ; functionContext . getResultSender ( ) . lastResult ( buildCheckSumMap ( region ) ) ; } catch ( Exception e ) { String stack = Debugger . stackTrace ( e ) ; LogManager . getLogger ( getClass ( ) ) . error ( stack ) ; throw new FunctionException ( stack ) ; }


signature:
public class GetEntriesChecksumFunction { /** * Build check sum map
 * @ param region the region to build the information
 * @ return the map of the keys / checksums */
HashMap < Serializable , BigInteger > buildCheckSumMap ( Region < Serializable , Object > region ) { } }

implementation:
if ( region . getAttributes ( ) . getDataPolicy ( ) . withPartitioning ( ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } Set < Serializable > keySet = region . keySet ( ) ; if ( keySet == null || keySet . isEmpty ( ) ) return null ; HashMap < Serializable , BigInteger > regionCheckSumMap = new HashMap < Serializable , BigInteger > ( keySet . size ( ) ) ; Object object = null ; Object tmp = null ; for ( Map . Entry < Serializable , Object > entry : region . entrySet ( ) ) { object = entry . getValue ( ) ; if ( PdxInstance . class . isAssignableFrom ( object . getClass ( ) ) ) { tmp = ( ( PdxInstance ) object ) . getObject ( ) ; if ( Serializable . class . isAssignableFrom ( tmp . getClass ( ) ) ) { object = tmp ; } // else use PdxInstance . hashCode
} if ( ! ( PdxInstance . class . isAssignableFrom ( object . getClass ( ) ) ) ) { regionCheckSumMap . put ( entry . getKey ( ) , MD . checksum ( object ) ) ; } else { regionCheckSumMap . put ( entry . getKey ( ) , BigInteger . valueOf ( object . hashCode ( ) ) ) ; } } return regionCheckSumMap ;


signature:
public class GeodeQueryServiceRestService { /** * Execute a GemFire query with no limit
 * @ param query the OQL to execute
 * @ return the JSON array records
 * @ throws Exception */
@ PostMapping ( path = "/" , produces = "application/json" ) public String query ( @ RequestBody String query ) throws Exception { } }

implementation: return queryLimit ( query , - 1 ) ;


signature:
public class GeodeQueryServiceRestService { /** * Execute a GemFire query
 * @ param query the OQL to execute
 * @ param limit the results count limit
 * @ return the JSON records
 * @ throws Exception */
@ PostMapping ( path = "{limit}" , produces = "application/json" ) public String queryLimit ( @ RequestBody String query , @ PathVariable int limit ) throws Exception { } }

implementation: if ( query == null || query . length ( ) == 0 ) return null ; try { query = this . appendLimit ( query , limit ) ; Logger logger = LogManager . getLogger ( getClass ( ) ) ; logger . info ( "QueryService: START query " + query ) ; Collection < Object > results = querierService . query ( query ) ; logger . info ( "QueryService: END query " + query ) ; if ( results == null ) return null ; return gson . toJson ( results , Collection . class ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; }


signature:
public class ResourceType { /** * Frees up any resources no longer needed after the archive file is closed .
 * Returns true if this guy is no longer needed . */
protected boolean close ( ) { } }

implementation: if ( isLoaded ( ) ) { for ( int i = 0 ; i < stats . length ; i ++ ) { if ( stats [ i ] != null ) { if ( ! stats [ i ] . isLoaded ( ) ) { stats [ i ] = null ; } } } return false ; } else { return true ; }


signature:
public class QueryBuilder { /** * Forces the value to be wrapped with ' if it isEqualTo for a string field . */
private Object valueOf ( String columnName , Object value ) { } }

implementation: java . lang . reflect . Field field ; try { field = tableObject . getDeclaredField ( columnName ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( String . format ( "%s isEqualTo not a field found in %s" , columnName , tableObject ) ) ; } return field . getType ( ) == String . class ? String . format ( "\'%s\'" , value ) : value ;


signature:
public class SqliteInteger { /** * Checks if a TypeMirror is mapped to Sqlite Integer Type
 * @ param typeMirror The TypeMirror to check if it ' s an Sqlite Integer Type
 * @ return true if it maps to Sqlite Integer false otherwise */
boolean isTypeOf ( TypeMirror typeMirror ) { } }

implementation: if ( integerKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( integerObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ;


signature:
public class ShillelaghUtil { /** * Takes an object and serializes it to a byte array . Don ' t enforce that it extends serializable
 * to allow for lists and maps to be passed in .
 * @ param object The object to serialize . Must implement { @ link java . io . Serializable }
 * @ return The object as a byte array . */
public static < T > byte [ ] serialize ( T object ) { } }

implementation: try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; ObjectOutputStream objectOutputStream = new ObjectOutputStream ( byteArrayOutputStream ) ; objectOutputStream . writeObject ( object ) ; return byteArrayOutputStream . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; }


signature:
public class ShillelaghUtil { /** * De - serialize a byte array back to it ' s original object .
 * @ param bytes The bytes that where serialized from an object .
 * @ param < K > The type the bytes should be serialised back too .
 * @ return The de - serialized object . */
public static < K > K deserialize ( byte [ ] bytes ) { } }

implementation: try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( byteArrayInputStream ) ; @ SuppressWarnings ( "unchecked" ) final K k = ( K ) objectInputStream . readObject ( ) ; return k ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; }


signature:
public class ShillelaghUtil { /** * Takes a class type and constructs it . If the class does not have an empty constructor this
 * will
 * find the parametrized constructor and use nulls and default values to construct the class .
 * @ param clazz The class to construct .
 * @ param < T > The type of the class to construct .
 * @ return The constructed object . */
@ SuppressWarnings ( "unchecked" ) public static < T > T createInstance ( Class < T > clazz ) { } }

implementation: if ( clazz . isInterface ( ) ) { if ( clazz == List . class ) { return ( T ) new ArrayList ( ) ; } else if ( clazz == Map . class ) { return ( T ) new HashMap ( ) ; } throw new UnsupportedOperationException ( "Interface types can not be instantiated." ) ; } ObjectInstantiator instantiator = OBJENESIS . getInstantiatorOf ( clazz ) ; return ( T ) instantiator . newInstance ( ) ;


signature:
public class ShillelaghProcessor { /** * Check if the element has the @ Id annotation if it does use that for it ' s id */
private void checkForTableId ( TableObject tableObject , Element element ) { } }

implementation:
// Check if user wants to use an id other than _ id
Id idAnnotation = element . getAnnotation ( Id . class ) ; if ( idAnnotation != null ) { if ( element . asType ( ) . getKind ( ) != TypeKind . LONG && ! ( "java.lang.Long" . equals ( element . asType ( ) . toString ( ) ) ) ) { logger . e ( "@Id must be on a long" ) ; } // Id attribute set and continue
String columnName = Strings . isBlank ( idAnnotation . name ( ) ) ? element . getSimpleName ( ) . toString ( ) : idAnnotation . name ( ) ; final TableColumn idColumn = new TableColumn ( columnName , element . getSimpleName ( ) . toString ( ) , element . asType ( ) . toString ( ) , SqliteType . INTEGER ) ; tableObject . setIdColumn ( idColumn ) ; }


signature:
public class ShillelaghProcessor { /** * Check if the element has a @ Field annotation if it does parse it and
 * add it to the table object */
private void checkForFields ( TableObject tableObject , Element columnElement ) { } }

implementation:
Column columnAnnotation = columnElement . getAnnotation ( Column . class ) ; if ( columnAnnotation == null ) return ; // Convert the element from a field to a type
final Element typeElement = typeUtils . asElement ( columnElement . asType ( ) ) ; final String type = typeElement == null ? columnElement . asType ( ) . toString ( ) : elementUtils . getBinaryName ( ( TypeElement ) typeElement ) . toString ( ) ; TableColumn tableColumn = new TableColumn ( columnElement , type , columnAnnotation . name ( ) ) ; if ( tableColumn . isBlob ( ) && ! tableColumn . isByteArray ( ) ) { String columnType = columnElement . asType ( ) . toString ( ) ; logger . d ( "Column Element Type: " + columnType ) ; if ( ! checkForSuperType ( columnElement , Serializable . class ) && ! columnType . equals ( "java.lang.Byte[]" ) && ! columnType . startsWith ( "java.util.Map" ) && ! columnType . startsWith ( "java.util.List" ) ) { logger . e ( String . format ( "%s in %s is not Serializable and will not be able to be converted to a byte array" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } } else if ( tableColumn . isOneToMany ( ) ) { // List < T > should only have one generic type . Get that type and make sure
// it has @ Table annotation
TypeMirror typeMirror = ( ( DeclaredType ) columnElement . asType ( ) ) . getTypeArguments ( ) . get ( 0 ) ; if ( typeUtils . asElement ( typeMirror ) . getAnnotation ( Table . class ) == null ) { logger . e ( "One to many relationship in class %s where %s is not annotated with @Table" , tableObject . getTableName ( ) , tableColumn . getColumnName ( ) ) ; } oneToManyCache . put ( typeMirror . toString ( ) , tableObject ) ; TypeElement childColumnElement = elementUtils . getTypeElement ( typeMirror . toString ( ) ) ; tableColumn . setType ( getClassName ( childColumnElement , getPackageName ( childColumnElement ) ) ) ; } else if ( tableColumn . getSqlType ( ) == SqliteType . UNKNOWN ) { @ SuppressWarnings ( "ConstantConditions" ) Table annotation = typeElement . getAnnotation ( Table . class ) ; if ( annotation == null ) { logger . e ( String . format ( "%s in %s needs to be marked as a blob or should be " + "annotated with @Table" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } tableColumn . setOneToOne ( true ) ; } tableObject . addColumn ( tableColumn ) ;


signature:
public class ShillelaghProcessor { /** * Checks for a supertype returns true if element has a supertype */
private boolean checkForSuperType ( Element element , Class type ) { } }

implementation: List < ? extends TypeMirror > superTypes = typeUtils . directSupertypes ( element . asType ( ) ) ; for ( TypeMirror superType : superTypes ) { if ( superType . toString ( ) . equals ( type . getName ( ) ) ) { return true ; } } return false ;


signature:
public class TableObject { /** * Get table schema */
private String getSchema ( ) { } }

implementation:
StringBuilder sb = new StringBuilder ( ) ; Iterator < TableColumn > iterator = columns . iterator ( ) ; while ( iterator . hasNext ( ) ) { TableColumn column = iterator . next ( ) ; if ( column . isOneToMany ( ) ) { if ( ! iterator . hasNext ( ) ) { // remove the extra " , " after one to many
int length = sb . length ( ) ; sb . replace ( length - 2 , length , "" ) ; } continue ; } sb . append ( column ) ; if ( iterator . hasNext ( ) ) { sb . append ( ", " ) ; } } // writes out id _ missing for logging , the actual idMissing check happens
// by the annotation processor .
String idCol = idColumn == null ? "id_missing" : idColumn . getColumnName ( ) ; return String . format ( CREATE_TABLE_DEFAULT , getTableName ( ) , idCol , sb . toString ( ) ) ;


signature:
public class TableObject { /** * Create the java functions required for the internal class */
void brewJava ( Writer writer ) throws IOException { } }

implementation:
logger . d ( "brewJava" ) ; JavaWriter javaWriter = new JavaWriter ( writer ) ; javaWriter . setCompressingTypes ( false ) ; javaWriter . emitSingleLineComment ( "Generated code from Shillelagh. Do not modify!" ) . emitPackage ( classPackage ) /* Knows nothing of android types , must use strings . */
. emitImports ( "android.content.ContentValues" , "android.database.Cursor" , "android.database.DatabaseUtils" , "android.database.sqlite.SQLiteDatabase" ) . emitImports ( ShillelaghUtil . class , ByteArrayInputStream . class , ByteArrayOutputStream . class , IOException . class , ObjectInputStream . class , ObjectOutputStream . class , LinkedList . class , Date . class , List . class ) . beginType ( className , "class" , EnumSet . of ( PUBLIC , FINAL ) ) ; if ( this . isChildTable ) { emitParentInsert ( javaWriter ) ; emitSelectAll ( javaWriter ) ; } emitInsert ( javaWriter ) ; emitOneToOneInsert ( javaWriter ) ; emitGetId ( javaWriter ) ; emitCreateTable ( javaWriter ) ; emitDropTable ( javaWriter ) ; emitUpdate ( javaWriter ) ; emitUpdateColumnId ( javaWriter ) ; emitDeleteWithId ( javaWriter ) ; emitDeleteWithObject ( javaWriter ) ; emitMapCursorToObject ( javaWriter ) ; emitSingleMap ( javaWriter ) ; emitSelectById ( javaWriter ) ; javaWriter . endType ( ) ;


signature:
public class TableObject { /** * Create a way to get an id for foreign keys */
private void emitGetId ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitGetId" ) ; javaWriter . beginMethod ( "long" , GET_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "value" ) . emitStatement ( "return value.%s" , idColumn . getMemberName ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for creating the table */
private void emitCreateTable ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitCreateTable" ) ; javaWriter . beginMethod ( "void" , $$CREATE_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "SQLiteDatabase" , "db" ) . emitStatement ( "db.execSQL(\"%s\")" , getSchema ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function dropping the table */
private void emitDropTable ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitDropTable" ) ; javaWriter . beginMethod ( "void" , $$DROP_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "SQLiteDatabase" , "db" ) . emitStatement ( "db.execSQL(\"DROP TABLE IF EXISTS %s\")" , getTableName ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for inserting a new value into the database */
private void emitInsert ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitInsert" ) ; String tableName = getTableName ( ) ; javaWriter . beginMethod ( "void" , $$INSERT_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "ContentValues values = new ContentValues()" ) ; List < TableColumn > childColumns = Lists . newLinkedList ( ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . isBlob ( ) && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s(element.%s))" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( "%s%s.%s(element.%s, db)" , column . getType ( ) , $$SUFFIX , INSERT_ONE_TO_ONE , column . getColumnName ( ) ) . emitStatement ( "values.put(\"%s\", %s%s.%s(element.%s))" , columnName , column . getType ( ) , $$SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s.getTime())" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { childColumns . add ( column ) ; } else if ( ! column . isOneToManyChild ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s)" , columnName , memberName ) ; } } javaWriter . emitStatement ( "db.insert(\"%s\", null, values)" , tableName ) ; if ( ! childColumns . isEmpty ( ) ) { javaWriter . emitStatement ( "long id = DatabaseUtils.longForQuery(db, " + "\"SELECT ROWID FROM %s ORDER BY ROWID DESC LIMIT 1\", null)" , tableName ) ; } for ( TableColumn childColumn : childColumns ) { javaWriter . emitStatement ( "%s%s.%s(id, element.%s, db)" , childColumn . getType ( ) , $$SUFFIX , PARENT_INSERT_FUNCTION , childColumn . getMemberName ( ) ) ; } javaWriter . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for updating an object */
private void emitUpdate ( JavaWriter javaWriter ) throws IOException { } }

implementation:
logger . d ( "emitUpdate" ) ; javaWriter . beginMethod ( "void" , $$UPDATE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "ContentValues values = new ContentValues()" ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . getSqlType ( ) == SqliteType . BLOB && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s(element.%s))" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s%s.%s(element.%s))" , columnName , column . getType ( ) , $$SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s.getTime())" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { javaWriter . beginControlFlow ( "for (%s child : element.%s)" , column . getType ( ) . replace ( "$" , "." ) , column . getColumnName ( ) ) . emitStatement ( "%s%s.%s(child, db)" , column . getType ( ) , $$SUFFIX , $$UPDATE_OBJECT_FUNCTION ) . endControlFlow ( ) ; } else if ( column . isOneToManyChild ( ) ) { // TODO : actually no way of actually updating this value directly add a wrapper ?
} else { javaWriter . emitStatement ( "values.put(\"%s\", element.%s)" , columnName , memberName ) ; } } javaWriter . emitStatement ( "db.update(\"%s\", values, \"%s = \" + element.%s, null)" , getTableName ( ) , idColumn . getColumnName ( ) , idColumn . getMemberName ( ) ) ; javaWriter . endMethod ( ) ;


signature:
public class TableObject { /** * Updates the id of the object to the last insert */
private void emitUpdateColumnId ( JavaWriter javaWriter ) throws IOException { } }

implementation:
logger . d ( "emitUpdateColumnId" ) ; // Updates the column id for the last inserted row
javaWriter . beginMethod ( "void" , $$UPDATE_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "long id = DatabaseUtils.longForQuery(db, \"%s\", null)" , String . format ( GET_ID_OF_LAST_INSERTED_ROW_SQL , getTableName ( ) ) ) . emitStatement ( "element.%s = id" , idColumn . getMemberName ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for deleting an object by id */
private void emitDeleteWithId ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitDeleteWithId" ) ; javaWriter . beginMethod ( "void" , $$DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "Long" , "id" , "SQLiteDatabase" , "db" ) . emitStatement ( "db.delete(\"%s\", \"%s = \" + id, null)" , getTableName ( ) , idColumn . getColumnName ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for deleting an object from the table */
private void emitDeleteWithObject ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitDeleteWithObject" ) ; javaWriter . beginMethod ( "void" , $$DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "%s(element.%s, db)" , $$DELETE_OBJECT_FUNCTION , idColumn . getMemberName ( ) ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates the function for mapping a cursor to the object after executing a sql statement */
private void emitMapCursorToObject ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitMapCursorToObject" ) ; final String targetClass = getTargetClass ( ) ; javaWriter . beginMethod ( "List<" + targetClass + ">" , $$MAP_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "Cursor" , "cursor" , "SQLiteDatabase" , "db" ) . emitStatement ( "List<%s> tableObjects = new LinkedList<%s>()" , targetClass , targetClass ) . beginControlFlow ( "if (cursor.moveToFirst())" ) . beginControlFlow ( "while (!cursor.isAfterLast())" ) . emitStatement ( "%s tableObject = %s(cursor, db)" , targetClass , $$MAP_SINGLE_FUNCTION ) . emitStatement ( "tableObjects.add(tableObject)" ) . emitStatement ( "cursor.moveToNext()" ) . endControlFlow ( ) . endControlFlow ( ) . emitStatement ( "return tableObjects" ) . endMethod ( ) ;


signature:
public class TableObject { /** * Creates function for getting an object by value */
private void emitSelectById ( JavaWriter javaWriter ) throws IOException { } }

implementation: logger . d ( "emitSelectById" ) ; javaWriter . beginMethod ( getTargetClass ( ) , $$GET_OBJECT_BY_ID , EnumSet . of ( PUBLIC , STATIC ) , "long" , "id" , "SQLiteDatabase" , "db" ) . emitStatement ( "Cursor cursor = db.rawQuery(\"SELECT * FROM %s WHERE %s  = id\", null)" , getTableName ( ) , idColumn . getColumnName ( ) ) . emitStatement ( "%s value = %s(cursor, db).get(0)" , getTargetClass ( ) , $$MAP_OBJECT_FUNCTION ) . emitStatement ( "cursor.close()" ) . emitStatement ( "return value" ) . endMethod ( ) ;


signature:
public class Builder { /** * Executes a query and returns the results wrapped in an observable */
public final Observable < T > toObservable ( ) { } }

implementation: if ( ! HAS_RX_JAVA ) { throw new RuntimeException ( "RxJava not available! Add RxJava to your build to use this feature" ) ; } return shillelagh . getObservable ( tableObject , new CursorLoader ( ) { @ Override public Cursor getCursor ( ) { return shillelagh . rawQuery ( query . toString ( ) ) ; } } ) ;


signature:
public class Builder { /** * Check to ensure that the column name provided is valid */
final void checkColumnName ( String columnName ) { } }

implementation: try { tableObject . getDeclaredField ( columnName ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( String . format ( "%s isEqualTo not a field found in %s" , columnName , tableObject ) ) ; }


signature:
public class Strings { /** * Checks if a string there , if not returns the default string */
static String valueOrDefault ( String string , String defaultString ) { } }

implementation: return isBlank ( string ) ? defaultString : string ;


signature:
public class Strings { /** * Capitalizes the first letter of the string passed in */
static String capitalize ( String string ) { } }

implementation: if ( isBlank ( string ) ) { return "" ; } char first = string . charAt ( 0 ) ; if ( Character . isUpperCase ( first ) ) { return string ; } else { return Character . toUpperCase ( first ) + string . substring ( 1 ) ; }


signature:
public class SqliteReal { /** * Checks if a TypeMirror is mapped to Sqlite Type
 * @ param typeMirror The TypeMirror to check if it ' s an Sqlite Type
 * @ return true if it maps to the Sqlite Object false otherwise */
boolean isTypeOf ( TypeMirror typeMirror ) { } }

implementation: if ( realKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( realObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ;


signature:
public class OrderByBuilder { /** * Order the results in descending order */
public Builder < T > descending ( ) { } }

implementation: this . query . append ( " DESC" ) ; return new Builder < T > ( shillelagh , tableObject , query ) ;


signature:
public class OneWireTemperatureSensor { /** * Read temperature from the sensors .
 * @ return temperature
 * @ throws IOException
 * @ see { @ link TemperatureSensor # readTemperature ( ) } */
public float readTemperature ( ) throws IOException { } }

implementation: byte [ ] encoded = Files . readAllBytes ( new File ( deviceFile , "w1_slave" ) . toPath ( ) ) ; String tmp = new String ( encoded ) ; int tmpIndex = tmp . indexOf ( "t=" ) ; if ( tmpIndex < 0 ) { throw new IOException ( "Could not read temperature!" ) ; } return Integer . parseInt ( tmp . substring ( tmpIndex + 2 ) . trim ( ) ) / 1000f ;


signature:
public class CursorFunctions { /** * Maps a type to the corresponding Cursor get function . For mapping objects between the database
 * and java . If a type is not found getBlob is returned */
public static String get ( String type ) { } }

implementation: final String returnValue = SUPPORTED_CURSOR_METHODS . get ( type ) ; return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS . get ( BLOB ) ;


signature:
public class ShillelaghLogger { /** * Print out debug logs , will only print if { @ link shillelagh . internal . ShillelaghProcessor # DEBUG }
 * is true . */
void d ( String message , Object ... args ) { } }

implementation: if ( DEBUG ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; }


signature:
public class ShillelaghLogger { /** * Print out notes */
void n ( String message , Object ... args ) { } }

implementation: messenger . printMessage ( NOTE , formatString ( message , args ) ) ;


signature:
public class ShillelaghLogger { /** * Print out errors , this will stop the build from succeeding */
void e ( String message , Object ... args ) { } }

implementation: messenger . printMessage ( ERROR , formatString ( message , args ) ) ;


signature:
public class Bundle { /** * Returns all icon fonts from bundle .
 * @ return List with the fonts . */
public static List < IconFont > getIconFonts ( ) { } }

implementation: List < IconFont > list = new ArrayList < > ( ) ; list . add ( GoogleMaterialDesignIcons . getIconFont ( ) ) ; list . add ( Elusive . getIconFont ( ) ) ; list . add ( Entypo . getIconFont ( ) ) ; list . add ( FontAwesome . getIconFont ( ) ) ; list . add ( Iconic . getIconFont ( ) ) ; list . add ( Typicons . getIconFont ( ) ) ; return list ;


signature:
public class Bundle { /** * Returns all icons from bundle .
 * @ return List with the icons . */
public static List < IconCode > getIcons ( ) { } }

implementation: List < IconCode > list = new ArrayList < > ( ) ; for ( IconCode icon : GoogleMaterialDesignIcons . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Elusive . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Entypo . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : FontAwesome . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Iconic . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Typicons . values ( ) ) { list . add ( icon ) ; } return list ;


signature:
public class EulersDiffEqSolver { /** * Return the next data point in the approximation of the solution .
 * @ param h
 * the width of the interval */
@ Override public DataPoint nextPoint ( final float h ) { } }

implementation: m_fY += h * m_aEquation . at ( m_fX , m_fY ) ; m_fX += h ; return new DataPoint ( m_fX , m_fY ) ;


signature:
public class InterpolationPolynomial { /** * Add new data point : Augment the divided difference table by appending a new
 * entry at the bottom of each column .
 * @ param dataPoint
 * the new data point */
public void addDataPoint ( final DataPoint dataPoint ) { } }

implementation: if ( m_nDataPoints >= m_aData . length ) return ; m_aData [ m_nDataPoints ] = dataPoint ; m_aDivDiff [ m_nDataPoints ] [ 0 ] = dataPoint . getY ( ) ; ++ m_nDataPoints ; for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { final int bottom = m_nDataPoints - order - 1 ; final float numerator = m_aDivDiff [ bottom + 1 ] [ order - 1 ] - m_aDivDiff [ bottom ] [ order - 1 ] ; final float denominator = m_aData [ bottom + order ] . getX ( ) - m_aData [ bottom ] . getX ( ) ; m_aDivDiff [ bottom ] [ order ] = numerator / denominator ; }


signature:
public class InterpolationPolynomial { /** * Return the value of the polynomial interpolation function at x .
 * ( Implementation of Evaluatable . )
 * @ param x
 * the value of x
 * @ return the value of the function at x */
public float at ( final float x ) { } }

implementation:
if ( m_nDataPoints < 2 ) return Float . NaN ; float y = m_aDivDiff [ 0 ] [ 0 ] ; float xFactor = 1 ; // Compute the value of the function .
for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { xFactor = xFactor * ( x - m_aData [ order - 1 ] . getX ( ) ) ; y = y + xFactor * m_aDivDiff [ 0 ] [ order ] ; } return y ;


signature:
public class SldEditorWidgetViewImpl { /** * Create the Sld Editor layout and attach handlers to the actions .
 * @ return the Sld Editor layout */
public VLayout createSldEditorLayout ( ) { } }

implementation:
final VLayout vLayout = new VLayout ( ) ; toolStrip = new ToolStrip ( ) ; toolStrip . setWidth100 ( ) ; codeMirrorPanel = new CodeMirrorPanel ( ) ; WidgetCanvas canvas = new WidgetCanvas ( codeMirrorPanel ) ; canvas . setWidth100 ( ) ; canvas . setHeight100 ( ) ; vLayout . addMember ( toolStrip ) ; vLayout . addMember ( canvas ) ; ToolStripButton saveButton = new ToolStripButton ( ) ; saveButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/disk.png" ) ; saveButton . setTitle ( msg . saveButtonTitle ( ) ) ; saveButton . setTooltip ( msg . saveButtonTooltip ( ) ) ; saveButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onSaveButton ( ) ; } } ) ; ToolStripButton cancelButton = new ToolStripButton ( ) ; cancelButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/cancel.png" ) ; cancelButton . setTitle ( msg . cancelButtonTitle ( ) ) ; cancelButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onCancelButton ( ) ; } } ) ; ToolStripButton validateButton = new ToolStripButton ( ) ; validateButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/tick.png" ) ; validateButton . setTitle ( msg . validateButtonTitle ( ) ) ; validateButton . setTooltip ( msg . validateButtonTooltip ( ) ) ; validateButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onValidateButton ( ) ; } } ) ; ToolStripButton formatBtn = new ToolStripButton ( ) ; formatBtn . setIcon ( "[ISOMORPHIC]/" + "icons/silk/text_align_left.png" ) ; formatBtn . setTitle ( msg . formatButtonTitle ( ) ) ; formatBtn . setTooltip ( msg . formatButtonTooltip ( ) ) ; formatBtn . addClickHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { presenter . onFormatButton ( ) ; } } ) ; selectTemplate = new SelectItem ( ) ; selectTemplate . setTitle ( msg . templateSelectTitle ( ) ) ; selectTemplate . setTooltip ( msg . templateSelectTooltip ( ) ) ; selectTemplate . setWidth ( 200 ) ; selectTemplate . addChangeHandler ( new ChangeHandler ( ) { @ Override public void onChange ( ChangeEvent changeEvent ) { presenter . onTemplateSelect ( ( String ) changeEvent . getValue ( ) ) ; } } ) ; toolStrip . addFormItem ( selectTemplate ) ; toolStrip . addButton ( saveButton ) ; toolStrip . addButton ( validateButton ) ; toolStrip . addButton ( formatBtn ) ; /* * toolStrip . addSeparator ( ) ; toolStrip . addButton ( saveButton ) ; */
toolStrip . addFill ( ) ; toolStrip . addButton ( cancelButton ) ; return vLayout ;


signature:
public class SldEditorPanel { /** * Create background content decoration for the widget tab .
 * @ return HTMLFlow background content . */
private HTMLFlow getBackgroundDecoration ( ) { } }

implementation:
// Show some background content in the tab .
HTMLFlow htmlFlow = new HTMLFlow ( ) ; htmlFlow . setWidth100 ( ) ; htmlFlow . setHeight100 ( ) ; String contents = "
GEOMAJAS
" + "
SLD-Editor
" + "
EXPERT-mode
" ; htmlFlow . setContents ( contents ) ; return htmlFlow ;


signature:
public class IntPower { /** * Compute and return x ^ power .
 * @ param px
 * @ param pexponent
 * the integer power
 * @ return x ^ power */
public static double raise ( final double px , final int pexponent ) { } }

implementation:
double x = px ; int exponent = pexponent ; if ( exponent < 0 ) return 1 / raise ( x , - exponent ) ; double power = 1 ; // Loop to compute x ^ exponent .
while ( exponent > 0 ) { // Is the rightmost exponent bit a 1?
if ( ( exponent & 1 ) == 1 ) power *= x ; // Square x and shift the exponent 1 bit to the right .
x *= x ; exponent >>= 1 ; } return power ;


signature:
public class ColumnVector { /** * Copy the values of this matrix .
 * @ return the copied values */
public float [ ] copyValues1D ( ) { } }

implementation: final float v [ ] = new float [ m_nRows ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { v [ r ] = m_aValues [ r ] [ 0 ] ; } return v ;


signature:
public class ColumnVector { /** * Set this column vector from an array of values .
 * @ param values
 * the array of values */
protected void set ( final float values [ ] ) { } }

implementation: this . m_nRows = values . length ; this . m_nCols = 1 ; this . m_aValues = new float [ m_nRows ] [ 1 ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { this . m_aValues [ r ] [ 0 ] = values [ r ] ; }


signature:
public class ColumnVector { /** * Compute the Euclidean norm .
 * @ return the norm */
public float norm ( ) { } }

implementation: double t = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float v = m_aValues [ r ] [ 0 ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ;


signature:
public class ColumnVector { /** * Print the vector values . */
public void print ( ) { } }

implementation: for ( int r = 0 ; r < m_nRows ; ++ r ) { System . out . print ( "  " + m_aValues [ r ] [ 0 ] ) ; } System . out . println ( ) ;


signature:
public class BigFunctions { /** * Compute x ^ exponent to a given scale . Uses the same algorithm as class
 * numbercruncher . mathutils . IntPower .
 * @ param px
 * the value x
 * @ param pexponent
 * the exponent value
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
public static BigDecimal intPower ( @ Nonnull final BigDecimal px , final long pexponent , final int scale ) { } }

implementation:
BigDecimal x = px ; long exponent = pexponent ; // If the exponent is negative , compute 1 / ( x ^ - exponent ) .
if ( exponent < 0 ) { return BigDecimal . ONE . divide ( intPower ( x , - exponent , scale ) , scale , RoundingMode . HALF_EVEN ) ; } BigDecimal power = BigDecimal . ONE ; // Loop to compute value ^ exponent .
while ( exponent > 0 ) { // Is the rightmost bit a 1?
if ( ( exponent & 1 ) == 1 ) { power = power . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; } // Square x and shift exponent 1 bit to the right .
x = x . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; exponent >>= 1 ; Thread . yield ( ) ; } return power ;


signature:
public class BigFunctions { /** * Compute the integral root of x to a given scale , x & ge ; 0 . Use Newton ' s
 * algorithm .
 * @ param px
 * the value of x
 * @ param index
 * the integral root value
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
public static BigDecimal intRoot ( @ Nonnull final BigDecimal px , final long index , final int scale ) { } }

implementation:
BigDecimal x = px ; // Check that x > = 0.
if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( "x < 0: " + x ) ; } final int sp1 = scale + 1 ; final BigDecimal n = x ; final BigDecimal i = BigDecimal . valueOf ( index ) ; final BigDecimal im1 = BigDecimal . valueOf ( index - 1 ) ; final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; BigDecimal xPrev ; // The initial approximation is x / index .
x = x . divide ( i , scale , RoundingMode . HALF_EVEN ) ; // Loop until the approximations converge
// ( two successive approximations are equal after rounding ) .
do { // x ^ ( index - 1)
final BigDecimal xToIm1 = intPower ( x , index - 1 , sp1 ) ; // x ^ index
final BigDecimal xToI = x . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // n + ( index - 1 ) * ( x ^ index )
final BigDecimal numerator = n . add ( im1 . multiply ( xToI ) ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // ( index * ( x ^ ( index - 1 ) )
final BigDecimal denominator = i . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // x = ( n + ( index - 1 ) * ( x ^ index ) ) / ( index * ( x ^ ( index - 1 ) ) )
xPrev = x ; x = numerator . divide ( denominator , sp1 , RoundingMode . DOWN ) ; Thread . yield ( ) ; } while ( x . subtract ( xPrev ) . abs ( ) . compareTo ( tolerance ) > 0 ) ; return x ;


signature:
public class BigFunctions { /** * Compute e ^ x to a given scale . Break x into its whole and fraction parts and
 * compute ( e ^ ( 1 + fraction / whole ) ) ^ whole using Taylor ' s formula .
 * @ param x
 * the value of x
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
public static BigDecimal exp ( final BigDecimal x , final int scale ) { } }

implementation:
// e ^ 0 = 1
if ( x . signum ( ) == 0 ) { return BigDecimal . ONE ; } // If x is negative , return 1 / ( e ^ - x ) .
if ( x . signum ( ) == - 1 ) { return BigDecimal . ONE . divide ( exp ( x . negate ( ) , scale ) , scale , RoundingMode . HALF_EVEN ) ; } // Compute the whole part of x .
BigDecimal xWhole = x . setScale ( 0 , RoundingMode . DOWN ) ; // If there isn ' t a whole part , compute and return e ^ x .
if ( xWhole . signum ( ) == 0 ) return _expTaylor ( x , scale ) ; // Compute the fraction part of x .
final BigDecimal xFraction = x . subtract ( xWhole ) ; // z = 1 + fraction / whole
final BigDecimal z = BigDecimal . ONE . add ( xFraction . divide ( xWhole , scale , RoundingMode . HALF_EVEN ) ) ; // t = e ^ z
final BigDecimal t = _expTaylor ( z , scale ) ; final BigDecimal maxLong = BigDecimal . valueOf ( Long . MAX_VALUE ) ; BigDecimal result = BigDecimal . ONE ; // Compute and return t ^ whole using intPower ( ) .
// If whole > Long . MAX _ VALUE , then first compute products
// of e ^ Long . MAX _ VALUE .
while ( xWhole . compareTo ( maxLong ) >= 0 ) { result = result . multiply ( intPower ( t , Long . MAX_VALUE , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; xWhole = xWhole . subtract ( maxLong ) ; Thread . yield ( ) ; } return result . multiply ( intPower ( t , xWhole . longValue ( ) , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ;


signature:
public class BigFunctions { /** * Compute e ^ x to a given scale by the Taylor series .
 * @ param x
 * the value of x
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
private static BigDecimal _expTaylor ( final BigDecimal x , final int scale ) { } }

implementation:
BigDecimal factorial = BigDecimal . ONE ; BigDecimal xPower = x ; BigDecimal sumPrev ; // 1 + x
BigDecimal sum = x . add ( BigDecimal . ONE ) ; // Loop until the sums converge
// ( two successive sums are equal after rounding ) .
int i = 2 ; do { // x ^ i
xPower = xPower . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; factorial = factorial . multiply ( BigDecimal . valueOf ( i ) ) ; // x ^ i / i !
final BigDecimal term = xPower . divide ( factorial , scale , RoundingMode . HALF_EVEN ) ; // sum = sum + x ^ i / i !
sumPrev = sum ; sum = sum . add ( term ) ; ++ i ; Thread . yield ( ) ; } while ( sum . compareTo ( sumPrev ) != 0 ) ; return sum ;


signature:
public class BigFunctions { /** * Compute the natural logarithm of x to a given scale , x & gt ; 0.
 * @ param x
 * Base value
 * @ param scale
 * Scale
 * @ return ln ( x ) */
public static BigDecimal ln ( @ Nonnull final BigDecimal x , final int scale ) { } }

implementation:
// Check that x > 0.
if ( x . signum ( ) <= 0 ) { throw new IllegalArgumentException ( "x <= 0: " + x ) ; } // The number of digits to the left of the decimal point .
final int magnitude = x . toString ( ) . length ( ) - x . scale ( ) - 1 ; if ( magnitude < 3 ) { return _lnNewton ( x , scale ) ; } // Compute magnitude * ln ( x ^ ( 1 / magnitude ) ) .
// x ^ ( 1 / magnitude )
final BigDecimal root = intRoot ( x , magnitude , scale ) ; // ln ( x ^ ( 1 / magnitude ) )
final BigDecimal lnRoot = _lnNewton ( root , scale ) ; // magnitude * ln ( x ^ ( 1 / magnitude ) )
return BigDecimal . valueOf ( magnitude ) . multiply ( lnRoot ) . setScale ( scale , RoundingMode . HALF_EVEN ) ;


signature:
public class BigFunctions { /** * Compute the natural logarithm of x to a given scale , x > 0 . Use Newton ' s
 * algorithm . */
private static BigDecimal _lnNewton ( @ Nonnull final BigDecimal px , final int scale ) { } }

implementation:
BigDecimal x = px ; final int sp1 = scale + 1 ; final BigDecimal n = x ; BigDecimal term ; // Convergence tolerance = 5 * ( 10 ^ - ( scale + 1 ) )
final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge
// ( two successive approximations are within the tolerance ) .
do { // e ^ x
final BigDecimal eToX = exp ( x , sp1 ) ; // ( e ^ x - n ) / e ^ x
term = eToX . subtract ( n ) . divide ( eToX , sp1 , RoundingMode . DOWN ) ; // x - ( e ^ x - n ) / e ^ x
x = x . subtract ( term ) ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return x . setScale ( scale , RoundingMode . HALF_EVEN ) ;


signature:
public class BigFunctions { /** * Compute the arctangent of x to a given scale , | x | & lt ; 1
 * @ param x
 * the value of x
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
public static BigDecimal arctan ( @ Nonnull final BigDecimal x , final int scale ) { } }

implementation:
// Check that | x | < 1.
if ( x . abs ( ) . compareTo ( BigDecimal . ONE ) >= 0 ) { throw new IllegalArgumentException ( "|x| >= 1: " + x ) ; } // If x is negative , return - arctan ( - x ) .
if ( x . signum ( ) == - 1 ) { return arctan ( x . negate ( ) , scale ) . negate ( ) ; } return _arctanTaylor ( x , scale ) ;


signature:
public class BigFunctions { /** * Compute the arctangent of x to a given scale by the Taylor series , | x | < 1
 * @ param x
 * the value of x
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
private static BigDecimal _arctanTaylor ( final BigDecimal x , final int scale ) { } }

implementation:
final int sp1 = scale + 1 ; int i = 3 ; boolean addFlag = false ; BigDecimal power = x ; BigDecimal sum = x ; BigDecimal term ; // Convergence tolerance = 5 * ( 10 ^ - ( scale + 1 ) )
final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge
// ( two successive approximations are within the tolerance ) .
do { // x ^ i
power = power . multiply ( x ) . multiply ( x ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // ( x ^ i ) / i
term = power . divide ( BigDecimal . valueOf ( i ) , sp1 , RoundingMode . HALF_EVEN ) ; // sum = sum + - ( x ^ i ) / i
sum = addFlag ? sum . add ( term ) : sum . subtract ( term ) ; i += 2 ; addFlag = ! addFlag ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return sum ;


signature:
public class BigFunctions { /** * Compute the square root of x to a given scale , x & ge ; 0 . Use Newton ' s
 * algorithm .
 * @ param x
 * the value of x
 * @ param scale
 * the desired scale of the result
 * @ return the result value */
public static BigDecimal sqrt ( @ Nonnull final BigDecimal x , final int scale ) { } }

implementation:
// Check that x > = 0.
if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( "x < 0: " + x ) ; } // n = x * ( 10 ^ ( 2 * scale ) )
final BigInteger n = x . movePointRight ( scale << 1 ) . toBigInteger ( ) ; // The first approximation is the upper half of n .
final int bits = ( n . bitLength ( ) + 1 ) >> 1 ; BigInteger ix = n . shiftRight ( bits ) ; BigInteger ixPrev ; // Loop until the approximations converge
// ( two successive approximations are equal after rounding ) .
do { ixPrev = ix ; // x = ( x + n / x ) / 2
ix = ix . add ( n . divide ( ix ) ) . shiftRight ( 1 ) ; Thread . yield ( ) ; } while ( ix . compareTo ( ixPrev ) != 0 ) ; return new BigDecimal ( ix , scale ) ;


signature:
public class AbstractPiFormula { /** * Print the string containing the digits of pi .
 * @ param piString
 * the string containing the digits of pi */
protected void printPi ( final String piString ) { } }

implementation:
System . out . print ( "\npi = " + piString . substring ( 0 , 2 ) ) ; int index = 2 ; int line = 0 ; int group = 0 ; final int length = piString . length ( ) ; // Loop for each group of 5 digits
while ( index + 5 < length ) { System . out . print ( piString . substring ( index , index + 5 ) + " " ) ; index += 5 ; // End of line after 10 groups .
if ( ++ group == 10 ) { System . out . println ( ) ; // Print a blank line after 10 lines .
if ( ++ line == 10 ) { System . out . println ( ) ; line = 0 ; } System . out . print ( "       " ) ; group = 0 ; } } // Print the last partial line .
if ( index < length ) { System . out . println ( piString . substring ( index ) ) ; }


signature:
public class AbstractPiFormula { /** * Return a timestamp string that contains the elapsed time period .
 * @ param time
 * the starting time of the period
 * @ return the timestamp string */
protected String timestamp ( final long time ) { } }

implementation:
// Current time followed by elapsed time as ( hh : mm : ss ) .
final LocalDateTime aLDT = PDTFactory . getCurrentLocalDateTime ( ) ; final LocalDateTime aOld = PDTFactory . createLocalDateTime ( time ) ; return aLDT . toLocalTime ( ) . toString ( ) + " (" + Duration . between ( aOld , aLDT ) . toString ( ) + ")" ;


signature:
public class Buckets { /** * Set the minimum and maximum random values .
 * @ param rMin
 * the minimum value
 * @ param rMax
 * the maximum value */
public void setLimits ( final float rMin , final float rMax ) { } }

implementation: this . m_fMin = rMin ; this . m_fMax = rMax ; this . m_fWidth = ( rMax - rMin ) / m_n ;


signature:
public class Buckets { /** * Determine a random value ' s interval and count it .
 * @ param r
 * the random value */
public void put ( final float r ) { } }

implementation:
// Ignore the value if it ' s out of range .
if ( ( r < m_fMin ) || ( r > m_fMax ) ) return ; // Determine its interval and count it .
final int i = ( int ) ( ( r - m_fMin ) / m_fWidth ) ; ++ m_aCounters [ i ] ;


signature:
public class Buckets { /** * Print the counter values as a horizontal bar chart . Scale the chart so that
 * the longest bar is MAX _ BAR _ SIZE . */
public void print ( ) { } }

implementation:
// Get the longest bar ' s length .
int maxCount = 0 ; for ( int i = 0 ; i < m_n ; ++ i ) { maxCount = Math . max ( maxCount , m_aCounters [ i ] ) ; } // Compute the scaling factor .
final float factor = ( ( float ) MAX_BAR_SIZE ) / maxCount ; // Loop to print each bar .
for ( int i = 0 ; i < m_n ; ++ i ) { final int b = m_aCounters [ i ] ; // Interval number .
m_aAlignRight . print ( i , 2 ) ; m_aAlignRight . print ( b , 7 ) ; System . out . print ( ": " ) ; // Bar .
final int length = Math . round ( factor * b ) ; for ( int j = 0 ; j < length ; ++ j ) System . out . print ( "*" ) ; System . out . println ( ) ; }


signature:
public class Complex { /** * Add another complex number to this one .
 * @ param z
 * the other complex number
 * @ return a new complex number that is the sum */
public Complex add ( final Complex z ) { } }

implementation: return new Complex ( m_fReal + z . real ( ) , m_fImaginary + z . imaginary ( ) ) ;


signature:
public class Complex { /** * Subtract another complex number from this one .
 * @ param z
 * the other complex number
 * @ return a new complex number that is the difference */
public Complex subtract ( final Complex z ) { } }

implementation: return new Complex ( m_fReal - z . real ( ) , m_fImaginary - z . imaginary ( ) ) ;


signature:
public class Complex { /** * Multiply this complex number by another one .
 * @ param z
 * the other complex number
 * @ return a new complex number that is the product */
public Complex multiply ( final Complex z ) { } }

implementation: return new Complex ( m_fReal * z . real ( ) - m_fImaginary * z . imaginary ( ) , m_fReal * z . imaginary ( ) + m_fImaginary * z . real ( ) ) ;


signature:
public class Complex { /** * Divide this complex number by another one .
 * @ param z
 * the other complex number
 * @ return a new complex number that is the quotient */
public Complex divide ( final Complex z ) { } }

implementation: final float denom = z . real ( ) * z . real ( ) + z . imaginary ( ) * z . imaginary ( ) ; final float qr = ( m_fReal * z . real ( ) + m_fImaginary * z . imaginary ( ) ) / denom ; final float qi = ( m_fImaginary * z . real ( ) - m_fReal * z . imaginary ( ) ) / denom ; return new Complex ( qr , qi ) ;


signature:
public class RowVector { /** * Copy the values of this matrix .
 * @ return the copied values */
@ Nonnull @ ReturnsMutableCopy public float [ ] copyValues1D ( ) { } }

implementation: final float v [ ] = new float [ m_nCols ] ; for ( int c = 0 ; c < m_nCols ; ++ c ) v [ c ] = m_aValues [ 0 ] [ c ] ; return v ;


signature:
public class RowVector { /** * Set this row vector from a matrix . Only the first row is used .
 * @ param m
 * the matrix */
private void _set ( final Matrix m ) { } }

implementation: m_nRows = 1 ; m_nCols = m . m_nCols ; m_aValues = m . m_aValues ;


signature:
public class RowVector { /** * Compute the Euclidean norm .
 * @ return the norm */
public float norm ( ) { } }

implementation: double t = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ 0 ] [ c ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ;


signature:
public class RowVector { /** * Print the vector values . */
public void print ( ) { } }

implementation: for ( int c = 0 ; c < m_nCols ; ++ c ) { System . out . print ( "  " + m_aValues [ 0 ] [ c ] ) ; } System . out . println ( ) ;


signature:
public class Matrix { /** * Get the value of element [ r , c ] in the matrix .
 * @ param r
 * the row index
 * @ param c
 * the column index
 * @ return the value
 * @ throws MatrixException
 * for an invalid index */
public float at ( final int r , final int c ) throws MatrixException { } }

implementation: if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } return m_aValues [ r ] [ c ] ;


signature:
public class Matrix { /** * Get a row of this matrix .
 * @ param r
 * the row index
 * @ return the row as a row vector
 * @ throws MatrixException
 * for an invalid index */
public RowVector getRow ( final int r ) throws MatrixException { } }

implementation: if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final RowVector rv = new RowVector ( m_nCols ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { rv . m_aValues [ 0 ] [ c ] = m_aValues [ r ] [ c ] ; } return rv ;


signature:
public class Matrix { /** * Get a column of this matrix .
 * @ param c
 * the column index
 * @ return the column as a column vector
 * @ throws MatrixException
 * for an invalid index */
public ColumnVector getColumn ( final int c ) throws MatrixException { } }

implementation: if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final ColumnVector cv = new ColumnVector ( m_nRows ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { cv . m_aValues [ r ] [ 0 ] = m_aValues [ r ] [ c ] ; } return cv ;


signature:
public class Matrix { /** * Copy the values of this matrix .
 * @ return the copied values */
public float [ ] [ ] copyValues2D ( ) { } }

implementation: final float v [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { v [ r ] [ c ] = m_aValues [ r ] [ c ] ; } } return v ;


signature:
public class Matrix { /** * Set the value of element [ r , c ] .
 * @ param r
 * the row index
 * @ param c
 * the column index
 * @ param value
 * the value
 * @ throws MatrixException
 * for an invalid index */
public void set ( final int r , final int c , final float value ) throws MatrixException { } }

implementation: if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } m_aValues [ r ] [ c ] = value ;


signature:
public class Matrix { /** * Set this matrix from a 2 - d array of values . If the rows do not have the
 * same length , then the matrix column count is the length of the shortest
 * row .
 * @ param values
 * the 2 - d array of values */
protected void set ( final float values [ ] [ ] ) { } }

implementation: m_nRows = values . length ; m_nCols = values [ 0 ] . length ; m_aValues = values ; for ( int r = 1 ; r < m_nRows ; ++ r ) { m_nCols = Math . min ( m_nCols , values [ r ] . length ) ; }


signature:
public class Matrix { /** * Set a row of this matrix from a row vector .
 * @ param rv
 * the row vector
 * @ param r
 * the row index
 * @ throws MatrixException
 * for an invalid index or an invalid vector size */
public void setRow ( final RowVector rv , final int r ) throws MatrixException { } }

implementation: if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int c = 0 ; c < m_nCols ; ++ c ) { m_aValues [ r ] [ c ] = rv . m_aValues [ 0 ] [ c ] ; }


signature:
public class Matrix { /** * Set a column of this matrix from a column vector .
 * @ param cv
 * the column vector
 * @ param c
 * the column index
 * @ throws MatrixException
 * for an invalid index or an invalid vector size */
public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { } }

implementation: if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aValues [ r ] [ c ] = cv . m_aValues [ r ] [ 0 ] ; }


signature:
public class Matrix { /** * Return the transpose of this matrix .
 * @ return the transposed matrix */
public Matrix transpose ( ) { } }

implementation:
final float tv [ ] [ ] = new float [ m_nCols ] [ m_nRows ] ; // transposed values
// Set the values of the transpose .
for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { tv [ c ] [ r ] = m_aValues [ r ] [ c ] ; } } return new Matrix ( tv ) ;


signature:
public class Matrix { /** * Add another matrix to this matrix .
 * @ param m
 * the matrix addend
 * @ return the sum matrix
 * @ throws MatrixException
 * for invalid size */
public Matrix add ( final Matrix m ) throws MatrixException { } }

implementation:
// Validate m ' s size .
if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float sv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // sum values
// Compute values of the sum .
for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { sv [ r ] [ c ] = m_aValues [ r ] [ c ] + m . m_aValues [ r ] [ c ] ; } } return new Matrix ( sv ) ;


signature:
public class Matrix { /** * Subtract another matrix from this matrix .
 * @ param m
 * the matrix subrrahend
 * @ return the difference matrix
 * @ throws MatrixException
 * for invalid size */
public Matrix subtract ( final Matrix m ) throws MatrixException { } }

implementation:
// Validate m ' s size .
if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float dv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // difference values
// Compute values of the difference .
for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { dv [ r ] [ c ] = m_aValues [ r ] [ c ] - m . m_aValues [ r ] [ c ] ; } } return new Matrix ( dv ) ;


signature:
public class Matrix { /** * Multiply this matrix by a constant .
 * @ param k
 * the constant
 * @ return the product matrix */
public Matrix multiply ( final float k ) { } }

implementation:
final float pv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // product values
// Compute values of the product .
for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { pv [ r ] [ c ] = k * m_aValues [ r ] [ c ] ; } } return new Matrix ( pv ) ;


signature:
public class Matrix { /** * Multiply this matrix by another matrix .
 * @ param m
 * the matrix multiplier
 * @ return the product matrix
 * @ throws MatrixException
 * for invalid size */
public Matrix multiply ( final Matrix m ) throws MatrixException { } }

implementation:
// Validate m ' s dimensions .
if ( m_nCols != m . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] [ ] = new float [ m_nRows ] [ m . m_nCols ] ; // product values
// Compute values of the product .
for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m . m_nCols ; ++ c ) { float dot = 0 ; for ( int k = 0 ; k < m_nCols ; ++ k ) { dot += m_aValues [ r ] [ k ] * m . m_aValues [ k ] [ c ] ; } pv [ r ] [ c ] = dot ; } } return new Matrix ( pv ) ;


signature:
public class Matrix { /** * Multiply this matrix by a column vector : this * cv
 * @ param cv
 * the column vector
 * @ return the product column vector
 * @ throws MatrixException
 * for invalid size */
public ColumnVector multiply ( final ColumnVector cv ) throws MatrixException { } }

implementation:
// Validate cv ' s size .
if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values
// Compute the values of the product .
for ( int r = 0 ; r < m_nRows ; ++ r ) { float dot = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { dot += m_aValues [ r ] [ c ] * cv . m_aValues [ c ] [ 0 ] ; } pv [ r ] = dot ; } return new ColumnVector ( pv ) ;


signature:
public class Matrix { /** * Multiply a row vector by this matrix : rv * this
 * @ param rv
 * the row vector
 * @ return the product row vector
 * @ throws MatrixException
 * for invalid size */
public RowVector multiply ( final RowVector rv ) throws MatrixException { } }

implementation:
// Validate rv ' s size .
if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values
// Compute the values of the product .
for ( int c = 0 ; c < m_nCols ; ++ c ) { float dot = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { dot += rv . m_aValues [ 0 ] [ r ] * m_aValues [ r ] [ c ] ; } pv [ c ] = dot ; } return new RowVector ( pv ) ;


signature:
public class Matrix { /** * Print the matrix values .
 * @ param width
 * the column width */
public void print ( final int width , @ Nonnull final PrintStream aPS ) { } }

implementation: final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { ar . print ( "Row " , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( ":" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aValues [ r ] [ c ] , width ) ; } ar . println ( ) ; }


signature:
public class NewtonsRootFinder { /** * Compute the next position of x [ n + 1 ] . */
@ Override protected void computeNextPosition ( ) { } }

implementation:
m_fFn = m_fFnp1 ; m_fFpn = m_aFunction . derivativeAt ( m_fXn ) ; // Compute the value of x [ n + 1 ] .
m_fPrevXnp1 = m_fXnp1 ; m_fXnp1 = m_fXn - m_fFn / m_fFpn ; m_fFnp1 = m_aFunction . at ( m_fXnp1 ) ;


signature:
public class NewtonsRootFinder { /** * Check the position of x [ n + 1 ] .
 * @ throws PositionUnchangedException */
@ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { } }

implementation: if ( EqualsHelper . equals ( m_fXnp1 , m_fPrevXnp1 ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; }


signature:
public class SldEditorToolBarButton { /** * Attach an ImageResource to the button .
 * @ param imageResource imageResource */
public void setResource ( ImageResource imageResource ) { } }

implementation: Image img = new Image ( imageResource ) ; DOM . insertChild ( getElement ( ) , img . getElement ( ) , 0 ) ;


signature:
public class RegressionLine { /** * Add a new data point : Update the sums .
 * @ param dataPoint
 * the new data point */
public void addDataPoint ( final DataPoint dataPoint ) { } }

implementation: m_dSumX += dataPoint . getX ( ) ; m_dSumY += dataPoint . getY ( ) ; m_dSumXX += dataPoint . getX ( ) * dataPoint . getX ( ) ; m_dSumXY += dataPoint . getX ( ) * dataPoint . getY ( ) ; ++ m_nDataPoints ; m_bCoefsValid = false ;


signature:
public class RegressionLine { /** * Validate the coefficients . */
private void _validateCoefficients ( ) { } }

implementation: if ( m_bCoefsValid ) return ; if ( m_nDataPoints >= 2 ) { final float xBar = ( float ) m_dSumX / m_nDataPoints ; final float yBar = ( float ) m_dSumY / m_nDataPoints ; m_fA1 = ( float ) ( ( m_nDataPoints * m_dSumXY - m_dSumX * m_dSumY ) / ( m_nDataPoints * m_dSumXX - m_dSumX * m_dSumX ) ) ; m_fA0 = yBar - m_fA1 * xBar ; } else { m_fA0 = m_fA1 = Float . NaN ; } m_bCoefsValid = true ;


signature:
public class FixedPointRootFinder { /** * Compute the next position of xn . */
@ Override protected void computeNextPosition ( ) { } }

implementation: m_fPrevXn = m_fXn ; m_fXn = m_fGn ; m_fGn = m_aFunction . at ( m_fXn ) ;


signature:
public class SldModelImpl { /** * Does not clear templateNames . */
public void clear ( ) { } }

implementation: rawSld = new RawSld ( ) ; dirty = false ; valid = false ; template = null ; sldDescriptor = null ;


signature:
public class InMemorySldServiceImpl { /** * Convert StyledLayerDescriptorInfo to raw xml .
 * @ param sldi
 * @ return rawSld
 * @ throws SldException */
public RawSld toXml ( StyledLayerDescriptorInfo sldi ) throws SldException { } }

implementation: try { if ( sldi . getVersion ( ) == null ) { sldi . setVersion ( "1.0.0" ) ; } return parseSldI ( sldi ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; }


signature:
public class InMemorySldServiceImpl { /** * Convert raw xml to StyledLayerDescriptorInfo .
 * @ param sld
 * @ return StyledLayerDescriptorInfo
 * @ throws SldException */
public StyledLayerDescriptorInfo toSldI ( RawSld sld ) throws SldException { } }

implementation: try { return parseXml ( sld . getName ( ) , sld . getXml ( ) ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; }


signature:
public class InMemorySldServiceImpl { /** * Test by marshalling .
 * @ param sld
 * @ throws SldException */
public void validate ( StyledLayerDescriptorInfo sld ) throws SldException { } }

implementation: try { parseSldI ( sld ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; }


signature:
public class InMemorySldServiceImpl { /** * Test by unmarshalling .
 * @ param sld
 * @ throws SldException */
public boolean validate ( RawSld sld ) throws SldException { } }

implementation: try { parseXml ( "" , sld . getXml ( ) ) ; return true ; } catch ( JiBXException e ) { return false ; }


signature: public class InMemorySldServiceImpl { private StyledLayerDescriptorInfo parseXml ( String name , String raw ) throws JiBXException { } }

implementation: IBindingFactory bfact = BindingDirectory . getFactory ( StyledLayerDescriptorInfo . class ) ; IUnmarshallingContext uctx = bfact . createUnmarshallingContext ( ) ; Object object = uctx . unmarshalDocument ( new StringReader ( raw ) ) ; StyledLayerDescriptorInfo sld = ( StyledLayerDescriptorInfo ) object ; if ( sld . getName ( ) == null ) { sld . setName ( name ) ; } if ( sld . getTitle ( ) == null ) { sld . setTitle ( getTitle ( sld , name ) ) ; } if ( sld . getVersion ( ) == null ) { sld . setVersion ( "1.0.0" ) ; } return sld ;


signature:
public class PredictorCorrectorDiffEqSolver { /** * Return the next data point in the approximation of the solution .
 * @ param h
 * the width of the interval */
@ Override public DataPoint nextPoint ( final float h ) { } }

implementation:
final float predictor = m_fY + Math . abs ( h ) * m_aEquation . at ( m_fX ) ; final float avgSlope = ( m_aEquation . at ( m_fX , m_fY ) + m_aEquation . at ( m_fX + h , predictor ) ) / 2 ; m_fY += h * avgSlope ; // corrector
m_fX += h ; return new DataPoint ( m_fX , m_fY ) ;


signature:
public class TrapezoidalIntegrator { /** * Integrate the function from a to b using the trapezoidal algorithm , and
 * return an approximation to the area . ( Integrator implementation . )
 * @ param a
 * the lower limit
 * @ param b
 * the upper limit
 * @ param intervals
 * the number of equal - width intervals
 * @ return an approximation to the area */
public float integrate ( final float a , final float b , final int intervals ) { } }

implementation:
if ( b <= a ) return 0 ; final float h = ( b - a ) / intervals ; // interval width
float totalArea = 0 ; // Compute the area using the current number of intervals .
for ( int i = 0 ; i < intervals ; ++ i ) { final float x1 = a + i * h ; totalArea += _areaOf ( x1 , h ) ; } return totalArea ;


signature:
public class TrapezoidalIntegrator { /** * Compute the area of the ith trapezoidal region .
 * @ param x1
 * the left bound of the region
 * @ param h
 * the interval width
 * @ return the area of the region */
private float _areaOf ( final float x1 , final float h ) { } }

implementation:
final float x2 = x1 + h ; // right bound of the region
final float y1 = m_aIntegrand . at ( x1 ) ; // value at left bound
final float y2 = m_aIntegrand . at ( x2 ) ; // value at right bound
final float area = h * ( y1 + y2 ) / 2 ; // area of the region
return area ;


signature:
public class SquareMatrix { /** * Set this square matrix from another matrix . Note that this matrix will
 * reference the values of the argument matrix . If the values are not square ,
 * only the upper left square is used .
 * @ param m
 * the 2 - d array of values */
private void _set ( final Matrix m ) { } }

implementation: this . m_nRows = this . m_nCols = Math . min ( m . m_nRows , m . m_nCols ) ; this . m_aValues = m . m_aValues ;


signature:
public class SquareMatrix { /** * Set this square matrix from a 2 - d array of values . If the values are not
 * square , only the upper left square is used .
 * @ param values
 * the 2 - d array of values */
@ Override protected void set ( final float values [ ] [ ] ) { } }

implementation: super . set ( values ) ; m_nRows = m_nCols = Math . min ( m_nRows , m_nCols ) ;


signature:
public class SldCloseEvent { /** * Fires a { @ link SldCloseEvent } that will save the current SLD and close it . If not successful , the current SLD
 * remains open .
 * @ param source
 * @ param name */
public static void fireSave ( HasHandlers source ) { } }

implementation: SldCloseEvent eventInstance = new SldCloseEvent ( true ) ; source . fireEvent ( eventInstance ) ;


signature:
public class SldCloseEvent { /** * Fires a { @ link SldCloseEvent } that will close the current SLD regardless of changes .
 * @ param source
 * @ param name */
public static void fire ( HasHandlers source ) { } }

implementation: SldCloseEvent eventInstance = new SldCloseEvent ( false ) ; source . fireEvent ( eventInstance ) ;


signature:
public class InvertibleMatrix { /** * Compute the inverse of this matrix .
 * @ return the inverse matrix
 * @ throws MatrixException
 * if an error occurred */
public InvertibleMatrix inverse ( ) throws MatrixException { } }

implementation:
final InvertibleMatrix inverse = new InvertibleMatrix ( m_nRows ) ; final IdentityMatrix identity = new IdentityMatrix ( m_nRows ) ; // Compute each column of the inverse matrix
// using columns of the identity matrix .
for ( int c = 0 ; c < m_nCols ; ++ c ) { final ColumnVector col = solve ( identity . getColumn ( c ) , true ) ; inverse . setColumn ( col , c ) ; } return inverse ;


signature:
public class InvertibleMatrix { /** * Compute the determinant .
 * @ return the determinant
 * @ throws MatrixException
 * if an error occurred */
public float determinant ( ) throws MatrixException { } }

implementation:
decompose ( ) ; // Each row exchange during forward elimination flips the sign
// of the determinant , so check for an odd number of exchanges .
float determinant = ( ( m_nExchangeCount & 1 ) == 0 ) ? 1 : - 1 ; // Form the product of the diagonal elements of matrix U .
for ( int i = 0 ; i < m_nRows ; ++ i ) { final int pi = m_aPermutation [ i ] ; // permuted index
determinant *= m_aLU . at ( pi , i ) ; } return determinant ;


signature:
public class InvertibleMatrix { /** * Compute the Euclidean norm of this matrix .
 * @ return the norm */
public float norm ( ) { } }

implementation: float sum = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ r ] [ c ] ; sum += v * v ; } } return ( float ) Math . sqrt ( sum ) ;


signature:
public class LinearSystem { /** * Set the value of element [ r , c ] in the matrix .
 * @ param r
 * the row index , 0 . . nRows
 * @ param c
 * the column index , 0 . . nRows
 * @ param value
 * the value
 * @ throws MatrixException
 * for invalid index */
@ Override public void set ( final int r , final int c , final float value ) throws MatrixException { } }

implementation: super . set ( r , c , value ) ; reset ( ) ;


signature:
public class LinearSystem { /** * Set a row of this matrix from a row vector .
 * @ param rv
 * the row vector
 * @ param r
 * the row index
 * @ throws MatrixException
 * for an invalid index or an invalid vector size */
@ Override public void setRow ( final RowVector rv , final int r ) throws MatrixException { } }

implementation: super . setRow ( rv , r ) ; reset ( ) ;


signature:
public class LinearSystem { /** * Set a column of this matrix from a column vector .
 * @ param cv
 * the column vector
 * @ param c
 * the column index
 * @ throws MatrixException
 * for an invalid index or an invalid vector size */
@ Override public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { } }

implementation: super . setColumn ( cv , c ) ; reset ( ) ;


signature:
public class LinearSystem { /** * Solve Ax = b for x using the Gaussian elimination algorithm .
 * @ param b
 * the right - hand - side column vector
 * @ param improve
 * true to improve the solution
 * @ return the solution column vector
 * @ throws MatrixException
 * if an error occurred */
public ColumnVector solve ( final ColumnVector b , final boolean improve ) throws MatrixException { } }

implementation:
// Validate b ' s size .
if ( b . m_nRows != m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } decompose ( ) ; // Solve Ly = b for y by forward substitution .
// Solve Ux = y for x by back substitution .
final ColumnVector y = _forwardSubstitution ( b ) ; final ColumnVector x = _backSubstitution ( y ) ; // Improve and return x .
if ( improve ) _improve ( b , x ) ; return x ;


signature:
public class LinearSystem { /** * Print the decomposed matrix LU .
 * @ param width
 * the column width
 * @ throws MatrixException
 * if an error occurred */
public void printDecomposed ( final int width , @ Nonnull final PrintStream aPS ) throws MatrixException { } }

implementation:
decompose ( ) ; final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index
ar . print ( "Row " , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( ":" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aLU . m_aValues [ pr ] [ c ] , width ) ; } ar . println ( ) ; }


signature:
public class LinearSystem { /** * Compute the upper triangular matrix U and lower triangular matrix L such
 * that A = L * U . Store L and U together in matrix LU . Compute the permutation
 * vector permutation of the row indices .
 * @ throws MatrixException
 * for a zero row or a singular matrix */
protected void decompose ( ) throws MatrixException { } }

implementation:
// Return if the decomposition is valid .
if ( m_aLU != null ) return ; // Create a new LU matrix and permutation vector .
// LU is initially just a copy of the values of this system .
m_aLU = new SquareMatrix ( this . copyValues2D ( ) ) ; m_aPermutation = new int [ m_nRows ] ; final float scales [ ] = new float [ m_nRows ] ; // Loop to initialize the permutation vector and scales .
for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aPermutation [ r ] = r ; // initially no row exchanges
// Find the largest row element .
float largestRowElmt = 0 ; for ( int c = 0 ; c < m_nRows ; ++ c ) { final float elmt = Math . abs ( m_aLU . at ( r , c ) ) ; if ( largestRowElmt < elmt ) largestRowElmt = elmt ; } // Set the scaling factor for row equilibration .
if ( largestRowElmt != 0 ) { scales [ r ] = 1 / largestRowElmt ; } else { throw new MatrixException ( MatrixException . ZERO_ROW ) ; } } // Do forward elimination with scaled partial row pivoting .
_forwardElimination ( scales ) ; // Check bottom right element of the permuted matrix .
if ( m_aLU . at ( m_aPermutation [ m_nRows - 1 ] , m_nRows - 1 ) == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; }


signature:
public class LinearSystem { /** * Do forward elimination with scaled partial row pivoting .
 * @ parm scales the scaling vector
 * @ throws MatrixException
 * for a singular matrix */
private void _forwardElimination ( final float scales [ ] ) throws MatrixException { } }

implementation:
// Loop once per pivot row 0 . . nRows - 1.
for ( int rPivot = 0 ; rPivot < m_nRows - 1 ; ++ rPivot ) { float largestScaledElmt = 0 ; int rLargest = 0 ; // Starting from the pivot row rPivot , look down
// column rPivot to find the largest scaled element .
for ( int r = rPivot ; r < m_nRows ; ++ r ) { // Use the permuted row index .
final int pr = m_aPermutation [ r ] ; final float absElmt = Math . abs ( m_aLU . at ( pr , rPivot ) ) ; final float scaledElmt = absElmt * scales [ pr ] ; if ( largestScaledElmt < scaledElmt ) { // The largest scaled element and
// its row index .
largestScaledElmt = scaledElmt ; rLargest = r ; } } // Is the matrix singular ?
if ( largestScaledElmt == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } // Exchange rows if necessary to choose the best
// pivot element by making its row the pivot row .
if ( rLargest != rPivot ) { final int temp = m_aPermutation [ rPivot ] ; m_aPermutation [ rPivot ] = m_aPermutation [ rLargest ] ; m_aPermutation [ rLargest ] = temp ; ++ m_nExchangeCount ; } // Use the permuted pivot row index .
final int prPivot = m_aPermutation [ rPivot ] ; final float pivotElmt = m_aLU . at ( prPivot , rPivot ) ; // Do the elimination below the pivot row .
for ( int r = rPivot + 1 ; r < m_nRows ; ++ r ) { // Use the permuted row index .
final int pr = m_aPermutation [ r ] ; final float multiple = m_aLU . at ( pr , rPivot ) / pivotElmt ; // Set the multiple into matrix L .
m_aLU . set ( pr , rPivot , multiple ) ; // Eliminate an unknown from matrix U .
if ( multiple != 0 ) { for ( int c = rPivot + 1 ; c < m_nCols ; ++ c ) { float elmt = m_aLU . at ( pr , c ) ; // Subtract the multiple of the pivot row .
elmt -= multiple * m_aLU . at ( prPivot , c ) ; m_aLU . set ( pr , c , elmt ) ; } } } }


signature:
public class LinearSystem { /** * Solve Ly = b for y by forward substitution .
 * @ param b
 * the column vector b
 * @ return the column vector y
 * @ throws MatrixException
 * if an error occurred */
private ColumnVector _forwardSubstitution ( final ColumnVector b ) throws MatrixException { } }

implementation:
final ColumnVector y = new ColumnVector ( m_nRows ) ; // Do forward substitution .
for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index
float dot = 0 ; for ( int c = 0 ; c < r ; ++ c ) { dot += m_aLU . at ( pr , c ) * y . at ( c ) ; } y . set ( r , b . at ( pr ) - dot ) ; } return y ;


signature:
public class LinearSystem { /** * Solve Ux = y for x by back substitution .
 * @ param y
 * the column vector y
 * @ return the solution column vector x
 * @ throws MatrixException
 * if an error occurred */
private ColumnVector _backSubstitution ( final ColumnVector y ) throws MatrixException { } }

implementation:
final ColumnVector x = new ColumnVector ( m_nRows ) ; // Do back substitution .
for ( int r = m_nRows - 1 ; r >= 0 ; -- r ) { final int pr = m_aPermutation [ r ] ; // permuted row index
float dot = 0 ; for ( int c = r + 1 ; c < m_nRows ; ++ c ) { dot += m_aLU . at ( pr , c ) * x . at ( c ) ; } x . set ( r , ( y . at ( r ) - dot ) / m_aLU . at ( pr , r ) ) ; } return x ;