signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level VERBOSE according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the VERBOSE level .
 * @ param format the format string
 * @ param argArray an array of arguments */
public void trace ( String format , Object ... argArray ) { } }

implementation: formatAndLog ( Log . VERBOSE , format , argArray ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log an exception ( throwable ) at level VERBOSE with an accompanying message .
 * @ param msg the message accompanying the exception
 * @ param t the exception ( throwable ) to log */
public void trace ( String msg , Throwable t ) { } }

implementation: log ( Log . VERBOSE , msg , t ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level DEBUG according to the specified format and argument .
 * This form avoids superfluous object creation when the logger is disabled
 * for level DEBUG .
 * @ param format the format string
 * @ param arg the argument */
public void debug ( String format , Object arg ) { } }

implementation: formatAndLog ( Log . DEBUG , format , arg ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level DEBUG according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the DEBUG level .
 * @ param format the format string
 * @ param arg1 the first argument
 * @ param arg2 the second argument */
public void debug ( String format , Object arg1 , Object arg2 ) { } }

implementation: formatAndLog ( Log . DEBUG , format , arg1 , arg2 ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level DEBUG according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the DEBUG level .
 * @ param format the format string
 * @ param argArray an array of arguments */
public void debug ( String format , Object ... argArray ) { } }

implementation: formatAndLog ( Log . DEBUG , format , argArray ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log an exception ( throwable ) at level DEBUG with an accompanying message .
 * @ param msg the message accompanying the exception
 * @ param t the exception ( throwable ) to log */
public void debug ( String msg , Throwable t ) { } }

implementation: log ( Log . DEBUG , msg , t ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level INFO according to the specified format and argument .
 * This form avoids superfluous object creation when the logger is disabled
 * for the INFO level .
 * @ param format the format string
 * @ param arg the argument */
public void info ( String format , Object arg ) { } }

implementation: formatAndLog ( Log . INFO , format , arg ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at the INFO level according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the INFO level .
 * @ param format the format string
 * @ param arg1 the first argument
 * @ param arg2 the second argument */
public void info ( String format , Object arg1 , Object arg2 ) { } }

implementation: formatAndLog ( Log . INFO , format , arg1 , arg2 ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level INFO according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the INFO level .
 * @ param format the format string
 * @ param argArray an array of arguments */
public void info ( String format , Object ... argArray ) { } }

implementation: formatAndLog ( Log . INFO , format , argArray ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log an exception ( throwable ) at the INFO level with an accompanying
 * message .
 * @ param msg the message accompanying the exception
 * @ param t the exception ( throwable ) to log */
public void info ( String msg , Throwable t ) { } }

implementation: log ( Log . INFO , msg , t ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at the WARN level according to the specified format and
 * argument .
 * This form avoids superfluous object creation when the logger is disabled
 * for the WARN level .
 * @ param format the format string
 * @ param arg the argument */
public void warn ( String format , Object arg ) { } }

implementation: formatAndLog ( Log . WARN , format , arg ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at the WARN level according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the WARN level .
 * @ param format the format string
 * @ param arg1 the first argument
 * @ param arg2 the second argument */
public void warn ( String format , Object arg1 , Object arg2 ) { } }

implementation: formatAndLog ( Log . WARN , format , arg1 , arg2 ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level WARN according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the WARN level .
 * @ param format the format string
 * @ param argArray an array of arguments */
public void warn ( String format , Object ... argArray ) { } }

implementation: formatAndLog ( Log . WARN , format , argArray ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log an exception ( throwable ) at the WARN level with an accompanying
 * message .
 * @ param msg the message accompanying the exception
 * @ param t the exception ( throwable ) to log */
public void warn ( String msg , Throwable t ) { } }

implementation: log ( Log . WARN , msg , t ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at the ERROR level according to the specified format and
 * argument .
 * This form avoids superfluous object creation when the logger is disabled
 * for the ERROR level .
 * @ param format the format string
 * @ param arg the argument */
public void error ( String format , Object arg ) { } }

implementation: formatAndLog ( Log . ERROR , format , arg ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at the ERROR level according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the ERROR level .
 * @ param format the format string
 * @ param arg1 the first argument
 * @ param arg2 the second argument */
public void error ( String format , Object arg1 , Object arg2 ) { } }

implementation: formatAndLog ( Log . ERROR , format , arg1 , arg2 ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log a message at level ERROR according to the specified format and
 * arguments .
 * This form avoids superfluous object creation when the logger is disabled
 * for the ERROR level .
 * @ param format the format string
 * @ param argArray an array of arguments */
public void error ( String format , Object ... argArray ) { } }

implementation: formatAndLog ( Log . ERROR , format , argArray ) ;


signature:
public class TimberAndroidLoggerAdapter { /** * Log an exception ( throwable ) at the ERROR level with an accompanying
 * message .
 * @ param msg the message accompanying the exception
 * @ param t the exception ( throwable ) to log */
public void error ( String msg , Throwable t ) { } }

implementation: log ( Log . ERROR , msg , t ) ;


signature:
public class RecordJoiner { /** * One to many */
public Stream < Record > oneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { } }

implementation: return oneToMany ( rights . stream ( ) , manyKey ) ;


signature:
public class RecordJoiner { /** * Strict one to many */
public Stream < Record > strictOneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { } }

implementation: return strictOneToMany ( rights . stream ( ) , manyKey ) ;


signature:
public class Joiner { /** * Many to one */
public Stream < T2 < L , R > > manyToOne ( Collection < ? extends R > rights ) { } }

implementation: return manyToOne ( rights . stream ( ) ) ;


signature:
public class Joiner { /** * Strict many to one */
public Stream < T2 < L , R > > strictManyToOne ( Collection < ? extends R > rights ) { } }

implementation: return strictManyToOne ( rights . stream ( ) ) ;


signature:
public class Joiner { /** * Strict one to many */
public Stream < T2 < L , Set < R > > > strictOneToMany ( Collection < ? extends R > rights ) { } }

implementation: return strictOneToMany ( rights . stream ( ) ) ;


signature:
public class Joiner { /** * Strict one to one */
public Stream < T2 < L , R > > strictOneToOne ( Collection < ? extends R > rights ) { } }

implementation: return strictOneToOne ( rights . stream ( ) ) ;


signature:
public class RavenBootstrap { /** * Bootstrap the SLF4J root logger with a configured
 * { @ link com . getsentry . raven . logback . SentryAppender } .
 * @ param dsn The DSN ( Data Source Name ) for your project
 * @ param tags Custom tags to send to Sentry along with errors
 * @ param cleanRootLogger If true , detach and stop all other appenders from the root logger */
public static void bootstrap ( final String dsn , Optional < String > tags , boolean cleanRootLogger ) { } }

implementation: bootstrap ( dsn , tags , Optional . empty ( ) , Optional . empty ( ) , cleanRootLogger ) ;


signature:
public class RavenBootstrap { /** * Bootstrap the SLF4J root logger with a configured
 * { @ link com . getsentry . raven . logback . SentryAppender } .
 * @ param dsn The DSN ( Data Source Name ) for your project
 * @ param tags Custom tags to send to Sentry along with errors
 * @ param environment The environment name to pass to Sentry
 * @ param release The release name to pass to Sentry
 * @ param cleanRootLogger If true , detach and stop all other appenders from the root logger */
public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , boolean cleanRootLogger ) { } }

implementation: bootstrap ( dsn , tags , environment , release , Optional . empty ( ) , cleanRootLogger ) ;


signature:
public class RavenBootstrap { /** * Bootstrap the SLF4J root logger with a configured
 * { @ link com . getsentry . raven . logback . SentryAppender } .
 * @ param dsn The DSN ( Data Source Name ) for your project
 * @ param tags Custom tags to send to Sentry along with errors
 * @ param environment The environment name to pass to Sentry
 * @ param release The release name to pass to Sentry
 * @ param serverName The server name to pass to Sentry
 * @ param cleanRootLogger If true , detach and stop all other appenders from the root logger */
public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , Optional < String > serverName , boolean cleanRootLogger ) { } }

implementation: final RavenAppenderFactory raven = new RavenAppenderFactory ( ) ; raven . setThreshold ( Level . ERROR ) ; raven . setDsn ( dsn ) ; raven . setTags ( tags ) ; raven . setEnvironment ( environment ) ; raven . setRelease ( release ) ; raven . setServerName ( serverName ) ; registerAppender ( dsn , cleanRootLogger , raven ) ;


signature:
public class ContentView { /** * The last modified time of a page is the most recent of :
 * < ol >
 * < li > { @ link Page # getDateCreated ( ) } < / li >
 * < li > { @ link Page # getDatePublished ( ) } < / li >
 * < li > { @ link Page # getDateModified ( ) } < / li >
 * < / ol >
 * Note : { @ link Page # getDateReviewed ( ) } is left out because a change in its value alone does not indicate a change in content . */
@ Override public ReadableInstant getLastModified ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { } }

implementation: return AoArrays . maxNonNull ( page . getDateCreated ( ) , page . getDatePublished ( ) , page . getDateModified ( ) ) ;


signature:
public class ContentView { /** * Uses the page settings .
 * @ see PageUtils # findAllowRobots ( javax . servlet . ServletContext , javax . servlet . http . HttpServletRequest , javax . servlet . http . HttpServletResponse , com . semanticcms . core . model . Page ) */
@ Override public boolean getAllowRobots ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { } }

implementation: return PageUtils . findAllowRobots ( servletContext , request , response , page ) ;


signature:
public class TakeOrderSteps { /** * Assert that the generated command matches the specified command .
 * @ param command expected command
 * @ throws Throwable */
@ Then ( "^the instruction generated should be \"([^\"]*)\"$" ) public void the_instruction_generated_should_be ( String command ) throws Throwable { } }

implementation: verify ( context . getDrinkMaker ( ) ) . executeCommand ( eq ( command ) ) ;


signature:
public class GrammarParser { /** * Attempt to retrieve the parameter ( < code > @ param < / code > doclet parameter )
 * using the parameter name , otherwise fallback to the parameter index . */
private DocletTag findParamDocByNameOrIndex ( String name , int paramIndex , List < DocletTag > tags ) { } }

implementation: for ( DocletTag tag : tags ) { if ( name . equals ( tag . getParameters ( ) . get ( 0 ) ) ) { return tag ; } } if ( paramIndex < tags . size ( ) ) { return tags . get ( paramIndex ) ; } return null ;


signature:
public class MergeDic { /** * 尝试合并 sogou ( 去除了没有词性的 ) 与 rmmseg 的词库 。
 * @ throws IOException */
public static void main ( String [ ] args ) throws IOException { } }

implementation: FileInputStream fis = new FileInputStream ( new File ( "dic/word-with-attr.dic" ) ) ; final Set < String > words = new TreeSet < String > ( ) ; final int [ ] num = { 0 } ; FileLoading fl = new FileLoading ( ) { public void row ( String line , int n ) { words . add ( line . trim ( ) ) ; num [ 0 ] ++ ; } } ; Dictionary . load ( fis , fl ) ; fis = new FileInputStream ( new File ( "dic/words-rmmseg.dic" ) ) ; Dictionary . load ( fis , fl ) ; WriterRow wr = new WriterRow ( new File ( "dic/words-marge-sogou-no-attr-and-rmmseg.dic" ) ) ; for ( String word : words ) { wr . writerRow ( word ) ; } wr . close ( ) ; System . out . println ( "rows=" + num [ 0 ] + ", size=" + words . size ( ) + ", same=" + ( num [ 0 ] - words . size ( ) ) ) ;


