idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
3,100 | protected void start ( ) { final Runnable resilientTask = ( ) -> { try { run ( ) ; } catch ( final Exception e ) { logger . error ( "[{}] Error during timeout-initiated flush" , name , e ) ; } } ; scheduler . scheduleAtFixedRate ( resilientTask , 0 , batchTimeout + salt , TimeUnit . MILLISECONDS ) ; } | Starts the timer task . |
3,101 | public void destroy ( ) { logger . trace ( "{} - Destroy called on Batch" , name ) ; scheduler . shutdown ( ) ; try { if ( ! scheduler . awaitTermination ( maxAwaitTimeShutdown , TimeUnit . MILLISECONDS ) ) { logger . warn ( "Could not terminate batch within {}. Forcing shutdown." , DurationFormatUtils . formatDuration... | Destroys this batch . |
3,102 | public void flush ( ) { List < BatchEntry > temp ; bufferLock . lock ( ) ; try { lastFlush = System . currentTimeMillis ( ) ; if ( batch == batchSize ) { logger . trace ( "[{}] Batch empty, not flushing" , name ) ; return ; } batch = batchSize ; temp = buffer ; buffer = new LinkedList < > ( ) ; } finally { bufferLock .... | Flushes the pending batches . |
3,103 | public final void merge ( final Properties properties ) { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { setProperty ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } } | Merges properties with the existing ones . |
3,104 | public int getIsolationLevel ( ) { final Optional < IsolationLevel > e = Enums . getIfPresent ( IsolationLevel . class , getProperty ( ISOLATION_LEVEL ) . toUpperCase ( ) ) ; if ( ! e . isPresent ( ) ) { throw new DatabaseEngineRuntimeException ( ISOLATION_LEVEL + " must be set and be one of the following: " + EnumSet ... | Gets the isolation level . |
3,105 | public void checkMandatoryProperties ( ) throws PdbConfigurationException { StringBuilder exceptionMessage = new StringBuilder ( ) ; if ( StringUtils . isBlank ( getJdbc ( ) ) ) { exceptionMessage . append ( "- A connection string should be declared under the 'database.jdbc' property.\n" ) ; } if ( StringUtils . isBlan... | Checks if the configuration validates for mandatory properties . |
3,106 | private String reorg ( String tableName ) { List < String > statement = new ArrayList < > ( ) ; statement . add ( "CALL sysproc.admin_cmd('REORG TABLE" ) ; statement . add ( quotize ( tableName ) ) ; statement . add ( "')" ) ; return join ( statement , " " ) ; } | Reorganizes the table so it doesn t contain fragments . |
3,107 | private String alterColumnSetNotNull ( String tableName , List < String > columnNames ) { List < String > statement = new ArrayList < > ( ) ; statement . add ( "ALTER TABLE" ) ; statement . add ( quotize ( tableName ) ) ; for ( String columnName : columnNames ) { statement . add ( "ALTER COLUMN" ) ; statement . add ( q... | Generates a command to set the specified columns to enforce non nullability . |
3,108 | public static String md5 ( final String message ) { byte [ ] res ; try { MessageDigest instance = MessageDigest . getInstance ( "MD5" ) ; instance . reset ( ) ; instance . update ( message . getBytes ( ) ) ; res = instance . digest ( ) ; } catch ( final NoSuchAlgorithmException ex ) { throw new RuntimeException ( ex ) ... | Generates the MD5 checksum for the specified message . |
3,109 | public static String md5 ( final String message , final int nchar ) { final String hash = md5 ( message ) ; return nchar > hash . length ( ) ? hash : hash . substring ( 0 , nchar ) ; } | Generates de MD5 checksum for the specified message . |
3,110 | public static String readString ( final InputStream stream ) throws IOException { InputStreamReader br = null ; StringBuilder sb = new StringBuilder ( ) ; try { br = new InputStreamReader ( stream ) ; int got ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { got = br . read ( ) ; if ( got == - 1 ) { break ... | Reads a string from the input stream . |
3,111 | protected Object processObject ( Object o ) { if ( o instanceof PGobject && ( ( PGobject ) o ) . getType ( ) . equals ( "jsonb" ) ) { return ( ( PGobject ) o ) . getValue ( ) ; } return super . processObject ( o ) ; } | Overrides default behaviour for JSON values that are converted to strings . |
3,112 | public static DatabaseEngine getConnection ( Properties p ) throws DatabaseFactoryException { PdbProperties pdbProperties = new PdbProperties ( p , true ) ; final String engine = pdbProperties . getEngine ( ) ; if ( StringUtils . isBlank ( engine ) ) { throw new DatabaseFactoryException ( "pdb.engine property is mandat... | Gets a database connection from the specified properties . |
3,113 | public static Case caseWhen ( final Expression condition , final Expression trueAction ) { return Case . caseWhen ( condition , trueAction ) ; } | Creates a case expression . |
3,114 | public static Expression in ( final Expression e1 , final Expression e2 ) { return new RepeatDelimiter ( IN , e1 . isEnclosed ( ) ? e1 : e1 . enclose ( ) , e2 . isEnclosed ( ) ? e2 : e2 . enclose ( ) ) ; } | The IN expression . |
3,115 | public static Expression notIn ( final Expression e1 , final Expression e2 ) { return new RepeatDelimiter ( NOTIN , e1 . isEnclosed ( ) ? e1 : e1 . enclose ( ) , e2 . isEnclosed ( ) ? e2 : e2 . enclose ( ) ) ; } | The NOT IN expression . |
3,116 | public static Between between ( final Expression exp1 , final Expression exp2 , final Expression exp3 ) { return new Between ( exp1 , and ( exp2 , exp3 ) ) ; } | The BETWEEN operator . |
3,117 | public static Between notBetween ( final Expression exp1 , final Expression exp2 , final Expression exp3 ) { return new Between ( exp1 , and ( exp2 , exp3 ) ) . not ( ) ; } | The NOT BETWEEN operator . |
3,118 | public static AlterColumn alterColumn ( Expression table , Name column , DbColumnType dbColumnType , DbColumnConstraint ... constraints ) { return alterColumn ( table , dbColumn ( ) . name ( column . getName ( ) ) . type ( dbColumnType ) . addConstraints ( constraints ) . build ( ) ) ; } | Alter column operator . |
3,119 | public static DbColumn . Builder dbColumn ( String name , DbColumnType type , boolean autoInc ) { return new DbColumn . Builder ( ) . name ( name ) . type ( type ) . autoInc ( autoInc ) ; } | Creates a Database Column builder . |
3,120 | public With andWith ( final String alias , final Expression expression ) { this . clauses . add ( new ImmutablePair < > ( new Name ( alias ) , expression ) ) ; return this ; } | Adds an alias and expression to the with clause . |
3,121 | private void setAnsiMode ( ) throws SQLException { Statement s = conn . createStatement ( ) ; s . executeUpdate ( "SET sql_mode = 'ansi'" ) ; s . close ( ) ; } | Sets the session to ANSI mode . |
3,122 | public boolean containsColumn ( String columnName ) { return columns . stream ( ) . map ( DbColumn :: getName ) . anyMatch ( listColName -> listColName . equals ( columnName ) ) ; } | Checks if the given column is present in the list of columns . |
3,123 | public Builder newBuilder ( ) { return new Builder ( ) . name ( name ) . addColumn ( columns ) . addFk ( fks ) . pkFields ( pkFields ) . addIndexes ( indexes ) ; } | Returns a new builder out of the configuration . |
3,124 | public Case when ( final Expression condition , final Expression action ) { whens . add ( When . when ( condition , action ) ) ; return this ; } | Adds a new when clause to this case . |
3,125 | private Object getJSONValue ( String val ) throws DatabaseEngineException { try { PGobject dataObject = new PGobject ( ) ; dataObject . setType ( "jsonb" ) ; dataObject . setValue ( val ) ; return dataObject ; } catch ( final SQLException ex ) { throw new DatabaseEngineException ( "Error while mapping variables to data... | Converts a String value into a PG JSON value ready to be assigned to bind variables in Prepared Statements . |
3,126 | public Expression leftOuterJoin ( final Expression table , final Expression expr ) { if ( table instanceof Query ) { table . enclose ( ) ; } joins . add ( new Join ( "LEFT OUTER JOIN" , table , expr ) ) ; return this ; } | Sets a left outer join with the current table . |
3,127 | public Builder newBuilder ( ) { return new Builder ( ) . name ( name ) . type ( dbColumnType ) . size ( size ) . addConstraints ( columnConstraints ) . autoInc ( autoInc ) . defaultValue ( defaultValue ) ; } | Returns a new builder out of this configuration . |
3,128 | protected String getPrivateKey ( ) throws Exception { String location = this . properties . getProperty ( SECRET_LOCATION ) ; if ( StringUtils . isBlank ( location ) ) { throw new DatabaseEngineException ( "Encryption was specified but there's no location specified for the private key." ) ; } File f = new File ( locati... | Reads the private key from the secret location . |
3,129 | public synchronized void close ( ) { try { for ( final PreparedStatementCapsule preparedStatement : stmts . values ( ) ) { try { preparedStatement . ps . close ( ) ; } catch ( final SQLException e ) { logger . warn ( "Could not close statement." , e ) ; } } stmts . clear ( ) ; entities . forEach ( ( key , mappedEntity ... | Closes the connection to the database . |
3,130 | private void addEntity ( DbEntity entity , boolean recovering ) throws DatabaseEngineException { if ( ! recovering ) { try { getConnection ( ) ; } catch ( final Exception e ) { throw new DatabaseEngineException ( "Could not add entity" , e ) ; } validateEntity ( entity ) ; if ( entities . containsKey ( entity . getName... | Adds an entity to the engine . It will create tables and everything necessary so persistence can work . |
3,131 | public synchronized void dropEntity ( String entity ) throws DatabaseEngineException { if ( ! containsEntity ( entity ) ) { return ; } dropEntity ( entities . get ( entity ) . getEntity ( ) ) ; } | Drops an entity . |
3,132 | public synchronized void dropEntity ( final DbEntity entity ) throws DatabaseEngineException { dropSequences ( entity ) ; dropTable ( entity ) ; entities . remove ( entity . getName ( ) ) ; logger . trace ( "Entity {} dropped" , entity . getName ( ) ) ; } | Drops everything that belongs to the entity . |
3,133 | private void dropAllEntities ( ) { for ( final MappedEntity mappedEntity : ImmutableList . copyOf ( entities . values ( ) ) ) { try { dropEntity ( mappedEntity . getEntity ( ) ) ; } catch ( final DatabaseEngineException ex ) { logger . debug ( String . format ( "Failed to drop entity '%s'" , mappedEntity . getEntity ( ... | Drops all entities associated with this engine . |
3,134 | public synchronized void flush ( ) throws DatabaseEngineException { try { for ( MappedEntity me : entities . values ( ) ) { me . getInsert ( ) . executeBatch ( ) ; } } catch ( final Exception ex ) { throw new DatabaseEngineException ( "Something went wrong while flushing" , ex ) ; } } | Flushes the batches for all the registered entities . |
3,135 | public synchronized int executeUpdate ( final String query ) throws DatabaseEngineException { Statement s = null ; try { getConnection ( ) ; s = conn . createStatement ( ) ; return s . executeUpdate ( query ) ; } catch ( final Exception ex ) { throw new DatabaseEngineException ( "Error handling native query" , ex ) ; }... | Executes a native query . |
3,136 | public synchronized int executeUpdate ( final Expression query ) throws DatabaseEngineException { final String trans = translate ( query ) ; logger . trace ( trans ) ; return executeUpdate ( trans ) ; } | Executes the given update . |
3,137 | public synchronized boolean checkConnection ( final boolean forceReconnect ) { if ( checkConnection ( conn ) ) { return true ; } else if ( forceReconnect ) { try { connect ( ) ; recover ( ) ; return true ; } catch ( final Exception ex ) { logger . debug ( dev , "reconnection failure" , ex ) ; return false ; } } return ... | Checks if the connection is alive . |
3,138 | public synchronized void addBatch ( final String name , final EntityEntry entry ) throws DatabaseEngineException { try { final MappedEntity me = entities . get ( name ) ; if ( me == null ) { throw new DatabaseEngineException ( String . format ( "Unknown entity '%s'" , name ) ) ; } PreparedStatement ps = me . getInsert ... | Add an entry to the batch . |
3,139 | public synchronized DatabaseEngine duplicate ( Properties mergeProperties , final boolean copyEntities ) throws DuplicateEngineException { if ( mergeProperties == null ) { mergeProperties = new Properties ( ) ; } final PdbProperties niwProps = properties . clone ( ) ; niwProps . merge ( mergeProperties ) ; if ( ! ( niw... | Duplicates a connection . |
3,140 | public synchronized List < Map < String , ResultColumn > > getPSResultSet ( final String name ) throws DatabaseEngineException { return processResultIterator ( getPSIterator ( name ) ) ; } | Gets the result set of the specified prepared statement . |
3,141 | public synchronized void executePS ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name ) ) ; } tr... | Executes the specified prepared statement . |
3,142 | public synchronized void clearParameters ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name ) ) ... | Clears the prepared statement parameters . |
3,143 | public synchronized Integer executePSUpdate ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name )... | Executes update on the specified prepared statement . |
3,144 | private void createPreparedStatement ( final String name , final String query , final int timeout , final boolean recovering ) throws NameAlreadyExistsException , DatabaseEngineException { if ( ! recovering ) { if ( stmts . containsKey ( name ) ) { throw new NameAlreadyExistsException ( String . format ( "There's alrea... | Creates a prepared statement . |
3,145 | protected final synchronized byte [ ] objectToArray ( Object val ) throws IOException { final ByteArrayOutputStream bos = new InitiallyReusableByteArrayOutputStream ( getReusableByteBuffer ( ) ) ; final ObjectOutputStream oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( val ) ; return bos . toByteArray ( ) ; ... | Converts an object to byte array . |
3,146 | public boolean hasIdentityColumn ( DbEntity entity ) { for ( final DbColumn column : entity . getColumns ( ) ) { if ( column . isAutoInc ( ) ) { return true ; } } return false ; } | Check if the entity has an identity column . |
3,147 | public static Properties getPropertiesFromClasspath ( String fileName ) throws PropertiesFileNotFoundException { Properties props = new Properties ( ) ; try { InputStream is = ClassLoader . getSystemResourceAsStream ( fileName ) ; if ( is == null ) { is = Thread . currentThread ( ) . getContextClassLoader ( ) . getReso... | Loads a Properties file from the classpath matching the given file name |
3,148 | public static Properties getPropertiesFromPath ( String fileName ) throws PropertiesFileNotFoundException { Properties props = new Properties ( ) ; FileInputStream fis ; try { fis = new FileInputStream ( fileName ) ; props . load ( fis ) ; fis . close ( ) ; } catch ( Exception e ) { throw new PropertiesFileNotFoundExce... | Loads a Properties file from the given file name |
3,149 | public static int execute ( String sql , Object [ ] params ) throws YankSQLException { return execute ( YankPoolManager . DEFAULT_POOL_NAME , sql , params ) ; } | Executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL prepared statement . Returns the number of rows affected using the default connection pool . |
3,150 | public static int execute ( String poolName , String sql , Object [ ] params ) throws YankSQLException { int returnInt = 0 ; try { returnInt = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . update ( sql , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } ret... | Executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL prepared statement . Returns the number of rows affected . |
3,151 | public static < T > T queryScalar ( String sql , Class < T > scalarType , Object [ ] params ) throws SQLStatementNotFoundException , YankSQLException { return queryScalar ( YankPoolManager . DEFAULT_POOL_NAME , sql , scalarType , params ) ; } | Return just one scalar given a an SQL statement using the default connection pool . |
3,152 | public static < T > T queryScalar ( String poolName , String sql , Class < T > scalarType , Object [ ] params ) throws SQLStatementNotFoundException , YankSQLException { T returnObject = null ; try { ScalarHandler < T > resultSetHandler ; if ( scalarType . equals ( Integer . class ) ) { resultSetHandler = ( ScalarHandl... | Return just one scalar given a an SQL statement |
3,153 | public static < T > T queryBean ( String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { return queryBean ( YankPoolManager . DEFAULT_POOL_NAME , sql , beanType , params ) ; } | Return just one Bean given an SQL statement . If more than one row match the query only the first row is returned using the default connection pool . |
3,154 | public static < T > T queryBean ( String poolName , String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { T returnObject = null ; try { BeanHandler < T > resultSetHandler = new BeanHandler < T > ( beanType , new BasicRowProcessor ( new YankBeanProcessor < T > ( beanType ) ) ) ; returnObject ... | Return just one Bean given an SQL statement . If more than one row match the query only the first row is returned . |
3,155 | public static < T > List < T > queryBeanList ( String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { return queryBeanList ( YankPoolManager . DEFAULT_POOL_NAME , sql , beanType , params ) ; } | Return a List of Beans given an SQL statement using the default connection pool . |
3,156 | public static < T > List < T > queryBeanList ( String poolName , String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { List < T > returnList = null ; try { BeanListHandler < T > resultSetHandler = new BeanListHandler < T > ( beanType , new BasicRowProcessor ( new YankBeanProcessor < T > ( be... | Return a List of Beans given an SQL statement |
3,157 | public static < T > List < T > queryColumn ( String sql , String columnName , Class < T > columnType , Object [ ] params ) throws YankSQLException { return queryColumn ( YankPoolManager . DEFAULT_POOL_NAME , sql , columnName , columnType , params ) ; } | Return a List of Objects from a single table column given an SQL statement using the default connection pool . |
3,158 | public static < T > List < T > queryColumn ( String poolName , String sql , String columnName , Class < T > columnType , Object [ ] params ) throws YankSQLException { List < T > returnList = null ; try { ColumnListHandler < T > resultSetHandler ; if ( columnType . equals ( Integer . class ) ) { resultSetHandler = ( Col... | Return a List of Objects from a single table column given an SQL statement |
3,159 | public static int [ ] executeBatch ( String sql , Object [ ] [ ] params ) throws YankSQLException { return executeBatch ( YankPoolManager . DEFAULT_POOL_NAME , sql , params ) ; } | Batch executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL statement using the default connection pool . |
3,160 | public static int [ ] executeBatch ( String poolName , String sql , Object [ ] [ ] params ) throws YankSQLException { int [ ] returnIntArray = null ; try { returnIntArray = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . batch ( sql , params ) ; } catch ( SQLException e ) { handleSQLException (... | Batch executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL statement |
3,161 | private static void handleSQLException ( SQLException e , String poolName , String sql ) { YankSQLException yankSQLException = new YankSQLException ( e , poolName , sql ) ; if ( throwWrappedExceptions ) { throw yankSQLException ; } else { logger . error ( yankSQLException . getMessage ( ) , yankSQLException ) ; } } | Handles exceptions and logs them |
3,162 | private void createPool ( String poolName , Properties connectionPoolProperties ) { releaseConnectionPool ( poolName ) ; connectionPoolProperties . put ( "autoCommit" , true ) ; HikariConfig config = new HikariConfig ( connectionPoolProperties ) ; config . setPoolName ( poolName ) ; HikariDataSource ds = new HikariData... | Creates a Hikari connection pool and puts it in the pools map . |
3,163 | protected synchronized void releaseConnectionPool ( String poolName ) { HikariDataSource pool = pools . get ( poolName ) ; if ( pool != null ) { logger . info ( "Releasing pool: {}..." , pool . getPoolName ( ) ) ; pool . close ( ) ; } } | Closes a connection pool |
3,164 | protected synchronized void releaseAllConnectionPools ( ) { for ( HikariDataSource pool : pools . values ( ) ) { if ( pool != null ) { logger . info ( "Releasing pool: {}..." , pool . getPoolName ( ) ) ; pool . close ( ) ; } } } | Closes all connection pools |
3,165 | public int compareTo ( DetectedLanguage o ) { int compare = Double . compare ( o . probability , this . probability ) ; if ( compare != 0 ) return compare ; return this . locale . toString ( ) . compareTo ( o . locale . toString ( ) ) ; } | See class header . |
3,166 | public static void main ( String [ ] args ) throws IOException { CommandLineInterface cli = new CommandLineInterface ( ) ; cli . addOpt ( "-d" , "directory" , "./" ) ; cli . addOpt ( "-a" , "alpha" , "" + DEFAULT_ALPHA ) ; cli . addOpt ( "-s" , "seed" , null ) ; cli . parse ( args ) ; if ( cli . hasParam ( "--genprofil... | Command Line Interface |
3,167 | private void parse ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( opt_with_value . containsKey ( args [ i ] ) ) { String key = opt_with_value . get ( args [ i ] ) ; values . put ( key , args [ i + 1 ] ) ; i ++ ; } else if ( args [ i ] . startsWith ( "-" ) ) { opt_without_value . add ( args [ ... | Command line easy parser |
3,168 | private double getParamDouble ( String key , double defaultValue ) { String value = values . get ( key ) ; if ( value == null || value . isEmpty ( ) ) { return defaultValue ; } try { return Double . valueOf ( value ) ; } catch ( NumberFormatException e ) { throw new RuntimeException ( "Invalid double value: >>>" + valu... | Returns the double or the default is absent . Throws if the double is specified but invalid . |
3,169 | public void generateProfile ( ) { File directory = new File ( arglist . get ( 0 ) ) ; String lang = arglist . get ( 1 ) ; File file = searchFile ( directory , lang + "wiki-.*-abstract\\.xml.*" ) ; if ( file == null ) { System . err . println ( "Not Found text file : lang = " + lang ) ; return ; } try ( FileOutputStream... | Generate Language Profile from a text file . |
3,170 | private LanguageDetector makeDetector ( ) throws IOException { double alpha = getParamDouble ( "alpha" , DEFAULT_ALPHA ) ; String profileDirectory = requireParamString ( "directory" ) + "/" ; Optional < Long > seed = Optional . fromNullable ( getParamLongOrNull ( "seed" ) ) ; List < LanguageProfile > languageProfiles =... | Using all language profiles from the given directory . |
3,171 | public static LangProfile load ( String lang , File file ) { LangProfile profile = new LangProfile ( lang ) ; try ( InputStream is = file . getName ( ) . endsWith ( ".gz" ) ? new GZIPInputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) ) : new BufferedInputStream ( new FileInputStream ( file ) ) ) { T... | Load Wikipedia abstract database file and generate its language profile |
3,172 | private double [ ] detectBlockLongText ( List < String > ngrams ) { assert ! ngrams . isEmpty ( ) ; double [ ] langprob = new double [ ngramFrequencyData . getLanguageList ( ) . size ( ) ] ; Random rand = new Random ( seed . or ( DEFAULT_SEED ) ) ; for ( int t = 0 ; t < N_TRIAL ; ++ t ) { double [ ] prob = initProbabil... | This is the original algorithm used for all text length . It is inappropriate for short text . |
3,173 | public static double normalizeProb ( double [ ] prob ) { double maxp = 0 , sump = 0 ; for ( int i = 0 ; i < prob . length ; ++ i ) sump += prob [ i ] ; for ( int i = 0 ; i < prob . length ; ++ i ) { double p = prob [ i ] / sump ; if ( maxp < p ) maxp = p ; prob [ i ] = p ; } return maxp ; } | normalize probabilities and check convergence by the maximum probability |
3,174 | public double validate ( ) { this . removeLanguageProfile ( this . languageProfileBuilder . build ( ) . getLocale ( ) . getLanguage ( ) ) ; List < TextObject > partitionedInput = partition ( ) ; List < Double > probabilities = new ArrayList < > ( this . k ) ; System . out . println ( "------------------- Running " + th... | Run the n - fold validation . |
3,175 | public LanguageProfileBuilder addGram ( String ngram , int frequency ) { Map < String , Integer > map = ngrams . get ( ngram . length ( ) ) ; if ( map == null ) { map = new HashMap < > ( ) ; ngrams . put ( ngram . length ( ) , map ) ; } Integer total = map . get ( ngram ) ; if ( total == null ) total = 0 ; total += fre... | If the builder already has this ngram the given frequency is added to the current count . |
3,176 | public List < LanguageProfile > read ( ClassLoader classLoader , String profileDirectory , Collection < String > profileFileNames ) throws IOException { List < LanguageProfile > loaded = new ArrayList < > ( profileFileNames . size ( ) ) ; for ( String profileFileName : profileFileNames ) { String path = makePathForClas... | Load profiles from the classpath in a specific directory . |
3,177 | public List < LanguageProfile > readAll ( File path ) throws IOException { if ( ! path . exists ( ) ) { throw new IOException ( "No such folder: " + path ) ; } if ( ! path . canRead ( ) ) { throw new IOException ( "Folder not readable: " + path ) ; } File [ ] listFiles = path . listFiles ( new FileFilter ( ) { public b... | Loads all profiles from the specified directory . |
3,178 | public TextObject append ( Reader reader ) throws IOException { char [ ] buf = new char [ 1024 ] ; while ( reader . ready ( ) && ( maxTextLength == 0 || stringBuilder . length ( ) < maxTextLength ) ) { int length = reader . read ( buf ) ; append ( String . valueOf ( buf , 0 , length ) ) ; } return this ; } | Append the target text for language detection . This method read the text from specified input reader . If the total size of target text exceeds the limit size the rest is ignored . |
3,179 | public TextObject append ( CharSequence text ) { if ( maxTextLength > 0 && stringBuilder . length ( ) >= maxTextLength ) return this ; text = textFilter . filter ( text ) ; char pre = stringBuilder . length ( ) == 0 ? 0 : stringBuilder . charAt ( stringBuilder . length ( ) - 1 ) ; for ( int i = 0 ; i < text . length ( ... | Append the target text for language detection . If the total size of target text exceeds the limit size the rest is cut down . |
3,180 | public void omitLessFreq ( ) { if ( name == null ) throw new IllegalStateException ( ) ; int threshold = nWords [ 0 ] / LESS_FREQ_RATIO ; if ( threshold < MINIMUM_FREQ ) threshold = MINIMUM_FREQ ; Set < String > keys = freq . keySet ( ) ; int roman = 0 ; for ( Iterator < String > i = keys . iterator ( ) ; i . hasNext (... | Removes ngrams that occur fewer times than MINIMUM_FREQ to get rid of rare ngrams . |
3,181 | public static LangProfile generate ( String lang , File textFile ) { LangProfile profile = new LangProfile ( lang ) ; InputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( textFile ) ) ; if ( textFile . getName ( ) . endsWith ( ".gz" ) ) is = new GZIPInputStream ( is ) ; BufferedReader read... | Loads a text file and generate a language profile from its content . The input text file is supposed to be encoded in UTF - 8 . |
3,182 | public String format ( LoggingEvent event ) { JsonObject jsonEvent = new JsonObject ( ) ; jsonEvent . addProperty ( "v" , 0 ) ; jsonEvent . addProperty ( "level" , BUNYAN_LEVEL . get ( event . getLevel ( ) ) ) ; jsonEvent . addProperty ( "name" , event . getLoggerName ( ) ) ; try { jsonEvent . addProperty ( "hostname" ... | Format the event as a Banyan style JSON object . |
3,183 | private String format ( LogEvent event ) { JsonObject jsonEvent = new JsonObject ( ) ; jsonEvent . addProperty ( "v" , 0 ) ; jsonEvent . addProperty ( "level" , BUNYAN_LEVEL . get ( event . getLevel ( ) ) ) ; jsonEvent . addProperty ( "levelStr" , event . getLevel ( ) . toString ( ) ) ; jsonEvent . addProperty ( "name"... | Format the event as a Bunyan style JSON object . |
3,184 | public final String getStringDefault ( String defaultValue , String attribute , String ... path ) { return getNodeStringDefault ( defaultValue , attribute , path ) ; } | Get a string in the xml tree . |
3,185 | public final boolean hasNode ( String ... path ) { Xml node = root ; for ( final String element : path ) { if ( ! node . hasChild ( element ) ) { return false ; } node = node . getChild ( element ) ; } return true ; } | Check if node exists . |
3,186 | private static Circuit getCircuitGroups ( String group , Collection < String > neighborGroups ) { final Collection < String > set = new HashSet < > ( neighborGroups ) ; final Circuit circuit ; if ( set . size ( ) > 1 ) { final Iterator < String > iterator = set . iterator ( ) ; final String groupIn = iterator . next ( ... | Get the tile circuit between two groups . |
3,187 | private static CircuitType getCircuitType ( String groupIn , Collection < String > neighborGroups ) { final boolean [ ] bits = new boolean [ CircuitType . BITS ] ; int i = CircuitType . BITS - 1 ; for ( final String neighborGroup : neighborGroups ) { bits [ i ] = groupIn . equals ( neighborGroup ) ; i -- ; } return Cir... | Get the circuit type from one group to another . |
3,188 | public Circuit getCircuit ( Tile tile ) { final Collection < String > neighborGroups = getNeighborGroups ( tile ) ; final Collection < String > groups = new HashSet < > ( neighborGroups ) ; final String group = mapGroup . getGroup ( tile ) ; final Circuit circuit ; if ( groups . size ( ) == 1 ) { if ( group . equals ( ... | Get the tile circuit . |
3,189 | public static BackgroundElement createElement ( String name , int x , int y ) { return new BackgroundElement ( x , y , createSprite ( Medias . create ( name ) ) ) ; } | Create an element from a name plus its coordinates . |
3,190 | protected static Sprite createSprite ( Media media ) { final Sprite sprite = Drawable . loadSprite ( media ) ; sprite . load ( ) ; sprite . prepare ( ) ; return sprite ; } | Create a sprite from its filename . |
3,191 | private static boolean containsCollisionFormula ( TileCollision tile , CollisionCategory category ) { final Collection < CollisionFormula > formulas = tile . getCollisionFormulas ( ) ; for ( final CollisionFormula formula : category . getFormulas ( ) ) { if ( formulas . contains ( formula ) ) { return true ; } } return... | Check if tile contains at least one collision from the category . |
3,192 | private static Double getCollisionX ( CollisionCategory category , TileCollision tileCollision , double x , double y ) { if ( Axis . X == category . getAxis ( ) ) { return tileCollision . getCollisionX ( category , x , y ) ; } return null ; } | Get the horizontal collision from current location . |
3,193 | private static Double getCollisionY ( CollisionCategory category , TileCollision tileCollision , double x , double y ) { if ( Axis . Y == category . getAxis ( ) ) { return tileCollision . getCollisionY ( category , x , y ) ; } return null ; } | Get the vertical collision from current location . |
3,194 | public CollisionResult computeCollision ( Transformable transformable , CollisionCategory category ) { final double sh = transformable . getOldX ( ) + category . getOffsetX ( ) ; final double sv = transformable . getOldY ( ) + category . getOffsetY ( ) ; final double dh = transformable . getX ( ) + category . getOffset... | Search first tile hit by the transformable that contains collision applying a ray tracing from its old location to its current . This way the transformable can not pass through a collidable tile . |
3,195 | private CollisionResult computeCollision ( CollisionCategory category , double ox , double oy , double x , double y ) { final Tile tile = map . getTileAt ( getPositionToSide ( ox , x ) , getPositionToSide ( oy , y ) ) ; if ( tile != null ) { final TileCollision tileCollision = tile . getFeature ( TileCollision . class ... | Compute the collision from current location . |
3,196 | private ColorRgba getTileColor ( Tile tile ) { final ColorRgba color ; if ( tile == null ) { color = NO_TILE ; } else { final TileRef ref = new TileRef ( tile . getSheet ( ) , tile . getNumber ( ) ) ; if ( ! pixels . containsKey ( ref ) ) { color = DEFAULT_COLOR ; } else { color = pixels . get ( ref ) ; } } return colo... | Get the corresponding tile color . |
3,197 | private void computeSheet ( Map < TileRef , ColorRgba > colors , Integer sheet ) { final SpriteTiled tiles = map . getSheet ( sheet ) ; final ImageBuffer tilesSurface = tiles . getSurface ( ) ; final int tw = map . getTileWidth ( ) ; final int th = map . getTileHeight ( ) ; int number = 0 ; for ( int i = 0 ; i < tilesS... | Compute the current sheet . |
3,198 | public void load ( ) { if ( surface == null ) { surface = Graphics . createImageBuffer ( map . getInTileWidth ( ) , map . getInTileHeight ( ) , ColorRgba . TRANSPARENT ) ; } } | Load minimap surface from map tile size . Does nothing if already loaded . |
3,199 | public void prepare ( ) { if ( surface == null ) { throw new LionEngineException ( ERROR_SURFACE ) ; } final Graphic g = surface . createGraphic ( ) ; final int v = map . getInTileHeight ( ) ; final int h = map . getInTileWidth ( ) ; for ( int ty = 0 ; ty < v ; ty ++ ) { for ( int tx = 0 ; tx < h ; tx ++ ) { final Tile... | Fill minimap surface with tile color configuration . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.