signature:
public class Effect { /** * - Dmode = simple , default is complex
 * @ param args args [ 0 ] txt path
 * @ author chenlb 2009-3-28 下午02:19:52
 * @ throws Exception */
public static void main ( String [ ] args ) throws Exception { } }

implementation: int n = 1 ; if ( args . length < 1 ) { usage ( ) ; return ; } Properties analyzers = new Properties ( ) ; analyzers . load ( new FileInputStream ( new File ( "analyzer.properties" ) ) ) ; String mode = System . getProperty ( "mode" , "complex" ) ; String a = System . getProperty ( "analyzer" , "mmseg4j" ) ; Analyzer analyzer = null ; String an = ( String ) analyzers . get ( a ) ; if ( an != null ) { analyzer = ( Analyzer ) Class . forName ( an ) . newInstance ( ) ; mode = a ; } else { usage ( ) ; return ; } if ( args . length > 1 ) { try { n = Integer . parseInt ( args [ 1 ] ) ; } catch ( NumberFormatException e ) { } } File path = new File ( args [ 0 ] ) ; System . out . println ( "analyzer=" + analyzer . getClass ( ) . getName ( ) ) ; Effect ef = new Effect ( path , analyzer ) ; ef . run ( mode , n ) ;


signature:
public class Dictionary { /** * 只要 wordsXXX . dic的文件
 * @ return */
protected File [ ] listWordsFiles ( ) { } }

implementation: return dicPath . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . startsWith ( "words" ) && name . endsWith ( ".dic" ) ; } } ) ;


signature:
public class Dictionary { /** * 加载词文件的模板
 * @ return 文件总行数 */
public static int load ( InputStream fin , FileLoading loading ) throws IOException { } }

implementation: BufferedReader br = new BufferedReader ( new InputStreamReader ( new BufferedInputStream ( fin ) , "UTF-8" ) ) ; String line = null ; int n = 0 ; while ( ( line = br . readLine ( ) ) != null ) { if ( line == null || line . startsWith ( "#" ) ) { continue ; } n ++ ; loading . row ( line , n ) ; } return n ;


signature:
public class Dictionary { /** * 取得 str 除去第一个char的部分
 * @ author chenlb 2009-3-3 下午10:05:26 */
private static char [ ] tail ( String str ) { } }

implementation: char [ ] cs = new char [ str . length ( ) - 1 ] ; str . getChars ( 1 , str . length ( ) , cs , 0 ) ; return cs ;


signature:
public class Dictionary { /** * 把 wordsFile 文件的最后更新时间加记录下来 .
 * @ param wordsFile 非 null */
private synchronized void addLastTime ( File wordsFile ) { } }

implementation: if ( wordsFile != null ) { wordsLastTime . put ( wordsFile , wordsFile . lastModified ( ) ) ; }


signature:
public class Dictionary { /** * 词典文件是否有修改过
 * @ return */
public synchronized boolean wordsFileIsChange ( ) { } }

implementation:
// 检查是否有修改文件 , 包括删除的
for ( Entry < File , Long > flt : wordsLastTime . entrySet ( ) ) { File words = flt . getKey ( ) ; if ( ! words . canRead ( ) ) { // 可能是删除了
return true ; } if ( words . lastModified ( ) > flt . getValue ( ) ) { // 更新了文件
return true ; } } // 检查是否有新文件
File [ ] words = listWordsFiles ( ) ; if ( words != null ) { for ( File wordsFile : words ) { if ( ! wordsLastTime . containsKey ( wordsFile ) ) { // 有新词典文件
return true ; } } } return false ;


signature:
public class Dictionary { /** * 全新加载词库 , 没有成功加载会回滚 。 < P / >
 * 注意 : 重新加载时 , 务必有两倍的词库树结构的内存 , 默认词库是 50M / 个 左右 。 否则抛出 OOM 。
 * @ return 是否成功加载 */
public synchronized boolean reload ( ) { } }

implementation:
Map < File , Long > oldWordsLastTime = new HashMap < File , Long > ( wordsLastTime ) ; Map < Character , CharNode > oldDict = dict ; Map < Character , Object > oldUnit = unit ; try { wordsLastTime . clear ( ) ; dict = loadDic ( dicPath ) ; unit = loadUnit ( dicPath ) ; lastLoadTime = System . currentTimeMillis ( ) ; } catch ( IOException e ) { // rollback
wordsLastTime . putAll ( oldWordsLastTime ) ; dict = oldDict ; unit = oldUnit ; if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , "reload dic error! dic=" + dicPath + ", and rollbacked." , e ) ; } return false ; } return true ;


signature:
public class Dictionary { /** * word 能否在词库里找到
 * @ author chenlb 2009-3-3 下午11:10:45 */
public boolean match ( String word ) { } }

implementation: if ( word == null || word . length ( ) < 2 ) { return false ; } CharNode cn = dict . get ( word . charAt ( 0 ) ) ; return search ( cn , word . toCharArray ( ) , 0 , word . length ( ) - 1 ) >= 0 ;


signature:
public class Dictionary { /** * sen [ offset ] 后 tailLen 长的词是否存在 .
 * @ see CharNode # indexOf ( char [ ] , int , int )
 * @ author chenlb 2009-4-8 下午11:13:49 */
public int search ( CharNode node , char [ ] sen , int offset , int tailLen ) { } }

implementation: if ( node != null ) { return node . indexOf ( sen , offset , tailLen ) ; } return - 1 ;


signature:
public class Dictionary { /** * 当 words . dic 是从 jar 里加载时 , 可能 defalut 不存在 */
public static File getDefalutPath ( ) { } }

implementation: if ( defalutPath == null ) { String defPath = System . getProperty ( "mmseg.dic.path" ) ; log . info ( "look up in mmseg.dic.path=" + defPath ) ; if ( defPath == null ) { URL url = Dictionary . class . getClassLoader ( ) . getResource ( "data" ) ; if ( url != null ) { defPath = url . getFile ( ) ; log . info ( "look up in classpath=" + defPath ) ; } else { defPath = System . getProperty ( "user.dir" ) + "/data" ; log . info ( "look up in user.dir=" + defPath ) ; } } defalutPath = new File ( defPath ) ; if ( ! defalutPath . exists ( ) ) { log . warning ( "defalut dic path=" + defalutPath + " not exist" ) ; } } return defalutPath ;


signature:
public class MMSeg { /** * 读取下一串指定类型的字符放到 bufSentence 中 .
 * @ param bufSentence
 * @ param readChar 判断字符的细节 .
 * @ return 返回读取的个数
 * @ throws IOException { @ link # readNext ( ) } 或 { @ link # pushBack ( ) } 抛出的 . */
private int readChars ( StringBuilder bufSentence , ReadChar readChar ) throws IOException { } }

implementation:
int num = 0 ; int data = - 1 ; while ( ( data = readNext ( ) ) != - 1 ) { int d = readChar . transform ( data ) ; if ( readChar . isRead ( d ) ) { bufSentence . appendCodePoint ( d ) ; num ++ ; } else { // 不是数字回压 , 要下一步操作
pushBack ( data ) ; break ; } } return num ;


signature:
public class MMSeg { /** * 从 StringBuilder 里复制出 char [ ] */
private static char [ ] toChars ( StringBuilder bufSentence ) { } }

implementation: char [ ] chs = new char [ bufSentence . length ( ) ] ; bufSentence . getChars ( 0 , bufSentence . length ( ) , chs , 0 ) ; return chs ;


signature:
public class MMSeg { /** * 双角转单角 */
private static int toAscii ( int codePoint ) { } }

implementation:
if ( ( codePoint >= 65296 && codePoint <= 65305 ) // 0-9
|| ( codePoint >= 65313 && codePoint <= 65338 ) // A - Z
|| ( codePoint >= 65345 && codePoint <= 65370 ) // a - z
) { codePoint -= 65248 ; } return codePoint ;


signature:
public class Performance { /** * - Dmode = simple , default is complex
 * - Dfile . encode = utf - 8 or other
 * @ param args args [ 0 ] txt path
 * @ author chenlb 2009-3-28 下午02:19:52
 * @ throws IOException */
public static void main ( String [ ] args ) throws IOException { } }

implementation: if ( args . length < 1 ) { System . out . println ( "Usage:" ) ; System . out . println ( "\t-Dmode=simple, defalut is complex" ) ; System . out . println ( "\tPerformance <txt path> - is a directory that contain *.txt" ) ; return ; } String mode = System . getProperty ( "mode" , "complex" ) ; Seg seg = null ; Dictionary dic = Dictionary . getInstance ( ) ; if ( "simple" . equals ( mode ) ) { seg = new SimpleSeg ( dic ) ; } else { seg = new ComplexSeg ( dic ) ; } File path = new File ( args [ 0 ] ) ; File [ ] txts = path . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".txt" ) ; } } ) ; long time = 0 ; for ( File txt : txts ) { MMSeg mmSeg = new MMSeg ( new InputStreamReader ( new FileInputStream ( txt ) ) , seg ) ; Word word = null ; OutputStreamWriter osw = new OutputStreamWriter ( new FileOutputStream ( new File ( txt . getAbsoluteFile ( ) + "." + mode + ".word" ) ) ) ; BufferedWriter bw = new BufferedWriter ( osw ) ; long start = System . currentTimeMillis ( ) ; while ( ( word = mmSeg . next ( ) ) != null ) { bw . append ( new String ( word . getString ( ) ) ) . append ( "\r\n" ) ; } time += System . currentTimeMillis ( ) - start ; bw . close ( ) ; } System . out . println ( "use " + time + "ms" ) ;


signature:
public class Chunk { /** * Word Length */
public int getLen ( ) { } }

implementation: if ( len < 0 ) { len = 0 ; count = 0 ; for ( Word word : words ) { if ( word != null ) { len += word . getLength ( ) ; count ++ ; } } } return len ;


signature:
public class Chunk { /** * 有多少个词 , 最多3个 。 */
public int getCount ( ) { } }

implementation: if ( count < 0 ) { count = 0 ; for ( Word word : words ) { if ( word != null ) { count ++ ; } } } return count ;


signature:
public class Chunk { /** * Variance of Word Lengths 就是 标准差的平方 */
public double getVariance ( ) { } }

implementation: if ( variance < 0 ) { double sum = 0 ; for ( Word word : words ) { if ( word != null ) { sum += Math . pow ( word . getLength ( ) - getAvgLen ( ) , 2 ) ; } } variance = sum / getCount ( ) ; } return variance ;


signature:
public class Chunk { /** * Sum of Degree of Morphemic Freedom of One - Character */
public int getSumDegree ( ) { } }

implementation: if ( sumDegree < 0 ) { int sum = 0 ; for ( Word word : words ) { if ( word != null && word . getDegree ( ) > - 1 ) { sum += word . getDegree ( ) ; } } sumDegree = sum ; } return sumDegree ;


signature:
public class Seg { /** * 输出 chunks , 调试用 . */
protected void printChunk ( List < Chunk > chunks ) { } }

implementation: for ( Chunk ck : chunks ) { System . out . println ( ck + " -> " + ck . toFactorString ( ) ) ; }


signature:
public class Seg { /** * 查找chs [ offset ] 后面的 tailLen个char是否为词 .
 * @ return 返回chs [ offset ] 字符结点下的词尾索引号 , 没找到返回 - 1. */
protected int search ( char [ ] chs , int offset , int tailLen ) { } }

implementation: if ( tailLen == 0 ) { return - 1 ; } CharNode cn = dic . head ( chs [ offset ] ) ; return search ( cn , chs , offset , tailLen ) ;


signature:
public class Seg { /** * 没有数组的复制 .
 * @ author chenlb 2009-4-8 下午11:39:15 */
protected int search ( CharNode cn , char [ ] chs , int offset , int tailLen ) { } }

implementation: if ( tailLen == 0 || cn == null ) { return - 1 ; } return dic . search ( cn , chs , offset , tailLen ) ;


signature:
public class Seg { /** * 最大匹配 < br / >
 * 从 chs [ offset ] 开始匹配 , 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ]
 * @ return 最大匹配到的词尾长 , > 0 找到 */
protected int maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset ) { } }

implementation: CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; return dic . maxMatch ( cn , chs , offset ) ;


signature:
public class Seg { /** * 匹配 , 同时找出长度 . < br / >
 * 从 chs [ offset ] 开始找所有匹配的词 , 找到的放到 tailLens [ tailLensIdx ] 中 . < br / >
 * 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ] .
 * @ author chenlb 2009-4-12 上午10:37:58 */
protected void maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset , ArrayList < Integer > [ ] tailLens , int tailLensIdx ) { } }

implementation: CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; dic . maxMatch ( cn , tailLens [ tailLensIdx ] , chs , offset ) ;


signature:
public class DicTransform { /** * 词库转换
 * @ throws IOException */
public static void main ( String [ ] args ) throws IOException { } }

implementation:
String words = "sogou/SogouLabDic.dic" ; String charset = "GBK" ; if ( args . length > 0 ) { words = args [ 0 ] ; } File file = new File ( words ) ; // File path = file . getParentFile ( ) ;
// File dist = new File ( " dic / words . dic " ) ;
File dist = new File ( "dic/word-with-attr.dic" ) ; DicTransform dt = new DicTransform ( ) ; // 只要词 , 不频率
// dt . transform ( file , charset , dist , new DeFreq ( ) ) ;
// 只要两或三个字的词 .
// dt . transform ( file , charset , dist , new TwoOrThreeChar ( ) ) ;
dt . transform ( file , charset , dist , new NoAttr ( ) ) ;


signature:
public class NameApiModeFactory { /** * You can take this and extend for your setup if you need more .
 * < p > Example : . with ( StdoutLoggingExtension . enabled ( ) ) < / p >
 * @ param apiKey Your personal api key from registering with us .
 * @ param host for example { @ code new Host ( " api . nameapi . org " , 80 ) }
 * @ param portUrlFactory for example { @ code NameApiPortUrlFactory . versionLatestStable ( ) } */
@ NotNull public static Mode minimal ( @ NotNull String apiKey , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { } }

implementation:
return Mode . create ( ) . with ( RestKeys . REST_PORT_URL_FACTORY , portUrlFactory ) // . with ( ExceptionTranslationExtension . TRANSLATOR , new CombinedExceptionTranslator ( new DefaultClientExceptionTranslator ( ) , new SoapFaultExceptionTranslator ( ) ) )
. with ( Keys . HOST , host ) . with ( NameApiKeys . API_KEY , apiKey ) ;


signature:
public class NameApiModeFactory { /** * Overloaded method that uses
 * for host : { @ code new Host ( " api . nameapi . org " , 80 ) }
 * for port url : { @ code NameApiPortUrlFactory . versionLatestStable ( ) } */
@ NotNull public static Mode minimal ( @ NotNull String apiKey ) { } }

implementation: return minimal ( apiKey , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ;


signature:
public class NameApiModeFactory { /** * You can take this and extend for your setup if you need more .
 * < p > Example : . with ( StdoutLoggingExtension . enabled ( ) ) < / p >
 * @ param apiKey Your personal api key from registering with us .
 * @ param context for example { @ code new ContextBuilder ( ) . priority ( Priority . REALTIME ) . build ( ) }
 * @ param host for example { @ code new Host ( " api . nameapi . org " , 80 ) }
 * @ param portUrlFactory for example { @ code NameApiPortUrlFactory . versionLatestStable ( ) } */
@ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { } }

implementation: return minimal ( apiKey , host , portUrlFactory ) . with ( NameApiKeys . CONTEXT , context ) ;


signature:
public class NameApiModeFactory { /** * Overloaded method that uses
 * for host : { @ code new Host ( " api . nameapi . org " , 80 ) }
 * for port url : { @ code NameApiPortUrlFactory . versionLatestStable ( ) } */
@ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context ) { } }

implementation: return withContext ( apiKey , context , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ;


signature:
public class JdbcStemmerOverrideFilterFactory { /** * Returns a map which contains only those arguments that the superclass understands . */
private static Map < String , String > superclassArgs ( Map < String , String > args ) { } }

implementation:
Map < String , String > result = new HashMap < > ( ) ; // resource loading does not take place if no file has been configured .
if ( ! result . containsKey ( "dictionary" ) ) { result . put ( "dictionary" , JdbcResourceLoader . DATABASE ) ; } for ( String arg : ImmutableList . of ( "dictionary" , "ignoreCase" ) ) { String value = args . get ( arg ) ; if ( value != null ) { result . put ( arg , value ) ; } } return result ;


signature:
public class JdbcKeepWordFilterFactory { /** * Load words from jdbc */
@ Override public void inform ( ResourceLoader loader ) throws IOException { } }

implementation: super . inform ( new JdbcResourceLoader ( loader , reader , StandardCharsets . UTF_8 ) ) ;


signature:
public class SimpleJdbcReader { /** * Check if the datasource is able to provide connections . */
protected final void checkDatasource ( ) { } }

implementation:
// Check database connection information of data source
if ( dataSource != null ) { // noinspection unused , EmptyTryBlock
try ( Connection connection = dataSource . getConnection ( ) ) { // Just get the connection to check if data source parameters are configured correctly .
} catch ( SQLException e ) { dataSource = null ; logger . error ( "Failed to connect to database of data source: {}." , e . getMessage ( ) ) ; if ( ! ignore ) { throw new IllegalArgumentException ( "Failed to connect to the database." , e ) ; } } }


signature:
public class SimpleJdbcReader { /** * { @ inheritDoc } */
@ Override public Reader getReader ( ) { } }

implementation:
if ( dataSource == null ) { if ( ignore ) { return new StringReader ( "" ) ; } throw new IllegalArgumentException ( "Missing data source." ) ; } QueryRunner runner = new QueryRunner ( dataSource ) ; try { logger . info ( "Querying for data using {}" , sql ) ; List < String > content = runner . query ( sql , SINGLE_LINE_RESULT_SET_HANDLER ) ; logger . info ( "Loaded {} lines" , content . size ( ) ) ; // return joined
return new StringReader ( Joiner . on ( '\n' ) . join ( content ) ) ; } catch ( SQLException e ) { throw new IllegalArgumentException ( "Failed to load data from the database" , e ) ; }


signature:
public class SimpleJdbcReader { /** * { @ inheritDoc } */
@ Override public QueryRunner getJdbcRunner ( ) { } }

implementation: if ( dataSource == null ) { if ( ignore ) { logger . warn ( "Could not load Jdbc Datasource!" ) ; return null ; } throw new IllegalArgumentException ( "Missing data source." ) ; } return new QueryRunner ( dataSource ) ;


signature:
public class SearcherAwareReloader { /** * Inform { @ link SearcherAware } about a new searcher .
 * @ param type
 * Description of concrete type of the { @ link SearcherAware } .
 * @ param name
 * Name of the field type .
 * @ param o
 * The { @ link SearcherAware } .
 * @ param searcher
 * The new searcher . */
private void inform ( String type , String name , Object o , SolrIndexSearcher searcher ) { } }

implementation: if ( o instanceof SearcherAware ) { logger . info ( "Informing searcher aware {} ({}) of field type {} about a new searcher." , type , o . getClass ( ) . getName ( ) , name ) ; try { ( ( SearcherAware ) o ) . inform ( searcher ) ; } catch ( IOException e ) { logger . error ( "Failed to inform {} ({}) of field type {} about a new searcher." , type , o . getClass ( ) . getName ( ) , name , e ) ; throw new IllegalArgumentException ( "Failed to inform about a new searcher." , e ) ; } }


signature:
public class SearcherAwareReloader { /** * Inform { @ link SearcherAware } filter factories in a { @ link TokenizerChain } about a new searcher .
 * @ param name
 * Name of the field type .
 * @ param tokenizers
 * The { @ link TokenizerChain } .
 * @ param searcher
 * The new searcher . */
private void inform ( String name , TokenizerChain tokenizers , SolrIndexSearcher searcher ) { } }

implementation: for ( TokenFilterFactory factory : tokenizers . getTokenFilterFactories ( ) ) { inform ( "token filter factory" , name , factory , searcher ) ; }


signature:
public class JdbcDataSourceFactory { /** * Lookup data source .
 * @ param config
 * Configuration .
 * @ return DataSource . */
public static DataSource getDataSource ( Map < ? , ? > config ) { } }

implementation: String ignoreString = ( String ) config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! "false" . equals ( ignoreString ) ; String dataSourceName = ( String ) config . remove ( JdbcReaderFactoryParams . DATASOURCE ) ; DataSource dataSource = null ; if ( dataSourceName != null ) { dataSource = jndiDataSource ( fixJndiName ( dataSourceName ) ) ; if ( dataSource == null ) { log . error ( "Data source {} not found." , dataSourceName ) ; if ( ! ignore ) { throw new IllegalArgumentException ( "No data source found." ) ; } } } else { log . error ( "No data source configured." ) ; if ( ! ignore ) { throw new IllegalArgumentException ( "No data source configured." ) ; } } return dataSource ;


signature:
public class JdbcDataSourceFactory { /** * Initializes the database and lookups a { @ linkplain DataSource } in JNDI .
 * @ param jndiName
 * JNDI name of data source . */
private static DataSource jndiDataSource ( String jndiName ) { } }

implementation: try { Context ctx = new InitialContext ( ) ; log . info ( "Looking up data source {} in JNDI." , jndiName ) ; DataSource dataSource = ( DataSource ) ctx . lookup ( jndiName ) ; ctx . close ( ) ; return dataSource ; } catch ( NameNotFoundException e ) { return null ; } catch ( NamingException e ) { log . error ( "JNDI error: {}." , e . getMessage ( ) ) ; throw new IllegalArgumentException ( "JNDI error." , e ) ; } catch ( ClassCastException e ) { log . error ( "The JNDI resource {} is no data source: {}." , jndiName , e . getMessage ( ) ) ; throw new IllegalArgumentException ( "The JNDI resource is no data source." , e ) ; }


signature:
public class JdbcReaderFactory { /** * Create the { @ link JdbcReader } from configuration .
 * Set synonyms file to a fixed name .
 * This is needed because our patched resource loader should load the synonyms exactly once .
 * @ param config
 * Configuration .
 * @ param originalParamName
 * Default synonym file name .
 * @ return JdbcReader . */
public static JdbcReader createFromSolrParams ( Map < String , String > config , String originalParamName ) { } }

implementation:
Preconditions . checkNotNull ( config ) ; // Set a fixed synonyms " file " .
// This " file " will be loaded from the database by the JdbcResourceLoader .
if ( originalParamName != null ) { config . put ( originalParamName , JdbcResourceLoader . DATABASE ) ; } DataSource dataSource = JdbcDataSourceFactory . getDataSource ( config ) ; String sql = config . remove ( JdbcReaderFactoryParams . SQL ) ; String ignoreString = config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! "false" . equals ( ignoreString ) ; return new SimpleJdbcReader ( dataSource , sql , ignore ) ;


signature:
public class Any { /** * ITERABLES - complete */
@ NonNull public static < T > Iterable < T > iterableOf ( final InstanceOf < T > type ) { } }

implementation: return PrivateGenerate . FIXTURE . createMany ( type ) ;


signature:
public class Any { /** * ARRAYS - complete */
@ NonNull public static < T > T [ ] arrayOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "arrayOf" ) ) ; return PrivateGenerate . manyAsArrayOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * LISTS - complete */
@ NonNull public static < T > List < T > listOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "listOf" ) ) ; return PrivateGenerate . manyAsListOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * COLLECTIONS - complete */
@ NonNull public static < T > Collection < T > collectionOf ( final InstanceOf < T > typeToken , final InlineConstrainedGenerator < T > omittedValues ) { } }

implementation: return PrivateGenerate . manyAsListOf ( typeToken , omittedValues ) ;


signature:
public class Any { /** * TODO variations */
@ NonNull public static < T > Set < T > setOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "setOf" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * TODO UT */
@ NonNull public static < T > Set < T > setOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { } }

implementation: assertIsNotParameterized ( type , ErrorMessages . msgInline ( "setOf" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( type ) , omittedValues ) ;


signature:
public class Any { /** * queues : incomplete */
@ NonNull public static < T > Queue < T > queueOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "queueOf" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * TODO UT */
@ NonNull public static < T > Queue < T > queueOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { } }

implementation: assertIsNotParameterized ( type , ErrorMessages . msgInline ( "queueOf" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( type ) , omittedValues ) ;


signature:
public class Any { /** * Deques : incomplete */
@ NonNull public static < T > Deque < T > dequeOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "dequeOf" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * TODO UT */
@ NonNull public static < T > Deque < T > dequeOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { } }

implementation: assertIsNotParameterized ( type , ErrorMessages . msgInline ( "dequeOf" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( type ) , omittedValues ) ;


signature:
public class Any { /** * sorted sets : incomplete */
@ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , ErrorMessages . msg ( "sortedSetOf" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( clazz ) ) ;


signature:
public class Any { /** * TODO UT */
@ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { } }

implementation: assertIsNotParameterized ( type , ErrorMessages . msgInline ( "sortedSetOf" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( type ) , omittedValues ) ;


signature:
public class Any { /** * TODO variations and UT */
@ NonNull public static < T , V > SortedMap < T , V > sortedMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { } }

implementation: assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return PrivateGenerate . manyAsSortedMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ;


signature:
public class Any { /** * TODO variations */
@ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { } }

implementation: assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return PrivateGenerate . manyAsMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ;


signature:
public class Any { /** * / optionals */
@ NonNull public static < T > Optional < T > optional ( Class < T > type ) { } }

implementation: return Optional . of ( Any . anonymous ( type ) ) ;


signature:
public class PrivateGenerate { /** * TODO rethink putting this into the Fixture class */
static < T > List < T > manyAsListOf ( final TypeToken < T > typeToken , final InlineConstrainedGenerator < T > generator ) { } }

implementation: final List < T > result = CollectionFactory . createList ( ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; return result ;


signature:
public class InterfaceHandler { /** * TODO check case when new X < Integer > ( ) . GetValue ( ) and new X < String > ( ) . GetValue ( ) afterwards - does this work ? */
private Object generateFreshValueFor ( final Object proxy , final Method method , final TypeToken < ? > returnType ) { } }

implementation: final Optional < Object > freshReturnValue = createReturnValue ( fixture , returnType ) ; if ( freshReturnValue . isPresent ( ) ) { methodsInvocationResultCache . setFor ( proxy , method , freshReturnValue . get ( ) ) ; } return freshReturnValue . orNull ( ) ;


signature:
public class AnyVavr { /** * todo add generics checks */
@ NonNull public static < T > List < T > listOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "listOf" ) ) ; return io . vavr . collection . List . ofAll ( Any . listOf ( clazz ) ) ;


signature:
public class AnyVavr { /** * / / / / / arrays */
@ NonNull public static < T > Array < T > arrayOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "arrayOf" ) ) ; return Array . ofAll ( Any . listOf ( clazz ) ) ;


signature:
public class AnyVavr { /** * / / / / / hashsets */
@ NonNull public static < T > HashSet < T > hashSetOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "hashSetOf" ) ) ; return HashSet . ofAll ( Any . listOf ( clazz ) ) ;


signature:
public class AnyVavr { /** * / / / / / tree sets */
@ NonNull public static < T > TreeSet < T > treeSetOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "treeSetOf" ) ) ; return TreeSet . ofAll ( ( Iterable ) Any . iterableOf ( clazz ) ) ;


signature:
public class AnyVavr { /** * / / / / / sets */
@ NonNull public static < T > Set < T > setOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "setOf" ) ) ; return hashSetOf ( clazz ) ;


signature:
public class AnyVavr { /** * / / / / / sorted sets */
@ NonNull public static < T > SortedSet < T > sortedSetOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "sortedSetOf" ) ) ; return treeSetOf ( clazz ) ;


signature:
public class AnyVavr { /** * / / / / / hash maps */
@ NonNull public static < T , V > HashMap < T , V > hashMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { } }

implementation: assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return HashMap . ofAll ( Any . mapBetween ( keyClass , valueClass ) ) ;


signature:
public class AnyVavr { /** * / / / / / maps */
@ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { } }

implementation: assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return hashMapBetween ( keyClass , valueClass ) ;


signature:
public class AnyVavr { /** * / / / / / queues */
@ NonNull public static < T > Queue < T > queueOf ( Class < T > clazz ) { } }

implementation: assertIsNotParameterized ( clazz , msg ( "queueOf" ) ) ; return Queue . ofAll ( Any . queueOf ( clazz ) ) ;


signature:
public class AnyVavr { /** * options */
@ NonNull public static < T > Option < T > option ( final Class < T > type ) { } }

implementation: assertIsNotParameterized ( type , msgInline ( "option" ) ) ; return Option . of ( Any . instanceOf ( type ) ) ;


signature:
public class AnyVavr { /** * eithers - left */
@ NonNull public static < T , U > Either < T , U > left ( final Class < T > leftType ) { } }

implementation: assertIsNotParameterized ( leftType , msgInline ( "left" ) ) ; return Either . left ( Any . instanceOf ( leftType ) ) ;


signature:
public class AnyVavr { /** * eithers - right */
@ NonNull public static < T , U > Either < T , U > right ( final Class < U > rightType ) { } }

implementation: assertIsNotParameterized ( rightType , msgInline ( "right" ) ) ; return Either . right ( Any . instanceOf ( rightType ) ) ;


signature:
public class AnyVavr { /** * validations - failures */
@ NonNull public static < T , U > Validation < T , U > validationFailed ( final Class < T > type ) { } }

implementation: assertIsNotParameterized ( type , msgInline ( "validationFailed" ) ) ; return Validation . invalid ( Any . instanceOf ( type ) ) ;


signature:
public class AnyVavr { /** * validations - successful */
@ NonNull public static < T , U > Validation < T , U > validationSuccess ( final Class < U > type ) { } }

implementation: assertIsNotParameterized ( type , msgInline ( "validationSuccess" ) ) ; return Validation . valid ( Any . instanceOf ( type ) ) ;


signature:
public class AnyVavr { /** * try - successful */
@ NonNull public static < T > Try < T > trySuccess ( final Class < T > type ) { } }

implementation: assertIsNotParameterized ( type , msgInline ( "trySuccess" ) ) ; return Try . success ( Any . instanceOf ( type ) ) ;


signature:
public class JdbcFixture { /** * Registers a database to further execute SQL commands
 * < p > < code >
 * | connect jdbc on | < i > database < / i > | with url | < i > url < / i > | and driver | < i > driver < / i > | and username | < i > username < / i > | and | < i > password < / i > |
 * < / code > < / p >
 * @ param url */
@ SuppressWarnings ( "unchecked" ) public boolean connectJdbcOnWithUrlAndDriverAndUsernameAndPassword ( String dataBaseId , String url , String driverClassName , String username , String password ) throws ReflectiveOperationException { } }

implementation: SimpleDriverDataSource dataSource = new SimpleDriverDataSource ( ) ; dataSource . setUrl ( url ) ; dataSource . setDriverClass ( ( Class < Driver > ) Class . forName ( driverClassName ) ) ; dataSource . setUsername ( username ) ; dataSource . setPassword ( password ) ; this . templateMap . put ( dataBaseId , new JdbcTemplate ( dataSource ) ) ; return true ;


signature:
public class JdbcFixture { /** * Simply runs a SQL command , used for udpates , inserts which the result doesn ' t matter .
 * < p > < code >
 * | run in | < i > database < / i > | the sql | < i > sql < / i > |
 * < / code > < / p >
 * @ param database registered database to run the SQL
 * @ param sql to run */
public boolean runInTheSql ( String database , final String sql ) { } }

implementation: getDatabaseJdbcTemplate ( database ) . update ( sql ) ; return true ;


signature:
public class JdbcFixture { /** * Used generally when the result is assigned to a variable
 * < p > < code >
 * | $ variable = | query in | < i > database < / i > | with sql | < i > sql < / i > |
 * < / code > < / p >
 * @ param database registered database to run the SQL
 * @ param sql to run */
public String queryInWithSql ( String database , String sql ) { } }

implementation: JdbcTemplate template = getDatabaseJdbcTemplate ( database ) ; if ( sql != null && ! sql . trim ( ) . toUpperCase ( ) . startsWith ( JdbcFixture . SELECT_COMMAND_PREFIX ) ) { return Objects . toString ( template . update ( sql ) ) ; } List < String > results = template . queryForList ( sql , String . class ) ; if ( results == null || results . isEmpty ( ) ) { return null ; } return results . get ( 0 ) ;


signature:
public class UBValue { /** * Interprets a strongly - typed number array to array of booleans .
 * If a value found in the array is greater than 0 return true , false otherwise .
 * @ return booleans */
public boolean [ ] asBoolArray ( ) { } }

implementation: boolean [ ] retval ; UBArray array = asArray ( ) ; switch ( array . getStrongType ( ) ) { case Int8 : { byte [ ] data = ( ( UBInt8Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int16 : { short [ ] data = ( ( UBInt16Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int32 : { int [ ] data = ( ( UBInt32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int64 : { long [ ] data = ( ( UBInt64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float32 : { float [ ] data = ( ( UBFloat32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float64 : { double [ ] data = ( ( UBFloat64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } default : throw new RuntimeException ( "not an int32[] type" ) ; } return retval ;


signature:
public class Query { /** * Executes a query which returns all rows in the entity table
 * that match the fields of the example object having values other
 * than the defaults .
 * Calling method MUST close the { @ link Cursor } !
 * @ return Cursor */
public Query < T > byExample ( T obj ) { } }

implementation: if ( obj != null ) { return dao . getTableHelper ( ) . buildFilter ( this , obj ) ; } return this ;


signature:
public class Query { /** * Convenience methods for comparing equality of each wrapper type */
public Query < T > eq ( Column colName , Boolean param ) { } }

implementation: Integer sqlValue = BooleanConverter . GET . toSql ( param ) ; where . append ( " AND " + colName + "=?" ) ; params . add ( BooleanConverter . GET . toString ( sqlValue ) ) ; return this ;


signature:
public class TableHelper { /** * Upgrades the table that represents the associated entity . This will
 * typically be an ALTER TABLE statement .
 * @ param db
 * @ param oldVersion
 * @ param newVersion */
protected void onUpgrade ( final SQLiteDatabase db , final int oldVersion , final int newVersion ) { } }

implementation: db . execSQL ( upgradeSql ( oldVersion , newVersion ) ) ;


signature:
public class TableHelper { /** * Backs up the current table to a CSV file .
 * @ param db
 * @ param ctx
 * @ param suffix
 * @ return true on success */
public boolean backup ( SQLiteDatabase db , Context ctx , String suffix ) { } }

implementation: try { new CsvTableWriter ( this ) . dumpToCsv ( ctx , db , suffix ) ; } catch ( SQLException e ) { if ( e . getMessage ( ) . contains ( "no such table" ) ) { Log . w ( TAG , "Table " + this . getTableName ( ) + " doesn't exist. This is expected if the table is new in this db version." ) ; } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } return true ;


signature:
public class TableHelper { /** * Restores a table from a text file .
 * @ param db
 * @ param ctx
 * @ param suffix */
public void restore ( SQLiteDatabase db , Context ctx , String suffix ) { } }

implementation: new CsvTableReader ( this ) . importFromCsv ( ctx , db , suffix ) ;


signature:
public class TableHelper { /** * Cursor wrapper methods which bind to primitive type columns
 * and return the corresponding wrapper type which may be null */
protected byte [ ] getBlobOrNull ( Cursor c , int col ) { } }

implementation: return c . isNull ( col ) ? null : c . getBlob ( col ) ;


signature:
public class ContactActivity { /** * The default content for this Activity has a TextView that is shown when
 * the list is empty . If you would like to change the text , call this method
 * to supply the text it should use . */
public void setEmptyText ( CharSequence emptyText ) { } }

implementation: if ( mListView != null ) { View emptyView = mListView . getEmptyView ( ) ; if ( emptyText instanceof TextView ) { ( ( TextView ) emptyView ) . setText ( emptyText ) ; } }


signature:
public class CsvTableWriter { /** * Dumps a database table to a CSV file in the default location .
 * Returns the number of rows written to the file .
 * @ param ctx
 * @ param db
 * @ param suffix
 * @ return count of rows in the exported file */
public int dumpToCsv ( Context ctx , SQLiteDatabase db , String suffix ) throws FileNotFoundException { } }

implementation: int numRowsWritten = 0 ; Cursor c ; String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; c = db . query ( th . getTableName ( ) , null , null , null , null , null , null ) ; FileOutputStream fos ; fos = ctx . openFileOutput ( filename , 0 ) ; PrintWriter printWriter = new PrintWriter ( fos ) ; String headerRow = buildHeaderRow ( ) ; printWriter . println ( headerRow ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { String csv = buildCsvRow ( c ) ; printWriter . println ( csv ) ; numRowsWritten ++ ; } printWriter . flush ( ) ; printWriter . close ( ) ; return numRowsWritten ;


signature:
public class SelectQueryClause { /** * Adds an expression to this Select Clause with support for Constructor
 * Expressions .
 * @ param constructorClass
 * class to be use for constructor expression , make shure it has
 * a constructor that fits to the given { @ literal SQL } Select
 * Items
 * @ param expression
 * expression used as constructor parameter , will be passed
 * unchanged to the appropriated constructor of the given class
 * @ return the query builder */
public < T > QueryBuilder add ( final Class < T > constructorClass , final String expression ) { } }

implementation: return add ( ( String ) null , constructorClass , expression ) ;


signature:
public class SelectQueryClause { /** * Adds an expression to this Select Clause with support for Constructor
 * Expressions .
 * @ param lhsStatement
 * left hand side of the statement , e . g . { @ code DISTINCT }
 * @ param constructorClass
 * class to be use for Constructor Expression , make sure it has a
 * constructor that fits to the given { @ literal SQL } Select Items
 * @ param expression
 * expression used as constructor parameter , will be passed
 * unchanged to the appropriated constructor of the given class
 * @ return the query builder */
public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String expression ) { } }

implementation: StringBuilder itemBuilder = new StringBuilder ( ) ; if ( lhsStatement != null ) { itemBuilder . append ( lhsStatement ) ; itemBuilder . append ( " " ) ; } itemBuilder . append ( "NEW " ) ; itemBuilder . append ( constructorClass . getName ( ) ) ; itemBuilder . append ( "(" ) ; itemBuilder . append ( expression ) ; itemBuilder . append ( ")" ) ; items . add ( itemBuilder . toString ( ) ) ; return builder ;


signature:
public class SelectQueryClause { /** * Adds expressions to this Select Clause with support for Constructor
 * Expressions .
 * @ param constructorClass
 * class to be use for constructor expression , make shure it has
 * a constructor that fits to the given { @ literal SQL } Select
 * Items
 * @ param expressions
 * constructor parameters , will be passed as comma separated list
 * to the appropriated constructor of the given class
 * @ return the query builder */
public < T > QueryBuilder add ( final Class < T > constructorClass , final String ... expressions ) { } }

implementation: return add ( ( String ) null , constructorClass , expressions ) ;


signature:
public class SelectQueryClause { /** * Adds expressions to this Select Clause with support for Constructor
 * Expressions .
 * @ param lhsStatement
 * left hand side of the statement , e . g . { @ code DISTINCT }
 * @ param constructorClass
 * class to be use for constructor expression , make shure it has
 * a constructor that fits to the given { @ literal SQL } Select
 * items
 * @ param expressions
 * constructor parameters , will be passed as comma separated list
 * to the appropriated constructor of the given class
 * @ return the query builder */
public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String ... expressions ) { } }

implementation: return add ( lhsStatement , constructorClass , StringUtils . join ( expressions ) ) ;


signature:
public class CsvUtils { /** * Returns a { @ link String } for a CSV column enclosed in double
 * quotes , if required .
 * see < a
 * href = " http : / / en . wikipedia . org / wiki / Comma - separated _ values " > Wikipedia < / a >
 * and < a href = " http : / / tools . ietf . org / html / rfc4180 " > RFC 4180 < / a > .
 * @ param str the input String , may be null
 * @ return the input String enclosed in double quotes if required , or null */
public static String escapeCsv ( String str ) { } }

implementation: if ( str == null ) return "" ; if ( containsNone ( str , CSV_SEARCH_CHARS ) ) return str ; StringWriter out = new StringWriter ( ) ; out . write ( QUOTE ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; if ( c == QUOTE ) out . write ( QUOTE ) ; out . write ( c ) ; } out . write ( QUOTE ) ; return out . toString ( ) ;


signature:
public class CsvUtils { /** * Removes enclosing quotes and unescapes double quotes
 * @ param str An escaped CSV value
 * @ return the original value */
public static String unescapeCsv ( String str ) { } }

implementation: if ( str == null ) return null ; if ( ! ( str . charAt ( 0 ) == QUOTE && str . charAt ( str . length ( ) - 1 ) == QUOTE ) ) return str ; String quoteless = str . substring ( 1 , str . length ( ) - 1 ) ; return quoteless . replace ( QUOTE_STR + QUOTE_STR , QUOTE_STR ) ;


signature:
public class CsvUtils { /** * Returns values from a CSV String .
 * @ param csvRow
 * @ return */
public static List < String > getValues ( String csvRow ) { } }

implementation:
List < String > values = new ArrayList < String > ( ) ; StringReader in = new StringReader ( csvRow ) ; String value ; try { value = nextValue ( in ) ; while ( true ) { values . add ( value ) ; value = nextValue ( in ) ; } } catch ( IOException e ) { // TODO handle case of final null value better ?
if ( csvRow . lastIndexOf ( ',' ) == csvRow . length ( ) - 1 ) values . add ( null ) ; return values ; }


signature:
public class CsvUtils { /** * Obtains the next value from a { @ link StringReader } .
 * @ param in
 * @ return An escaped value
 * @ throws IOException */
public static String nextValue ( StringReader in ) throws IOException { } }

implementation:
StringWriter w = new StringWriter ( ) ; boolean inQuotedValue = false ; boolean openQuote = false ; int c = in . read ( ) ; if ( c == QUOTE ) inQuotedValue = true ; else if ( c == DELIMITER ) { return null ; } else if ( c >= 0 ) { w . write ( c ) ; } else { throw new IOException ( "End of line reached" ) ; } c = in . read ( ) ; while ( c >= 0 ) { if ( c == QUOTE ) { if ( inQuotedValue ) { if ( openQuote ) { openQuote = false ; w . write ( QUOTE ) ; } else { openQuote = true ; } } else // invalid
return w . toString ( ) ; } else if ( c == DELIMITER ) { if ( openQuote ) return w . toString ( ) ; else if ( inQuotedValue ) w . write ( c ) ; else // invalid
return w . toString ( ) ; } else w . write ( c ) ; c = in . read ( ) ; } return w . toString ( ) ;


signature:
public class CsvUtils { /** * Parses a CSV row containing name = value pairs .
 * @ param csvPairs
 * @ return Map < name , value > */
public static Map < String , String > getAsMap ( String csvPairs ) { } }

implementation: Map < String , String > map = new HashMap < String , String > ( ) ; String [ ] pairs = csvPairs . split ( "," ) ; for ( String pair : pairs ) { String [ ] split = pair . split ( "=" ) ; map . put ( split [ 0 ] , split [ 1 ] ) ; } return map ;


signature:
public class CsvUtils { /** * Returns a String containing a comma - separated list
 * of name = value pairs from a map .
 * @ param map
 * @ return String csv */
public static String mapToCsv ( Map < String , String > map ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; for ( String key : map . keySet ( ) ) { sb . append ( "," ) ; String val = map . get ( key ) ; sb . append ( key + "=" + val ) ; } return sb . toString ( ) . substring ( 1 ) ;


signature:
public class StringUtils { /** * Joins items of a text list , separating items by comma .
 * @ param list
 * list of text items
 * @ return joined list */
public static String join ( final List < String > list ) { } }

implementation:
// zero , empty or one element
if ( list == null ) { return null ; } else if ( list . size ( ) == 0 ) { return "" ; } else if ( list . size ( ) == 1 ) { return list . get ( 0 ) ; } // two or more elements
final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( ", " ) ; } builder . append ( item ) ; } return builder . toString ( ) ;


signature:
public class StringUtils { /** * Joins items of a text array , separating items by comma .
 * @ param list
 * list of text items
 * @ return joined list */
public static String join ( final String [ ] list ) { } }

implementation:
// zero , empty or one element
if ( list == null ) { return null ; } else if ( list . length == 0 ) { return "" ; } else if ( list . length == 1 ) { return list [ 0 ] ; } // two or more elements
final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( ", " ) ; } builder . append ( item ) ; } return builder . toString ( ) ;


signature:
public class OrderColumn { /** * Renders this object as { @ literal JPQL } fragment .
 * @ return OrderColumn rendered as String */
public String render ( ) { } }

implementation: StringBuilder builder = new StringBuilder ( column ) ; if ( order != null ) { builder . append ( " " ) . append ( getOrder ( ) . name ( ) ) ; } return builder . toString ( ) ;


signature:
public class DatabaseModel { /** * Populate the model of a database and its associated tables from
 * a file in support of incremental compilation .
 * @ param reader
 * @ param logger
 * @ return DatabaseModel
 * @ throws IOException */
public static DatabaseModel readFromIndex ( BufferedReader reader , ProcessorLogger logger ) throws IOException { } }

implementation:
String dbInfo = reader . readLine ( ) ; logger . info ( dbInfo ) ; Map < String , String > props = CsvUtils . getAsMap ( dbInfo ) ; String dbName = props . get ( "dbName" ) ; int dbVersion = Integer . parseInt ( props . get ( "dbVersion" ) ) ; String helperClass = props . get ( "helperClass" ) ; DatabaseModel dbModel = new DatabaseModel ( dbName , dbVersion , helperClass ) ; // read TableHelpers
List < String > tables = new ArrayList < String > ( ) ; String th = reader . readLine ( ) ; while ( th != null && ! th . equals ( StormEnvironment . END_DATABASE ) ) { tables . add ( th ) ; th = reader . readLine ( ) ; } dbModel . tableHelpers = tables ; return dbModel ;


signature:
public class DatabaseModel { /** * Write the database info and associated tables to a file
 * in support of incremental compilation .
 * @ param out PrintWriter */
public void writeToIndex ( PrintWriter out ) { } }

implementation:
out . println ( StormEnvironment . BEGIN_DATABASE ) ; Map < String , String > dbMap = new HashMap < String , String > ( ) ; dbMap . put ( "dbName" , this . getDbName ( ) ) ; dbMap . put ( "dbVersion" , String . valueOf ( this . getDbVersion ( ) ) ) ; dbMap . put ( "helperClass" , this . getQualifiedClassName ( ) ) ; String dbInfo = CsvUtils . mapToCsv ( dbMap ) ; out . println ( dbInfo ) ; // write TableHelpers
for ( String th : this . tableHelpers ) { out . println ( th ) ; } out . println ( StormEnvironment . END_DATABASE ) ;


signature:
public class EntityProcessor { /** * Verifies that the entity has exactly one id field of type long . */
private void inspectId ( ) { } }

implementation:
if ( entityModel . getIdField ( ) == null ) { // Default to field named " id "
List < FieldModel > fields = entityModel . getFields ( ) ; for ( FieldModel f : fields ) { if ( EntityModel . DEFAULT_ID_FIELD . equals ( f . getFieldName ( ) ) ) { entityModel . setIdField ( f ) ; } } } FieldModel idField = entityModel . getIdField ( ) ; if ( idField != null && "long" . equals ( idField . getJavaType ( ) ) ) { return ; } else { abort ( "Entity must contain a field named id or annotated with @Id of type long" ) ; }


signature:
public class EntityProcessor { /** * Trying to get Class < ? > from an annotation raises an exception
 * see http : / / stackoverflow . com / questions / 7687829 / java - 6 - annotation - processing - getting - a - class - from - an - annotation */
private static TypeMirror getBaseDaoTypeMirror ( Entity entity ) { } }

implementation: if ( entity != null ) { try { entity . baseDaoClass ( ) ; } catch ( MirroredTypeException mte ) { return mte . getTypeMirror ( ) ; } } return null ;


signature:
public class EntityProcessor { /** * Builds a BaseDaoModel from the class passed as attribute baseDaoClass of the annotation Entity
 * @ param entity
 * @ return BaseDaoModel containing the package name + Class name */
private static BaseDaoModel getBaseDaoClass ( Entity entity ) { } }

implementation: String qualifiedName = SQLiteDao . class . getName ( ) ; TypeMirror typeMirror = getBaseDaoTypeMirror ( entity ) ; if ( typeMirror != null ) qualifiedName = typeMirror . toString ( ) ; return new BaseDaoModel ( qualifiedName ) ;


signature:
public class FieldModel { /** * Morph bind type like INT = = > Int so it can be used in a Cursor getXxx
 * method name . Never called at runtime .
 * @ return */
public String getBindType ( ) { } }

implementation: String bindType = getConverter ( ) . getBindType ( ) . name ( ) ; return bindType . charAt ( 0 ) + bindType . toLowerCase ( ) . substring ( 1 ) ;


signature:
public class FieldModel { /** * Capitalizes the first letter to create a valid getter / setter name .
 * @ param String
 * @ return String */
private String capFirst ( String anyName ) { } }

implementation:
// obscure Java convention :
// if second letter capitalized , leave it alone
if ( anyName . length ( ) > 1 ) if ( anyName . charAt ( 1 ) >= 'A' && anyName . charAt ( 1 ) <= 'Z' ) return anyName ; String capFirstLetter = anyName . substring ( 0 , 1 ) . toUpperCase ( ) ; return capFirstLetter + anyName . substring ( 1 ) ;


signature:
public class CsvTableReader { /** * Attempts to import a database table from a CSV file in the default
 * location .
 * @ param ctx
 * @ param db
 * @ param suffix
 * @ return count of rows imported or - 1 if error */
public int importFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { } }

implementation: String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; FileInputStream fileInputStream ; try { fileInputStream = ctx . openFileInput ( filename ) ; return importFromCsv ( db , fileInputStream ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return - 1 ; }


signature:
public class CsvTableReader { /** * Attempts to import a database table from an { @ link InputStream }
 * formatted as a CSV file . Does all inserts in a single transaction
 * for efficiency and so that all inserts will succeed or fail
 * together .
 * @ param db
 * @ param is
 * @ return count of rows imported or - 1 if error */
public int importFromCsv ( SQLiteDatabase db , InputStream is ) { } }

implementation: int numInserts = 0 ; db . beginTransaction ( ) ; insertHelper = new DatabaseUtils . InsertHelper ( db , th . getTableName ( ) ) ; try { InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader reader = new BufferedReader ( isr ) ; String headerRow = reader . readLine ( ) ; String csvRow = reader . readLine ( ) ; while ( csvRow != null ) { long rowId = parseAndInsertRow ( csvRow ) ; if ( rowId == - 1L ) { throw new RuntimeException ( "Error after row " + numInserts ) ; } numInserts ++ ; csvRow = reader . readLine ( ) ; } db . setTransactionSuccessful ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { db . endTransaction ( ) ; } return numInserts ;


signature:
public class CsvTableReader { /** * Parse the values in a CSV row , map them to the table column
 * order , and insert . Uses { @ link InsertHelper } so it may be
 * called repeatedly within a transaction for max performance .
 * @ param csvRow
 * @ return row ID of the newly inserted row or - 1 */
private long parseAndInsertRow ( String csvRow ) { } }

implementation: List < String > textValues = CsvUtils . getValues ( csvRow ) ; insertHelper . prepareForInsert ( ) ; String [ ] rowValues = textValues . toArray ( new String [ textValues . size ( ) ] ) ; th . bindRowValues ( insertHelper , rowValues ) ; return insertHelper . execute ( ) ;


signature:
public class DatabaseHelper { /** * Calls { @ link TableHelper # onCreate ( SQLiteDatabase ) } for each TableHelper .
 * @ see android . database . sqlite . SQLiteOpenHelper # onCreate ( android . database . sqlite . SQLiteDatabase ) */
@ Override public void onCreate ( SQLiteDatabase db ) { } }

implementation: for ( TableHelper th : getTableHelpers ( ) ) { th . onCreate ( db ) ; }


signature:
public class DatabaseHelper { /** * Calls a method on each TableHelper depending on the { @ link UpgradeStrategy } .
 * In order to prevent recursive calls to getDatabase ( ) , this method must pass
 * the db parameter through to any other methods that need it .
 * @ see < a href = " https : / / code . google . com / p / storm - gen / issues / detail ? id = 11 " > Issue 11 < / a >
 * @ see android . database . sqlite . SQLiteOpenHelper # onUpgrade ( android . database . sqlite . SQLiteDatabase , int , int ) */
@ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { } }

implementation: switch ( getUpgradeStrategy ( ) ) { case DROP_CREATE : this . dropAndCreate ( db ) ; break ; case BACKUP_RESTORE : this . backupAndRestore ( this . getContext ( ) , db ) ; break ; case UPGRADE : this . upgrade ( db , oldVersion , newVersion ) ; break ; }


signature:
public class DatabaseHelper { /** * Calls { @ link TableHelper # onUpgrade ( SQLiteDatabase , int , int ) } for
 * each TableHelper . Override this method to implement your own
 * upgrade strategy .
 * @ param db
 * @ param oldVersion
 * @ param newVersion */
public void upgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { } }

implementation: for ( TableHelper th : getTableHelpers ( ) ) { th . onUpgrade ( db , oldVersion , newVersion ) ; }


signature:
public class DatabaseHelper { /** * Backs up all tables to CSV , drops and recreates them , then restores
 * them from CSV . By default , creates CSV filenames with no suffix . You
 * could override this method to supply a timestamp suffix ( make sure it ' s
 * the same for both backup and restore ) , but beware that this could
 * cause backup files to proliferate . Ideally , this method should
 * clean up backup files after the database has been restored .
 * @ param ctx
 * @ param db */
public void backupAndRestore ( Context ctx , SQLiteDatabase db ) { } }

implementation: if ( backupAllTablesToCsv ( ctx , db , null ) ) { dropAndCreate ( db ) ; restoreAllTablesFromCsv ( ctx , db , null ) ; } else { throw new RuntimeException ( "Backup of " + getDatabaseName ( ) + " failed, aborting upgrade" ) ; }


signature:
public class DatabaseHelper { /** * Backup all tables to CSV files , one per table
 * @ param ctx
 * @ param db
 * @ param suffix Optional filename suffix , none if null
 * @ return True if all tables completed without errors */
public boolean backupAllTablesToCsv ( Context ctx , SQLiteDatabase db , String suffix ) { } }

implementation: boolean allSucceeded = true ; for ( TableHelper table : getTableHelpers ( ) ) { allSucceeded &= table . backup ( db , ctx , suffix ) ; } return allSucceeded ;


signature:
public class DatabaseHelper { /** * Restore all tables from CSV files , one per table
 * @ param ctx
 * @ param db
 * @ param suffix Optional filename suffix , none if null */
public void restoreAllTablesFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { } }

implementation: for ( TableHelper table : getTableHelpers ( ) ) { table . restore ( db , ctx , suffix ) ; }


signature:
public class StormEnvironment { /** * Read the current model state from a file in support of incremental
 * compilation . This is necessary because the annotation processor has
 * access to only classes which have been annotated ( and any resulting
 * generated classes on subsequent rounds ) , but DatabaseHelper classes
 * aren ' t available when doing incremental compilation on a new @ Entity .
 * @ see http
 * : / / stackoverflow . com / questions / 10585665 / how - can - i - examine - the - whole
 * - source - tree - with - an - annotation - processor
 * https : / / github . com / sentinelt / evo - classindex
 * @ param Filer
 * used by the annotation processor */
void readIndex ( Filer filer ) { } }

implementation:
StandardLocation location = StandardLocation . SOURCE_OUTPUT ; FileObject indexFile ; try { indexFile = filer . getResource ( location , "com.turbomanage.storm" , ENV_FILE ) ; logger . info ( "Reading index " + indexFile . toUri ( ) ) ; // indexFile . openReader ( ) not implemented on all platforms
Reader fileReader = new InputStreamReader ( indexFile . openInputStream ( ) ) ; BufferedReader reader = new BufferedReader ( fileReader ) ; String line = reader . readLine ( ) ; // BEGIN _ CONVERTERS
line = reader . readLine ( ) ; while ( line != null && ! line . startsWith ( END_CONVERTERS ) ) { ConverterModel converter = ConverterModel . readFromIndex ( line , logger ) ; this . addConverter ( converter ) ; line = reader . readLine ( ) ; } line = reader . readLine ( ) ; while ( line != null && line . startsWith ( BEGIN_DATABASE ) ) { DatabaseModel dbModel = DatabaseModel . readFromIndex ( reader , logger ) ; this . addDatabase ( dbModel ) ; line = reader . readLine ( ) ; } reader . close ( ) ; } catch ( IOException e ) { // gulp - - only way to catch not yet existing file on first run
}


signature:
public class StormEnvironment { /** * Write the current model state to a file in support of incremental
 * compilation .
 * @ see StormEnvironment # readIndex ( Filer )
 * @ param Filer
 * used by the annotation processor */
void writeIndex ( Filer filer ) { } }

implementation:
StandardLocation location = StandardLocation . SOURCE_OUTPUT ; FileObject indexFile ; try { indexFile = filer . createResource ( location , "com.turbomanage.storm" , ENV_FILE ) ; OutputStream fos = indexFile . openOutputStream ( ) ; PrintWriter out = new PrintWriter ( fos ) ; // Dump converters
out . println ( BEGIN_CONVERTERS ) ; for ( ConverterModel converter : converters ) { converter . writeToIndex ( out ) ; } out . println ( END_CONVERTERS ) ; // Dump databases
for ( DatabaseModel dbModel : dbModels . values ( ) ) { dbModel . writeToIndex ( out ) ; } out . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; }


signature:
public class StormEnvironment { /** * Register a custom { @ link TypeConverter } for a given data ( field ) type .
 * This method is called at compile time by the annotation processor . In
 * order for the TypeConverter to be visible , it must be in a jar on the
 * client project ' s annotation factory classpath .
 * @ param converter
 * @ return true if successful , false if converter was already registered for
 * type */
public boolean addConverter ( ConverterModel converter ) { } }

implementation:
if ( converters . contains ( converter ) ) return true ; for ( String type : converter . getConvertibleTypes ( ) ) { // TODO what if already put the 1st type ?
if ( typeMap . containsKey ( type ) && ! typeMap . get ( type ) . equals ( converter ) ) return false ; typeMap . put ( type , converter ) ; } converters . add ( converter ) ; logger . info ( "Added " + converter . getQualifiedClassName ( ) ) ; return true ;


signature:
public class QueryBuilder { /** * Returns a JPA Query with all previously specified parameters added .
 * @ param manager
 * JPA EntityManager
 * @ return JPA Query */
public Query createQuery ( final EntityManager manager ) { } }

implementation: if ( manager == null ) { throw new NullPointerException ( "Entity Manager required" ) ; } final Query query = manager . createQuery ( render ( ) ) ; for ( Parameter < ? > parameter : parameters ) { parameter . apply ( query ) ; } return query ;


signature:
public class QueryBuilder { /** * Returns a JPA TypedQuery with all previously specified parameters added .
 * @ param manager
 * JPA EntityManager
 * @ param type
 * the type of the query result
 * @ return JPA Query */
public < T > TypedQuery < T > createQuery ( final EntityManager manager , Class < T > type ) { } }

implementation: if ( manager == null ) { throw new NullPointerException ( "Entity Manager required" ) ; } TypedQuery < T > result = manager . createQuery ( render ( ) , type ) ; for ( Parameter < ? > parameter : parameters ) { parameter . apply ( result ) ; } return result ;


signature:
public class QueryBuilder { /** * Adds the given parameter to the builder . All parameters will added to the
 * JPA Query returned by a call to { @ link # createQuery ( EntityManager ) } or
 * { @ link # createQuery ( EntityManager , Class ) } .
 * @ param name
 * parameter name
 * @ param value
 * parameter value
 * @ param temporalType
 * temporal type
 * @ return builder reference , fluent api support */
public QueryBuilder setParameter ( final String name , final Calendar value , TemporalType temporalType ) { } }

implementation: return setParameter ( new ParameterCalendar ( name , value , temporalType ) ) ;


signature:
public class QueryBuilder { /** * Adds the given parameter to the builder . All parameters will added to the
 * JPA Query returned by a call to { @ link # createQuery ( EntityManager ) } or
 * { @ link # createQuery ( EntityManager , Class ) } .
 * @ param name
 * parameter name
 * @ param value
 * parameter value
 * @ param temporalType
 * temporal type
 * @ return builder reference , fluent api support */
public QueryBuilder setParameter ( final String name , final Date value , final TemporalType temporalType ) { } }

implementation: return setParameter ( new ParameterDate ( name , value , temporalType ) ) ;


signature:
public class QueryBuilder { /** * Adds the given parameter to the builder . All parameters will added to the
 * JPA Query returned by a call to { @ link # createQuery ( EntityManager ) } or
 * { @ link # createQuery ( EntityManager , Class ) } .
 * @ param name
 * parameter name
 * @ param value
 * parameter value
 * @ return builder reference , fluent api support */
public QueryBuilder setParameter ( final String name , final Object value ) { } }

implementation: return setParameter ( new ParameterObject ( name , value ) ) ;


signature:
public class QueryBuilder { /** * Adds given parameter to the builder . All parameters will added to the JPA
 * Query returned by a call to { @ link # createQuery ( EntityManager ) } or
 * { @ link # createQuery ( EntityManager , Class ) } .
 * @ param parameter
 * parameter to add
 * @ return builder reference , fluent api support */
public QueryBuilder setParameter ( final Parameter < ? > parameter ) { } }

implementation: if ( parent == null ) { parameters . add ( parameter ) ; } else { parent . setParameter ( parameter ) ; } return this ;


signature:
public class QueryBuilder { /** * Adds all given parameters to the builder . All parameters will added to
 * the JPA Query returned by a call to { @ link # createQuery ( EntityManager ) }
 * or { @ link # createQuery ( EntityManager , Class ) } .
 * @ param parameters
 * parameters to add
 * @ return builder reference , fluent api support */
public QueryBuilder setParameters ( final List < Parameter < ? > > parameters ) { } }

implementation: if ( parent == null ) { this . parameters . addAll ( parameters ) ; } else { parent . setParameters ( parameters ) ; } return this ;


signature:
public class QueryBuilder { /** * Renders this object as JPQL query string .
 * @ return the query as string */
public String render ( ) { } }

implementation: StringBuilder query = new StringBuilder ( ) ; if ( ! select . isEmpty ( ) ) { query . append ( "SELECT " ) ; query . append ( StringUtils . join ( select . items ) ) ; } if ( ! deleteFrom . isEmpty ( ) ) { query . append ( "DELETE FROM " ) ; query . append ( deleteFrom . item ) ; } if ( ! update . isEmpty ( ) ) { query . append ( "UPDATE " ) ; query . append ( update . item ) ; if ( ! set . isEmpty ( ) ) { query . append ( " SET " ) ; query . append ( StringUtils . join ( set . items ) ) ; } } if ( ! from . isEmpty ( ) ) { query . append ( " FROM " ) ; query . append ( StringUtils . join ( from . items ) ) ; } if ( ! where . isEmpty ( ) ) { query . append ( " WHERE " ) ; query . append ( where . render ( ) ) ; } if ( ! group . isEmpty ( ) ) { query . append ( " GROUP BY " ) ; query . append ( StringUtils . join ( group . items ) ) ; } if ( order . isEmpty ( ) == false ) { query . append ( " ORDER BY " ) ; query . append ( StringUtils . join ( order . items ) ) ; } return query . toString ( ) ;


signature:
public class SQLiteDao { /** * Deletes a single row by ID . Returns the number of rows deleted
 * or 0 if unsuccessful .
 * @ param id
 * @ return count of rows deleted */
public int delete ( Long id ) { } }

implementation: if ( id != null ) { return getWritableDb ( ) . delete ( th . getTableName ( ) , th . getIdCol ( ) + "=?" , new String [ ] { id . toString ( ) } ) ; } return 0 ;


signature:
public class SQLiteDao { /** * Returns a single object by ID or null if no match found .
 * If more than one match is found , throws
 * { @ link TooManyResultsException } .
 * @ param id
 * @ return One entity */
public T get ( Long id ) { } }

implementation: return load ( ) . eq ( th . getIdCol ( ) , id ) . get ( ) ;


signature:
public class SQLiteDao { /** * Inserts a row for the provided entity . If the entity ' s id is the
 * default long ( 0 ) , the database generates an id and populates the
 * entity ' s ID field . Returns the generated ID or - 1 if error .
 * @ param obj An entity
 * @ return ID of newly inserted row or - 1 if err */
public long insert ( T obj ) { } }

implementation:
ContentValues cv = th . getEditableValues ( obj ) ; if ( th . getId ( obj ) == 0 ) { // the default , remove from ContentValues to allow autoincrement
cv . remove ( th . getIdCol ( ) . toString ( ) ) ; } long id = getWritableDb ( ) . insertOrThrow ( th . getTableName ( ) , null , cv ) ; th . setId ( obj , id ) ; return id ;


signature:
public class SQLiteDao { /** * Efficiently insert a collection of entities using { @ link InsertHelper } .
 * @ param many Collection of objects
 * @ return count of inserted objects or - 1 immediately if any errors */
public long insertMany ( Iterable < T > many ) { } }

implementation:
long numInserted = 0 ; InsertHelper insertHelper = new DatabaseUtils . InsertHelper ( getWritableDb ( ) , th . getTableName ( ) ) ; getWritableDb ( ) . beginTransaction ( ) ; try { for ( T obj : many ) { ContentValues cv = th . getEditableValues ( obj ) ; if ( th . getId ( obj ) == 0 ) { // the default , remove from ContentValues to allow autoincrement
cv . remove ( th . getIdCol ( ) . toString ( ) ) ; } long id = insertHelper . insert ( cv ) ; if ( id == - 1 ) return - 1 ; numInserted ++ ; } getWritableDb ( ) . setTransactionSuccessful ( ) ; } finally { getWritableDb ( ) . endTransaction ( ) ; } return numInserted ;


signature:
public class SQLiteDao { /** * Insert or update .
 * @ param obj An entity
 * @ return 0 if updated , - 1 if err , else new ID */
public long save ( T obj ) { } }

implementation: if ( th . getId ( obj ) == 0 ) { return insert ( obj ) ; } long updated = update ( obj ) ; if ( updated == 1 ) { return 0 ; } return - 1 ;


signature:
public class SQLiteDao { /** * Update all columns for the row having the ID matching
 * the provided entity ' s ID .
 * @ param obj An entity
 * @ return count of updated rows */
public long update ( T obj ) { } }

implementation: ContentValues cv = th . getEditableValues ( obj ) ; Long id = th . getId ( obj ) ; int numRowsUpdated = getWritableDb ( ) . update ( th . getTableName ( ) , cv , th . getIdCol ( ) + "=?" , new String [ ] { id . toString ( ) } ) ; return numRowsUpdated ;


signature:
public class SQLiteDao { /** * Convenience method queries the entity table using the provided
 * WHERE clause and parameters and returns a { @ link Cursor } .
 * The calling method MUST close the Cursor !
 * @ param where
 * @ param params
 * @ return Cursor */
public Cursor query ( String where , String [ ] params ) { } }

implementation: return query ( where , params , null ) ;


signature:
public class SQLiteDao { /** * Convenience method queries the entity table using the provided
 * WHERE clause and parameters and returns a { @ link Cursor } .
 * The calling method MUST close the Cursor !
 * @ param where
 * @ param params
 * @ param orderBy
 * @ return */
public Cursor query ( String where , String [ ] params , String orderBy ) { } }

implementation: return getReadableDb ( ) . query ( th . getTableName ( ) , null , where , params , null , null , orderBy ) ;


signature:
public class SQLiteDao { /** * Converts all rows in a { @ link Cursor } to a List of objects .
 * @ param c Cursor
 * @ return List < T > */
public List < T > asList ( Cursor c ) { } }

implementation:
// TODO consider returning Iterable < T > instead
try { ArrayList < T > resultList = new ArrayList < T > ( ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { T obj = th . newInstance ( c ) ; resultList . add ( obj ) ; } return resultList ; } finally { c . close ( ) ; }


signature:
public class SQLiteDao { /** * Converts a { @ link Cursor } to an object . If there is more than one
 * row in the Cursor , throws { @ link TooManyResultsException } .
 * @ param c Cursor
 * @ return An entity */
public T asObject ( Cursor c ) { } }

implementation: try { if ( c . getCount ( ) == 1 ) { c . moveToFirst ( ) ; return th . newInstance ( c ) ; } else if ( c . getCount ( ) > 1 ) { throw new TooManyResultsException ( "Cursor returned " + c . getCount ( ) + " rows" ) ; } return null ; } finally { c . close ( ) ; }


signature:
public class WhereItems { /** * Associate given { @ link QueryBuilder } with this object and all of its
 * items .
 * @ param builder
 * { @ link QueryBuilder } to associate */
void setBuilder ( final QueryBuilder builder ) { } }

implementation: super . setBuilder ( builder ) ; for ( WhereItem item : items ) { item . setBuilder ( builder ) ; }


signature:
public class WhereItems { /** * Add a { @ link WhereItem } to this object .
 * @ param item
 * WhereItem to be added
 * @ return this object */
public WhereItem add ( final WhereItem item ) { } }

implementation: items . add ( item ) ; item . setBuilder ( builder ( ) ) ; return this ;


signature:
public class WhereItems { /** * Adds an { @ literal SQL } { @ code AND } clause .
 * @ return the added { @ code AND } clause as { @ link WhereAnd } object */
public WhereAnd and ( ) { } }

implementation: final WhereAnd and = new WhereAnd ( builder ( ) ) ; items . add ( and ) ; return and ;


signature:
public class WhereItems { /** * Adds an { @ literal SQL } { @ code OR } clause .
 * @ return the added { @ code OR } clause as { @ link WhereOr } object */
public WhereOr or ( ) { } }

implementation: final WhereOr or = new WhereOr ( builder ( ) ) ; items . add ( or ) ; return or ;


signature:
public class WhereItems { /** * Adds an { @ literal SQL } { @ code IN } predicate .
 * @ param expression
 * { @ literal SQL } expression , e . g . expression in
 * { @ code expression IN ( . . . ) } , actually the left part of the
 * predicate
 * @ param collection
 * collection of literal values
 * @ return this object */
public < V extends Object > WhereItems in ( final String expression , final Collection < V > collection ) { } }

implementation: items . add ( new WhereIn ( builder ( ) , expression , false , collection ) ) ; return this ;


signature:
public class WhereItems { /** * Adds an { @ literal SQL } { @ code IN } predicate .
 * @ param expression
 * { @ literal SQL } expression , e . g . expression in
 * { @ code expression IN ( . . . ) } , actually the left part of the
 * predicate
 * @ param array
 * array literal values
 * @ return this object */
public < V extends Object > WhereItems in ( final String expression , final V ... array ) { } }

implementation: items . add ( new WhereIn ( builder ( ) , expression , false , array ) ) ; return this ;


signature:
public class WhereItems { /** * Adds a { @ code NOT IN } predicate .
 * @ param expression
 * SQL expression , e . g . expression in
 * { @ code expression NOT IN ( . . . ) } , actually the left part of the
 * predicate
 * @ param collection
 * collection of literal values
 * @ return this object */
public < V extends Object > WhereItems notIn ( final String expression , final Collection < V > collection ) { } }

implementation: items . add ( new WhereIn ( builder ( ) , expression , true , collection ) ) ; return this ;


signature:
public class WhereItems { /** * Adds a " NOT IN " predicate .
 * @ param expression
 * SQL expression , e . g . " expression " of
 * " expression NOT IN ( . . . ) " , actually the left part of the
 * predicate
 * @ param array
 * array of literal values
 * @ return this object */
public < V extends Object > WhereItems notIn ( final String expression , final V ... array ) { } }

implementation: items . add ( new WhereIn ( builder ( ) , expression , true , array ) ) ; return this ;


signature:
public class WhereItems { /** * Adds a sub - query predicate .
 * @ param lhsPredicate
 * left hand side of the predicate , i . e . expression and operator ,
 * e . g . " field IN " or " EXISTS "
 * @ return the added subquery builder */
public QueryBuilder subquery ( final String lhsPredicate ) { } }

implementation: final WhereSubquery subquery = new WhereSubquery ( builder ( ) , lhsPredicate ) ; items . add ( subquery ) ; return subquery . getQueryBuilder ( ) ;


signature:
public class ReceiveToken2 { /** * { @ inheritDoc } . */
@ Override public boolean context ( ) { } }

implementation: int myid = getAgent ( ) . getId ( ) ; Token2 goal = ( Token2 ) getGoal ( ) ; return ( myid == goal . getAgent ( ) ) ;


signature:
public class MoveTower { /** * / * package */
void log ( ) { } }

implementation: Board board = ( ( Player ) getAgent ( ) ) . getBoard ( ) ; Player . out . println ( "Moving disc " + solve . disc + " from pin " + solve . src + " to " + solve . dest ) ; board . move ( solve . src , solve . dest ) ; Player . out . println ( board . toString ( ) ) ;


signature:
public class IntentionStacks { /** * Makes the next intentions stack active using a round robin scheme .
 * @ return the newly active stack . */
Stack255 nextActiveStack ( ) { } }

implementation: activeStack = ( activeStack + 1 ) % stacks . size ( ) ; return ( Stack255 ) stacks . get ( activeStack ) ;


signature:
public class IntentionStacks { /** * Returns an empty intentions stack .
 * Creates a new intentions stack and adds it to the list of stacks if needed .
 * @ return the newly created stack */
Stack255 getEmptyIntentionStack ( ) { } }

implementation:
// If the active stack is empty then return it ( don ' t check other stacks )
if ( ! stacks . isEmpty ( ) && getActiveStack ( ) . isEmpty ( ) ) { return getActiveStack ( ) ; } // else create an empty stack , add it to the list ot stacks , and return it
Stack255 stack = new Stack255 ( ( byte ) 8 , ( byte ) 2 ) ; stacks . push ( stack ) ; return stack ;


signature:
public class PlanBindings { /** * Add the set of bindings for a given plan to this store . Any previously stored bindings for this
 * plan will be replaced .
 * @ param plan the plan type
 * @ param planBindings the available bindings */
public void add ( Plan plan , Set < Belief > planBindings ) { } }

implementation:
if ( plan == null ) { return ; } // remove any old bindings , making sure to decrement the cached size
if ( this . bindings . containsKey ( plan ) ) { Set < Belief > oldBindings = this . bindings . remove ( plan ) ; if ( oldBindings == null || oldBindings . isEmpty ( ) ) { cachedsize -- ; } else { cachedsize -= oldBindings . size ( ) ; } } // add this binding and update the cached size
this . bindings . put ( plan , planBindings ) ; if ( planBindings == null || planBindings . isEmpty ( ) ) { cachedsize ++ ; } else { cachedsize += planBindings . size ( ) ; }


signature:
public class PlanBindings { /** * Selects a plan instance from the set of plan bindings , using the given policy .
 * @ param policy the policy to use for plan selection
 * @ return the selected plan , or { @ code null } if something went wrong */
public Plan selectPlan ( PlanSelectionPolicy policy ) { } }

implementation:
Plan plan = null ; int index = 0 ; switch ( policy ) { case FIRST : case LAST : Plan [ ] plans = bindings . keySet ( ) . toArray ( new Plan [ 0 ] ) ; plan = ( policy == PlanSelectionPolicy . FIRST ) ? plans [ 0 ] : plans [ plans . length - 1 ] ; index = ( policy == PlanSelectionPolicy . FIRST ) ? 0 : plans . length - 1 ; setPlanVariables ( plan . getAgent ( ) , plan , bindings . get ( plan ) , index ) ; break ; case RANDOM : plan = selectPlanAtRandom ( ) ; break ; default : // TODO : ignore remaining polic
break ; } return plan ;


signature:
public class PlanBindings { /** * Selects a plan instance at random from the set of plan bindings .
 * @ return a randomly selected plan instance , or null if ther are no bindings to choose from */
private Plan selectPlanAtRandom ( ) { } }

implementation: Plan plan = null ; Set < Belief > vars = null ; int index = rand . nextInt ( size ( ) ) ; int idx = 0 ; boolean bindingsExist = false ; for ( Plan p : bindings . keySet ( ) ) { vars = bindings . get ( p ) ; bindingsExist = ( vars != null && ! vars . isEmpty ( ) ) ; idx += bindingsExist ? vars . size ( ) : 1 ; if ( idx > index ) { plan = p ; if ( bindingsExist ) { index = index - ( idx - vars . size ( ) ) ; setPlanVariables ( plan . getAgent ( ) , plan , vars , index ) ; } break ; } } return plan ;


signature:
public class PlanBindings { /** * Sets the plan instance variables using the given results set .
 * @ param agent the agent for which this operation applies
 * @ param planInstance the plan instance that is to be populated
 * @ param results the beliefs set representing all plan bindings
 * @ param choice index of the belief that is to be used to populate the plan instance variables */
private final void setPlanVariables ( Agent agent , Plan planInstance , Set < Belief > results , int choice ) { } }

implementation: if ( agent == null || planInstance == null ) { return ; } Belief belief = getResultAtIndex ( results , choice ) ; if ( belief == null ) { return ; } Object [ ] tuple = belief . getTuple ( ) ; if ( tuple == null ) { return ; } int index = 0 ; HashMap < String , Object > vars = new HashMap < String , Object > ( ) ; for ( Object o : belief . getTuple ( ) ) { try { String fieldname = ABeliefStore . getFieldName ( agent . getId ( ) , belief . getBeliefset ( ) , index ) ; vars . put ( fieldname , o ) ; } catch ( BeliefBaseException e ) { Log . error ( "Agent " + agent . getId ( ) + " could not retrive belief set field: " + e . getMessage ( ) ) ; } index ++ ; } planInstance . setPlanVariables ( vars ) ;


signature:
public class PlanBindings { /** * Gets the result at the given index from the results set .
 * @ param results results set ( implementation must support predictable iteration order )
 * @ param index the index within the set { @ code ( 0 < index < results . size ( ) ) } to retrieve
 * @ return the result at the given index , or null if there was an error */
private Belief getResultAtIndex ( Set < Belief > results , int index ) { } }

implementation: Belief belief = null ; if ( ! ( results == null || index < 0 || index >= results . size ( ) ) ) { int idx = 0 ; for ( Belief b : results ) { if ( idx == index ) { belief = b ; break ; } idx ++ ; } } return belief ;


signature:
public class GoalPlanType { /** * Gets the parents of this object in the Goal - Plan tree .
 * @ return array of parent IDs , or null if this object has no parents */
public byte [ ] getParents ( ) { } }

implementation: if ( parents == null ) { return null ; } byte [ ] arr = new byte [ parents . length ] ; System . arraycopy ( parents , 0 , arr , 0 , arr . length ) ; return arr ;


signature:
public class GoalPlanType { /** * Gets all the children of this object in the Goal - Plan tree .
 * @ return array of children IDs , or null if this object has no children */
public byte [ ] getChildren ( ) { } }

implementation: if ( children == null ) { return null ; } byte [ ] arr = new byte [ children . length ] ; System . arraycopy ( children , 0 , arr , 0 , arr . length ) ; return arr ;


signature:
public class GoalPlanType { /** * Grows the given array by the given size .
 * @ param bytes the array to grow
 * @ param increment the size by which to grow it
 * @ return the new extended array with all the contents of the old array copied over */
public static byte [ ] grow ( byte [ ] bytes , int increment ) { } }

implementation: if ( bytes == null ) { return new byte [ 1 ] ; } byte [ ] temp = new byte [ bytes . length + increment ] ; System . arraycopy ( bytes , 0 , temp , 0 , bytes . length ) ; return temp ;