idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
29,800 | public final Command createVerbosityCommand ( CountDownLatch latch , int level , boolean noreply ) { return new TextVerbosityCommand ( latch , level , noreply ) ; } | Create verbosity command | 42 | 4 |
29,801 | protected final int blockingRead ( ) throws ClosedChannelException , IOException { int n = 0 ; int readCount = 0 ; Selector readSelector = SelectorFactory . getSelector ( ) ; SelectionKey tmpKey = null ; try { if ( this . selectableChannel . isOpen ( ) ) { tmpKey = this . selectableChannel . register ( readSelector , 0 ) ; tmpKey . interestOps ( tmpKey . interestOps ( ) | SelectionKey . OP_READ ) ; int code = readSelector . select ( 500 ) ; tmpKey . interestOps ( tmpKey . interestOps ( ) & ~ SelectionKey . OP_READ ) ; if ( code > 0 ) { do { n = ( ( ReadableByteChannel ) this . selectableChannel ) . read ( this . readBuffer . buf ( ) ) ; readCount += n ; if ( log . isDebugEnabled ( ) ) { log . debug ( "use temp selector read " + n + " bytes" ) ; } } while ( n > 0 && this . readBuffer . hasRemaining ( ) ) ; if ( readCount > 0 ) { decodeAndDispatch ( ) ; } } } } finally { if ( tmpKey != null ) { tmpKey . cancel ( ) ; tmpKey = null ; } if ( readSelector != null ) { // Cancel the key. readSelector . selectNow ( ) ; SelectorFactory . returnSelector ( readSelector ) ; } } return readCount ; } | Blocking read using temp selector | 315 | 6 |
29,802 | protected byte [ ] encodeString ( String in ) { byte [ ] rv = null ; try { rv = in . getBytes ( this . charset ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return rv ; } | Encode a string into the current character set . | 60 | 10 |
29,803 | @ SuppressWarnings ( "unchecked" ) public final Command optimiezeMergeBuffer ( Command optimiezeCommand , final Queue writeQueue , final Queue < Command > executingCmds , int sendBufferSize ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Optimieze merge buffer:" + optimiezeCommand . toString ( ) ) ; } if ( this . optimiezeMergeBuffer && optimiezeCommand . getIoBuffer ( ) . remaining ( ) < sendBufferSize - 24 ) { optimiezeCommand = this . mergeBuffer ( optimiezeCommand , writeQueue , executingCmds , sendBufferSize ) ; } return optimiezeCommand ; } | merge buffers to fit socket s send buffer size | 155 | 10 |
29,804 | @ SuppressWarnings ( "unchecked" ) public final Command optimiezeGet ( final Queue writeQueue , final Queue < Command > executingCmds , Command optimiezeCommand ) { if ( optimiezeCommand . getCommandType ( ) == CommandType . GET_ONE || optimiezeCommand . getCommandType ( ) == CommandType . GETS_ONE ) { if ( this . optimiezeGet ) { optimiezeCommand = this . mergeGetCommands ( optimiezeCommand , writeQueue , executingCmds , optimiezeCommand . getCommandType ( ) ) ; } } return optimiezeCommand ; } | Merge get operation to multi - get operation | 138 | 9 |
29,805 | public static AuthInfo plain ( String username , String password ) { return new AuthInfo ( new PlainCallbackHandler ( username , password ) , new String [ ] { "PLAIN" } ) ; } | Get a typical auth descriptor for PLAIN auth with the given username and password . | 41 | 16 |
29,806 | public static AuthInfo cramMD5 ( String username , String password ) { return new AuthInfo ( new PlainCallbackHandler ( username , password ) , new String [ ] { "CRAM-MD5" } ) ; } | Get a typical auth descriptor for CRAM - MD5 auth with the given username and password . | 46 | 19 |
29,807 | @ Override public AWSElasticCacheClient build ( ) throws IOException { AWSElasticCacheClient memcachedClient = new AWSElasticCacheClient ( this . sessionLocator , this . sessionComparator , this . bufferAllocator , this . configuration , this . socketOptions , this . commandFactory , this . transcoder , this . stateListeners , this . authInfoMap , this . connectionPoolSize , this . connectTimeout , this . name , this . failureMode , configAddrs , this . pollConfigIntervalMs ) ; this . configureClient ( memcachedClient ) ; return memcachedClient ; } | Returns a new instanceof AWSElasticCacheClient . | 137 | 12 |
29,808 | public static URL getResourceURL ( String resource ) throws IOException { URL url = null ; ClassLoader loader = ResourcesUtils . class . getClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( resource ) ; } if ( url == null ) { url = ClassLoader . getSystemResource ( resource ) ; } if ( url == null ) { throw new IOException ( "Could not find resource " + resource ) ; } return url ; } | Returns the URL of the resource on the classpath | 100 | 10 |
29,809 | public static InputStream getResourceAsStream ( String resource ) throws IOException { InputStream in = null ; ClassLoader loader = ResourcesUtils . class . getClassLoader ( ) ; if ( loader != null ) { in = loader . getResourceAsStream ( resource ) ; } if ( in == null ) { in = ClassLoader . getSystemResourceAsStream ( resource ) ; } if ( in == null ) { throw new IOException ( "Could not find resource " + resource ) ; } return in ; } | Returns a resource on the classpath as a Stream object | 107 | 11 |
29,810 | protected void initialSelectorManager ( ) throws IOException { if ( this . selectorManager == null ) { this . selectorManager = new SelectorManager ( this . selectorPoolSize , this , this . configuration ) ; this . selectorManager . start ( ) ; } } | Start selector manager | 56 | 3 |
29,811 | public void onRead ( SelectionKey key ) { if ( this . readEventDispatcher == null ) { dispatchReadEvent ( key ) ; } else { this . readEventDispatcher . dispatch ( new ReadTask ( key ) ) ; } } | Read event occured | 53 | 4 |
29,812 | public void onWrite ( final SelectionKey key ) { if ( this . writeEventDispatcher == null ) { dispatchWriteEvent ( key ) ; } else { this . writeEventDispatcher . dispatch ( new WriteTask ( key ) ) ; } } | Writable event occured | 54 | 5 |
29,813 | public void closeSelectionKey ( SelectionKey key ) { if ( key . attachment ( ) instanceof Session ) { Session session = ( Session ) key . attachment ( ) ; if ( session != null ) { session . close ( ) ; } } } | Cancel selection key | 52 | 4 |
29,814 | protected final NioSessionConfig buildSessionConfig ( SelectableChannel sc , Queue < WriteMessage > queue ) { final NioSessionConfig sessionConfig = new NioSessionConfig ( sc , getHandler ( ) , this . selectorManager , getCodecFactory ( ) , getStatistics ( ) , queue , this . dispatchMessageDispatcher , isHandleReadWriteConcurrently ( ) , this . sessionTimeout , this . configuration . getSessionIdleTimeout ( ) ) ; return sessionConfig ; } | Build nio session config | 104 | 5 |
29,815 | protected void readHeader ( ByteBuffer buffer ) { super . readHeader ( buffer ) ; if ( this . responseStatus != ResponseStatus . NO_ERROR ) { if ( ByteUtils . stepBuffer ( buffer , this . responseTotalBodyLength ) ) { this . decodeStatus = BinaryDecodeStatus . DONE ; } } } | optimistic if response status is greater than zero then skip buffer to next response set result as null | 69 | 19 |
29,816 | public ClusterConfigration getConfig ( String key ) throws MemcachedException , InterruptedException , TimeoutException { Command cmd = this . commandFactory . createAWSElasticCacheConfigCommand ( "get" , key ) ; final Session session = this . sendCommand ( cmd ) ; this . latchWait ( cmd , opTimeout , session ) ; cmd . getIoBuffer ( ) . free ( ) ; this . checkException ( cmd ) ; String result = ( String ) cmd . getResult ( ) ; if ( result == null ) { throw new MemcachedException ( "Operation fail,may be caused by networking or timeout" ) ; } return AWSUtils . parseConfiguration ( result ) ; } | Get config by key from cache node by network command . | 149 | 11 |
29,817 | public static final String nextLine ( ByteBuffer buffer ) { if ( buffer == null ) { return null ; } int index = MemcachedDecoder . SPLIT_MATCHER . matchFirst ( com . google . code . yanf4j . buffer . IoBuffer . wrap ( buffer ) ) ; if ( index >= 0 ) { int limit = buffer . limit ( ) ; buffer . limit ( index ) ; byte [ ] bytes = new byte [ buffer . remaining ( ) ] ; buffer . get ( bytes ) ; buffer . limit ( limit ) ; buffer . position ( index + ByteUtils . SPLIT . remaining ( ) ) ; return getString ( bytes ) ; } return null ; } | Read next line from ByteBuffer | 147 | 6 |
29,818 | protected final void configureSocketChannel ( SocketChannel sc ) throws IOException { sc . socket ( ) . setSoTimeout ( this . soTimeout ) ; sc . configureBlocking ( false ) ; if ( this . socketOptions . get ( StandardSocketOption . SO_REUSEADDR ) != null ) { sc . socket ( ) . setReuseAddress ( StandardSocketOption . SO_REUSEADDR . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . SO_REUSEADDR ) ) ) ; } if ( this . socketOptions . get ( StandardSocketOption . SO_SNDBUF ) != null ) { sc . socket ( ) . setSendBufferSize ( StandardSocketOption . SO_SNDBUF . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . SO_SNDBUF ) ) ) ; } if ( this . socketOptions . get ( StandardSocketOption . SO_KEEPALIVE ) != null ) { sc . socket ( ) . setKeepAlive ( StandardSocketOption . SO_KEEPALIVE . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . SO_KEEPALIVE ) ) ) ; } if ( this . socketOptions . get ( StandardSocketOption . SO_LINGER ) != null ) { sc . socket ( ) . setSoLinger ( this . soLingerOn , StandardSocketOption . SO_LINGER . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . SO_LINGER ) ) ) ; } if ( this . socketOptions . get ( StandardSocketOption . SO_RCVBUF ) != null ) { sc . socket ( ) . setReceiveBufferSize ( StandardSocketOption . SO_RCVBUF . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . SO_RCVBUF ) ) ) ; } if ( this . socketOptions . get ( StandardSocketOption . TCP_NODELAY ) != null ) { sc . socket ( ) . setTcpNoDelay ( StandardSocketOption . TCP_NODELAY . type ( ) . cast ( this . socketOptions . get ( StandardSocketOption . TCP_NODELAY ) ) ) ; } } | Confiure socket channel | 492 | 5 |
29,819 | protected void readHeader ( ByteBuffer buffer ) { super . readHeader ( buffer ) ; if ( this . responseStatus == ResponseStatus . NO_ERROR ) { this . decodeStatus = BinaryDecodeStatus . DONE ; } } | optimistic if no error goto done | 48 | 7 |
29,820 | public void bind ( InetSocketAddress inetSocketAddress ) throws IOException { if ( inetSocketAddress == null ) { throw new IllegalArgumentException ( "Null inetSocketAddress" ) ; } setLocalSocketAddress ( inetSocketAddress ) ; start ( ) ; } | Bind localhost address | 60 | 4 |
29,821 | @ Override public final void onMessageReceived ( final Session session , final Object msg ) { Command command = ( Command ) msg ; if ( this . statisticsHandler . isStatistics ( ) ) { if ( command . getCopiedMergeCount ( ) > 0 && command instanceof MapReturnValueAware ) { Map < String , CachedData > returnValues = ( ( MapReturnValueAware ) command ) . getReturnValues ( ) ; int size = returnValues . size ( ) ; this . statisticsHandler . statistics ( CommandType . GET_HIT , size ) ; this . statisticsHandler . statistics ( CommandType . GET_MISS , command . getCopiedMergeCount ( ) - size ) ; } else if ( command instanceof TextGetOneCommand || command instanceof BinaryGetCommand ) { if ( command . getResult ( ) != null ) { this . statisticsHandler . statistics ( CommandType . GET_HIT ) ; } else { this . statisticsHandler . statistics ( CommandType . GET_MISS ) ; } } else { if ( command . getCopiedMergeCount ( ) > 0 ) { this . statisticsHandler . statistics ( command . getCommandType ( ) , command . getCopiedMergeCount ( ) ) ; } else this . statisticsHandler . statistics ( command . getCommandType ( ) ) ; } } } | On receive message from memcached server | 286 | 8 |
29,822 | @ Override public void onSessionStarted ( Session session ) { session . setUseBlockingRead ( true ) ; session . setAttribute ( HEART_BEAT_FAIL_COUNT_ATTR , new AtomicInteger ( 0 ) ) ; for ( MemcachedClientStateListener listener : this . client . getStateListeners ( ) ) { listener . onConnected ( this . client , session . getRemoteSocketAddress ( ) ) ; } this . listener . onConnect ( ( MemcachedTCPSession ) session , this . client ) ; } | On session started | 119 | 3 |
29,823 | protected void reconnect ( MemcachedTCPSession session ) { if ( ! this . client . isShutdown ( ) ) { // Prevent reconnecting repeatedly synchronized ( session ) { if ( ! session . isAllowReconnect ( ) ) { return ; } session . setAllowReconnect ( false ) ; } MemcachedSession memcachedTCPSession = session ; InetSocketAddressWrapper inetSocketAddressWrapper = memcachedTCPSession . getInetSocketAddressWrapper ( ) ; this . client . getConnector ( ) . addToWatingQueue ( new ReconnectRequest ( inetSocketAddressWrapper , 0 , this . client . getHealSessionInterval ( ) ) ) ; } } | Auto reconect to memcached server | 155 | 8 |
29,824 | public static void setAllocator ( IoBufferAllocator newAllocator ) { if ( newAllocator == null ) { throw new NullPointerException ( "allocator" ) ; } IoBufferAllocator oldAllocator = allocator ; allocator = newAllocator ; if ( null != oldAllocator ) { oldAllocator . dispose ( ) ; } } | Sets the allocator used by existing and new buffers | 85 | 11 |
29,825 | public static IoBuffer allocate ( int capacity , boolean direct ) { if ( capacity < 0 ) { throw new IllegalArgumentException ( "capacity: " + capacity ) ; } return allocator . allocate ( capacity , direct ) ; } | Returns the buffer which is capable of the specified size . | 48 | 11 |
29,826 | public static IoBuffer wrap ( byte [ ] byteArray , int offset , int length ) { return wrap ( ByteBuffer . wrap ( byteArray , offset , length ) ) ; } | Wraps the specified byte array into MINA heap buffer . | 37 | 12 |
29,827 | private boolean lookJVMBug ( long before , int selected , long wait ) throws IOException { boolean seeing = false ; long now = System . currentTimeMillis ( ) ; if ( JVMBUG_THRESHHOLD > 0 && selected == 0 && wait > JVMBUG_THRESHHOLD && now - before < wait / 4 && ! wakenUp . get ( ) /* waken up */ && ! Thread . currentThread ( ) . isInterrupted ( ) /* Interrupted */ ) { jvmBug . incrementAndGet ( ) ; if ( jvmBug . get ( ) >= JVMBUG_THRESHHOLD2 ) { gate . lock ( ) ; try { lastJVMBug = now ; log . warn ( "JVM bug occured at " + new Date ( lastJVMBug ) + ",http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933,reactIndex=" + reactorIndex ) ; if ( jvmBug1 ) { log . debug ( "seeing JVM BUG(s) - recreating selector,reactIndex=" + reactorIndex ) ; } else { jvmBug1 = true ; log . info ( "seeing JVM BUG(s) - recreating selector,reactIndex=" + reactorIndex ) ; } seeing = true ; final Selector new_selector = SystemUtils . openSelector ( ) ; for ( SelectionKey k : selector . keys ( ) ) { if ( ! k . isValid ( ) || k . interestOps ( ) == 0 ) { continue ; } final SelectableChannel channel = k . channel ( ) ; final Object attachment = k . attachment ( ) ; channel . register ( new_selector , k . interestOps ( ) , attachment ) ; } selector . close ( ) ; selector = new_selector ; } finally { gate . unlock ( ) ; } jvmBug . set ( 0 ) ; } else if ( jvmBug . get ( ) == JVMBUG_THRESHHOLD || jvmBug . get ( ) == JVMBUG_THRESHHOLD1 ) { if ( jvmBug0 ) { log . debug ( "seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + reactorIndex ) ; } else { jvmBug0 = true ; log . info ( "seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + reactorIndex ) ; } gate . lock ( ) ; seeing = true ; try { for ( SelectionKey k : selector . keys ( ) ) { if ( k . isValid ( ) && k . interestOps ( ) == 0 ) { k . cancel ( ) ; } } } finally { gate . unlock ( ) ; } } } else { jvmBug . set ( 0 ) ; } return seeing ; } | Look jvm bug | 613 | 4 |
29,828 | public final void dispatchEvent ( Set < SelectionKey > selectedKeySet ) { Iterator < SelectionKey > it = selectedKeySet . iterator ( ) ; boolean skipOpRead = false ; while ( it . hasNext ( ) ) { SelectionKey key = it . next ( ) ; it . remove ( ) ; if ( ! key . isValid ( ) ) { if ( key . attachment ( ) != null ) { controller . closeSelectionKey ( key ) ; } else { key . cancel ( ) ; } continue ; } try { if ( key . isValid ( ) && key . isAcceptable ( ) ) { controller . onAccept ( key ) ; continue ; } if ( key . isValid ( ) && ( key . readyOps ( ) & SelectionKey . OP_WRITE ) == SelectionKey . OP_WRITE ) { // Remove write interest key . interestOps ( key . interestOps ( ) & ~ SelectionKey . OP_WRITE ) ; controller . onWrite ( key ) ; if ( ! controller . isHandleReadWriteConcurrently ( ) ) { skipOpRead = true ; } } if ( ! skipOpRead && key . isValid ( ) && ( key . readyOps ( ) & SelectionKey . OP_READ ) == SelectionKey . OP_READ ) { key . interestOps ( key . interestOps ( ) & ~ SelectionKey . OP_READ ) ; if ( ! controller . getStatistics ( ) . isReceiveOverFlow ( ) ) { // Remove read interest controller . onRead ( key ) ; } else { key . interestOps ( key . interestOps ( ) | SelectionKey . OP_READ ) ; } } if ( ( key . readyOps ( ) & SelectionKey . OP_CONNECT ) == SelectionKey . OP_CONNECT ) { controller . onConnect ( key ) ; } } catch ( CancelledKeyException e ) { // ignore } catch ( RejectedExecutionException e ) { if ( key . attachment ( ) instanceof AbstractNioSession ) { ( ( AbstractNioSession ) key . attachment ( ) ) . onException ( e ) ; } controller . notifyException ( e ) ; if ( selector . isOpen ( ) ) { continue ; } else { break ; } } catch ( Exception e ) { if ( key . attachment ( ) instanceof AbstractNioSession ) { ( ( AbstractNioSession ) key . attachment ( ) ) . onException ( e ) ; } controller . closeSelectionKey ( key ) ; controller . notifyException ( e ) ; log . error ( "Reactor dispatch events error" , e ) ; if ( selector . isOpen ( ) ) { continue ; } else { break ; } } } } | Dispatch selected event | 567 | 3 |
29,829 | public final void addServer ( final String server , final int port , int weight ) throws IOException { if ( weight <= 0 ) { throw new IllegalArgumentException ( "weight<=0" ) ; } this . checkServerPort ( server , port ) ; this . connect ( new InetSocketAddressWrapper ( this . newSocketAddress ( server , port ) , this . serverOrderCount . incrementAndGet ( ) , weight , null ) ) ; } | add a memcached server to MemcachedClient | 97 | 11 |
29,830 | private final Collection < List < String > > catalogKeys ( final Collection < String > keyCollections ) { final Map < Session , List < String > > catalogMap = new HashMap < Session , List < String > > ( ) ; for ( String key : keyCollections ) { Session index = this . sessionLocator . getSessionByKey ( key ) ; List < String > tmpKeys = catalogMap . get ( index ) ; if ( tmpKeys == null ) { tmpKeys = new ArrayList < String > ( 10 ) ; catalogMap . put ( index , tmpKeys ) ; } tmpKeys . add ( key ) ; } Collection < List < String > > catalogKeys = catalogMap . values ( ) ; return catalogKeys ; } | Hash key to servers | 155 | 4 |
29,831 | public final void deleteWithNoReply ( final String key , final int time ) throws InterruptedException , MemcachedException { try { this . delete0 ( key , time , 0 , true , this . opTimeout ) ; } catch ( TimeoutException e ) { throw new MemcachedException ( e ) ; } } | Delete key s data item from memcached . This method doesn t wait for reply | 67 | 17 |
29,832 | public String getNamespace ( String ns ) throws TimeoutException , InterruptedException , MemcachedException { String key = this . keyProvider . process ( this . getNSKey ( ns ) ) ; byte [ ] keyBytes = ByteUtils . getBytes ( key ) ; ByteUtils . checkKey ( keyBytes ) ; Object item = this . fetch0 ( key , keyBytes , CommandType . GET_ONE , this . opTimeout , this . transcoder ) ; while ( item == null ) { item = String . valueOf ( System . nanoTime ( ) ) ; boolean added = this . add0 ( key , 0 , item , this . transcoder , this . opTimeout ) ; if ( ! added ) { item = this . fetch0 ( key , keyBytes , CommandType . GET_ONE , this . opTimeout , this . transcoder ) ; } } String namespace = item . toString ( ) ; if ( ! ByteUtils . isNumber ( namespace ) ) { throw new IllegalStateException ( "Namespace key already has value.The key is:" + key + ",and the value is:" + namespace ) ; } return namespace ; } | Returns the real namespace of ns . | 246 | 7 |
29,833 | public final static void setMaxSelectors ( int size ) throws IOException { synchronized ( selectors ) { if ( size < maxSelectors ) { reduce ( size ) ; } else if ( size > maxSelectors ) { grow ( size ) ; } maxSelectors = size ; } } | Set max selector pool size . | 61 | 6 |
29,834 | private boolean advanceHead ( QNode h , QNode nh ) { if ( h == this . head . get ( ) && this . head . compareAndSet ( h , nh ) ) { h . next = h ; // forget old next return true ; } return false ; } | Tries to cas nh as new head ; if successful unlink old head s next node to avoid garbage retention . | 60 | 24 |
29,835 | private QNode getValidatedTail ( ) { for ( ; ; ) { QNode h = this . head . get ( ) ; QNode first = h . next ; if ( first != null && first . next == first ) { // help advance advanceHead ( h , first ) ; continue ; } QNode t = this . tail . get ( ) ; QNode last = t . next ; if ( t == this . tail . get ( ) ) { if ( last != null ) { this . tail . compareAndSet ( t , last ) ; // help advance } else { return t ; } } } } | Returns validated tail for use in cleaning methods | 130 | 8 |
29,836 | QNode traversalHead ( ) { for ( ; ; ) { QNode t = this . tail . get ( ) ; QNode h = this . head . get ( ) ; if ( h != null && t != null ) { QNode last = t . next ; QNode first = h . next ; if ( t == this . tail . get ( ) ) { if ( last != null ) { this . tail . compareAndSet ( t , last ) ; } else if ( first != null ) { Object x = first . get ( ) ; if ( x == first ) { advanceHead ( h , first ) ; } else { return h ; } } else { return h ; } } } } } | Return head after performing any outstanding helping steps | 149 | 8 |
29,837 | public static ClusterConfigration parseConfiguration ( String line ) { String [ ] lines = line . trim ( ) . split ( "(?:\\r?\\n)" ) ; if ( lines . length < 2 ) { throw new IllegalArgumentException ( "Incorrect config response:" + line ) ; } String configversion = lines [ 0 ] ; String nodeListStr = lines [ 1 ] ; if ( ! ByteUtils . isNumber ( configversion ) ) { throw new IllegalArgumentException ( "Invalid configversion: " + configversion + ", it should be a number." ) ; } String [ ] nodeStrs = nodeListStr . split ( "(?:\\s)+" ) ; int version = Integer . parseInt ( configversion ) ; List < CacheNode > nodeList = new ArrayList < CacheNode > ( nodeStrs . length ) ; for ( String nodeStr : nodeStrs ) { if ( nodeStr . equals ( "" ) ) { continue ; } int firstDelimiter = nodeStr . indexOf ( DELIMITER ) ; int secondDelimiter = nodeStr . lastIndexOf ( DELIMITER ) ; if ( firstDelimiter < 1 || firstDelimiter == secondDelimiter ) { throw new IllegalArgumentException ( "Invalid server ''" + nodeStr + "'' in response: " + line ) ; } String hostName = nodeStr . substring ( 0 , firstDelimiter ) . trim ( ) ; String ipAddress = nodeStr . substring ( firstDelimiter + 1 , secondDelimiter ) . trim ( ) ; String portNum = nodeStr . substring ( secondDelimiter + 1 ) . trim ( ) ; int port = Integer . parseInt ( portNum ) ; nodeList . add ( new CacheNode ( hostName , ipAddress , port ) ) ; } return new ClusterConfigration ( version , nodeList ) ; } | Parse response string to ClusterConfiguration instance . | 404 | 9 |
29,838 | public long get ( ) throws MemcachedException , InterruptedException , TimeoutException { Object result = this . memcachedClient . get ( this . key ) ; if ( result == null ) { throw new MemcachedClientException ( "key is not existed." ) ; } else { if ( result instanceof Long ) return ( Long ) result ; else return Long . valueOf ( ( ( String ) result ) . trim ( ) ) ; } } | Get current value | 96 | 3 |
29,839 | public void set ( long value ) throws MemcachedException , InterruptedException , TimeoutException { this . memcachedClient . set ( this . key , 0 , String . valueOf ( value ) ) ; } | Set counter s value to expected . | 46 | 7 |
29,840 | public long addAndGet ( long delta ) throws MemcachedException , InterruptedException , TimeoutException { if ( delta >= 0 ) { return this . memcachedClient . incr ( this . key , delta , this . initialValue ) ; } else { return this . memcachedClient . decr ( this . key , - delta , this . initialValue ) ; } } | Add value and get the result | 82 | 6 |
29,841 | public static char [ ] getAllowedFunctionCharacters ( ) { char [ ] chars = new char [ 53 ] ; int count = 0 ; for ( int i = 65 ; i < 91 ; i ++ ) { chars [ count ++ ] = ( char ) i ; } for ( int i = 97 ; i < 123 ; i ++ ) { chars [ count ++ ] = ( char ) i ; } chars [ count ] = ' ' ; return chars ; } | Get the set of characters which are allowed for use in Function names . | 95 | 14 |
29,842 | public static Function getBuiltinFunction ( final String name ) { if ( name . equals ( "sin" ) ) { return builtinFunctions [ INDEX_SIN ] ; } else if ( name . equals ( "cos" ) ) { return builtinFunctions [ INDEX_COS ] ; } else if ( name . equals ( "tan" ) ) { return builtinFunctions [ INDEX_TAN ] ; } else if ( name . equals ( "cot" ) ) { return builtinFunctions [ INDEX_COT ] ; } else if ( name . equals ( "asin" ) ) { return builtinFunctions [ INDEX_ASIN ] ; } else if ( name . equals ( "acos" ) ) { return builtinFunctions [ INDEX_ACOS ] ; } else if ( name . equals ( "atan" ) ) { return builtinFunctions [ INDEX_ATAN ] ; } else if ( name . equals ( "sinh" ) ) { return builtinFunctions [ INDEX_SINH ] ; } else if ( name . equals ( "cosh" ) ) { return builtinFunctions [ INDEX_COSH ] ; } else if ( name . equals ( "tanh" ) ) { return builtinFunctions [ INDEX_TANH ] ; } else if ( name . equals ( "abs" ) ) { return builtinFunctions [ INDEX_ABS ] ; } else if ( name . equals ( "log" ) ) { return builtinFunctions [ INDEX_LOG ] ; } else if ( name . equals ( "log10" ) ) { return builtinFunctions [ INDEX_LOG10 ] ; } else if ( name . equals ( "log2" ) ) { return builtinFunctions [ INDEX_LOG2 ] ; } else if ( name . equals ( "log1p" ) ) { return builtinFunctions [ INDEX_LOG1P ] ; } else if ( name . equals ( "ceil" ) ) { return builtinFunctions [ INDEX_CEIL ] ; } else if ( name . equals ( "floor" ) ) { return builtinFunctions [ INDEX_FLOOR ] ; } else if ( name . equals ( "sqrt" ) ) { return builtinFunctions [ INDEX_SQRT ] ; } else if ( name . equals ( "cbrt" ) ) { return builtinFunctions [ INDEX_CBRT ] ; } else if ( name . equals ( "pow" ) ) { return builtinFunctions [ INDEX_POW ] ; } else if ( name . equals ( "exp" ) ) { return builtinFunctions [ INDEX_EXP ] ; } else if ( name . equals ( "expm1" ) ) { return builtinFunctions [ INDEX_EXPM1 ] ; } else if ( name . equals ( "signum" ) ) { return builtinFunctions [ INDEX_SGN ] ; } else { return null ; } } | Get the builtin function for a given name | 661 | 9 |
29,843 | public static List < Boolean > unmodifiableView ( boolean [ ] array , int length ) { return Collections . unmodifiableList ( view ( array , length ) ) ; } | Creates an returns an unmodifiable view of the given boolean array that requires only a small object allocation . | 37 | 22 |
29,844 | public static BooleanList view ( boolean [ ] array , int length ) { if ( length > array . length || length < 0 ) throw new IllegalArgumentException ( "length must be non-negative and no more than the size of the array(" + array . length + "), not " + length ) ; return new BooleanList ( array , length ) ; } | Creates and returns a view of the given boolean array that requires only a small object allocation . Changes to the list will be reflected in the array up to a point . If the modification would require increasing the capacity of the array a new array will be allocated - at which point operations will no longer be reflected in the original array . | 75 | 66 |
29,845 | public void setMomentum ( double momentum ) { if ( momentum < 0 || Double . isNaN ( momentum ) || Double . isInfinite ( momentum ) ) throw new ArithmeticException ( "Momentum must be non negative, not " + momentum ) ; this . momentum = momentum ; } | Sets the non negative momentum used in training . | 63 | 10 |
29,846 | public void setWeightDecay ( double weightDecay ) { if ( weightDecay < 0 || weightDecay >= 1 || Double . isNaN ( weightDecay ) ) throw new ArithmeticException ( "Weight decay must be in [0,1), not " + weightDecay ) ; this . weightDecay = weightDecay ; } | Sets the weight decay used for each update . The weight decay must be in the range [ 0 1 ) . Weight decay values must often be very small often 1e - 8 or less . | 74 | 39 |
29,847 | private void setUp ( Random rand ) { Ws = new ArrayList <> ( npl . length ) ; bs = new ArrayList <> ( npl . length ) ; //First Hiden layer takes input raw DenseMatrix W = new DenseMatrix ( npl [ 0 ] , inputSize ) ; Vec b = new DenseVector ( W . rows ( ) ) ; initializeWeights ( W , rand ) ; initializeWeights ( b , W . cols ( ) , rand ) ; Ws . add ( W ) ; bs . add ( b ) ; //Other Hiden Layers Layers for ( int i = 1 ; i < npl . length ; i ++ ) { W = new DenseMatrix ( npl [ i ] , npl [ i - 1 ] ) ; b = new DenseVector ( W . rows ( ) ) ; initializeWeights ( W , rand ) ; initializeWeights ( b , W . cols ( ) , rand ) ; Ws . add ( W ) ; bs . add ( b ) ; } //Output layer W = new DenseMatrix ( outputSize , npl [ npl . length - 1 ] ) ; b = new DenseVector ( W . rows ( ) ) ; initializeWeights ( W , rand ) ; initializeWeights ( b , W . cols ( ) , rand ) ; Ws . add ( W ) ; bs . add ( b ) ; } | Creates the weights for the hidden layers and output layer | 308 | 11 |
29,848 | private double computeOutputDelta ( DataSet dataSet , final int idx , Vec delta_out , Vec a_i , Vec d_i ) { double error = 0 ; if ( dataSet instanceof ClassificationDataSet ) { ClassificationDataSet cds = ( ClassificationDataSet ) dataSet ; final int ct = cds . getDataPointCategory ( idx ) ; for ( int i = 0 ; i < outputSize ; i ++ ) if ( i == ct ) delta_out . set ( i , f . max ( ) - targetBump ) ; else delta_out . set ( i , f . min ( ) + targetBump ) ; for ( int j = 0 ; j < delta_out . length ( ) ; j ++ ) { double val = delta_out . get ( j ) ; error += pow ( ( val - a_i . get ( j ) ) , 2 ) ; val = - ( val - a_i . get ( j ) ) * d_i . get ( j ) ; delta_out . set ( j , val ) ; } } else if ( dataSet instanceof RegressionDataSet ) { RegressionDataSet rds = ( RegressionDataSet ) dataSet ; double val = rds . getTargetValue ( idx ) ; val = f . min ( ) + targetBump + targetMultiplier * ( val - targetMin ) ; error += pow ( ( val - a_i . get ( 0 ) ) , 2 ) ; delta_out . set ( 0 , - ( val - a_i . get ( 0 ) ) * d_i . get ( 0 ) ) ; } else { throw new RuntimeException ( "BUG: please report" ) ; } return error ; } | Computes the delta between the networks output for a same and its true value | 371 | 15 |
29,849 | private void feedForward ( Vec input , List < Vec > activations , List < Vec > derivatives ) { Vec x = input ; for ( int i = 0 ; i < Ws . size ( ) ; i ++ ) { Matrix W_i = Ws . get ( i ) ; Vec b_i = bs . get ( i ) ; Vec a_i = activations . get ( i ) ; a_i . zeroOut ( ) ; W_i . multiply ( x , 1 , a_i ) ; a_i . mutableAdd ( b_i ) ; a_i . applyFunction ( f ) ; Vec d_i = derivatives . get ( i ) ; a_i . copyTo ( d_i ) ; d_i . applyFunction ( f . getD ( ) ) ; x = a_i ; } } | Feeds a vector through the network to get an output | 180 | 11 |
29,850 | private Vec feedForward ( Vec input ) { Vec x = input ; for ( int i = 0 ; i < Ws . size ( ) ; i ++ ) { Matrix W_i = Ws . get ( i ) ; Vec b_i = bs . get ( i ) ; Vec a_i = W_i . multiply ( x ) ; a_i . mutableAdd ( b_i ) ; a_i . applyFunction ( f ) ; x = a_i ; } return x ; } | Feeds an input through the network | 108 | 7 |
29,851 | public void setRegularization ( double regularization ) { if ( Double . isNaN ( regularization ) || Double . isInfinite ( regularization ) || regularization <= 0 ) throw new ArithmeticException ( "Regularization must be a positive constant, not " + regularization ) ; this . regularization = regularization ; } | Sets the amount of regularization to apply . The regularization must be a positive value | 69 | 18 |
29,852 | public void sortByEigenValue ( Comparator < Double > cmp ) { if ( isComplex ( ) ) throw new ArithmeticException ( "Eigen values can not be sorted due to complex results" ) ; IndexTable it = new IndexTable ( DoubleList . unmodifiableView ( d , d . length ) , cmp ) ; for ( int i = 0 ; i < d . length ; i ++ ) { RowColumnOps . swapCol ( V , i , it . index ( i ) ) ; double tmp = d [ i ] ; d [ i ] = d [ it . index ( i ) ] ; d [ it . index ( i ) ] = tmp ; it . swap ( i , it . index ( i ) ) ; } } | Sorts the eigen values and the corresponding eigenvector columns by the associated eigen value . Sorting can not occur if complex values are present . | 160 | 31 |
29,853 | public Vec feedfoward ( Vec x ) { Vec a_lprev = x ; for ( int l = 0 ; l < layersActivation . size ( ) ; l ++ ) { Vec z_l = new DenseVector ( layerSizes [ l + 1 ] ) ; z_l . zeroOut ( ) ; W . get ( l ) . multiply ( a_lprev , 1.0 , z_l ) ; //add the bias term back in final Vec B_l = B . get ( l ) ; z_l . mutableAdd ( B_l ) ; layersActivation . get ( l ) . activate ( z_l , z_l ) ; a_lprev = z_l ; } return a_lprev ; } | Feeds the given singular pattern through the network and computes its activations | 161 | 15 |
29,854 | private static void applyDropout ( final Matrix X , final int randThresh , final Random rand , ExecutorService ex ) { if ( ex == null ) { for ( int i = 0 ; i < X . rows ( ) ; i ++ ) for ( int j = 0 ; j < X . cols ( ) ; j ++ ) if ( rand . nextInt ( ) < randThresh ) X . set ( i , j , 0.0 ) ; } else { final CountDownLatch latch = new CountDownLatch ( SystemInfo . LogicalCores ) ; for ( int id = 0 ; id < SystemInfo . LogicalCores ; id ++ ) { final int ID = id ; ex . submit ( new Runnable ( ) { @ Override public void run ( ) { for ( int i = ID ; i < X . rows ( ) ; i += SystemInfo . LogicalCores ) for ( int j = 0 ; j < X . cols ( ) ; j ++ ) if ( rand . nextInt ( ) < randThresh ) X . set ( i , j , 0.0 ) ; latch . countDown ( ) ; } } ) ; } try { latch . await ( ) ; } catch ( InterruptedException ex1 ) { Logger . getLogger ( SGDNetworkTrainer . class . getName ( ) ) . log ( Level . SEVERE , null , ex1 ) ; } } } | Applies dropout to the given matrix | 307 | 8 |
29,855 | private DataPoint getPredVecR ( DataPoint data ) { Vec w = new DenseVector ( baseRegressors . size ( ) ) ; for ( int i = 0 ; i < baseRegressors . size ( ) ; i ++ ) w . set ( i , baseRegressors . get ( i ) . regress ( data ) ) ; return new DataPoint ( w ) ; } | Gets the predicted vector wrapped in a new DataPoint from a data point assuming we are doing regression | 84 | 20 |
29,856 | public static int getNextPow2TwinPrime ( int m ) { int pos = Arrays . binarySearch ( twinPrimesP2 , m + 1 ) ; if ( pos >= 0 ) return twinPrimesP2 [ pos ] ; else return twinPrimesP2 [ - pos - 1 ] ; } | Gets the next twin prime that is near a power of 2 and greater than or equal to the given value | 67 | 22 |
29,857 | public void replaceNumericFeatures ( List < Vec > newNumericFeatures ) { if ( this . size ( ) != newNumericFeatures . size ( ) ) throw new RuntimeException ( "Input list does not have the same not of dataums as the dataset" ) ; for ( int i = 0 ; i < newNumericFeatures . size ( ) ; i ++ ) { DataPoint dp_i = getDataPoint ( i ) ; setDataPoint ( i , new DataPoint ( newNumericFeatures . get ( i ) , dp_i . getCategoricalValues ( ) , dp_i . getCategoricalData ( ) ) ) ; } this . numNumerVals = getDataPoint ( 0 ) . numNumericalValues ( ) ; if ( this . numericalVariableNames != null ) this . numericalVariableNames . clear ( ) ; } | This method will replace every numeric feature in this dataset with a Vec object from the given list . All vecs in the given list must be of the same size . | 186 | 33 |
29,858 | protected void base_add ( DataPoint dp , double weight ) { datapoints . addDataPoint ( dp ) ; setWeight ( size ( ) - 1 , weight ) ; } | Adds a new datapoint to this set . This method is protected as not all datasets will be satisfied by adding just a data point . | 41 | 28 |
29,859 | public Iterator < DataPoint > getDataPointIterator ( ) { Iterator < DataPoint > iteData = new Iterator < DataPoint > ( ) { int cur = 0 ; int to = size ( ) ; @ Override public boolean hasNext ( ) { return cur < to ; } @ Override public DataPoint next ( ) { return getDataPoint ( cur ++ ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( "This operation is not supported for DataSet" ) ; } } ; return iteData ; } | Returns an iterator that will iterate over all data points in the set . The behavior is not defined if one attempts to modify the data set while being iterated . | 119 | 33 |
29,860 | public Type getMissingDropped ( ) { List < Integer > hasNoMissing = new IntList ( ) ; for ( int i = 0 ; i < size ( ) ; i ++ ) { DataPoint dp = getDataPoint ( i ) ; boolean missing = dp . getNumericalValues ( ) . countNaNs ( ) > 0 ; for ( int c : dp . getCategoricalValues ( ) ) if ( c < 0 ) missing = true ; if ( ! missing ) hasNoMissing . add ( i ) ; } return getSubset ( hasNoMissing ) ; } | This method returns a dataset that is a subset of this dataset where only the rows that have no missing values are kept . The new dataset is backed by this dataset . | 126 | 33 |
29,861 | public List < Type > randomSplit ( Random rand , double ... splits ) { if ( splits . length < 1 ) throw new IllegalArgumentException ( "Input array of split fractions must be non-empty" ) ; IntList randOrder = new IntList ( size ( ) ) ; ListUtils . addRange ( randOrder , 0 , size ( ) , 1 ) ; Collections . shuffle ( randOrder , rand ) ; int [ ] stops = new int [ splits . length ] ; double sum = 0 ; for ( int i = 0 ; i < splits . length ; i ++ ) { sum += splits [ i ] ; if ( sum >= 1.001 /*some flex room for numeric issues*/ ) throw new IllegalArgumentException ( "Input splits sum is greater than 1 by index " + i + " reaching a sum of " + sum ) ; stops [ i ] = ( int ) Math . round ( sum * randOrder . size ( ) ) ; } List < Type > datasets = new ArrayList <> ( splits . length ) ; int prev = 0 ; for ( int i = 0 ; i < stops . length ; i ++ ) { datasets . add ( getSubset ( randOrder . subList ( prev , stops [ i ] ) ) ) ; prev = stops [ i ] ; } return datasets ; } | Splits the dataset randomly into proportionally sized partitions . | 275 | 11 |
29,862 | public List < DataPoint > getDataPoints ( ) { List < DataPoint > list = new ArrayList <> ( size ( ) ) ; for ( int i = 0 ; i < size ( ) ; i ++ ) list . ( getDataPoint ( i ) ) ; return list ; } | Creates a list containing the same DataPoints in this set . They are soft copies in the same order as this data set . However altering this list will have no effect on DataSet . Altering the DataPoints in the list will effect the DataPoints in this DataSet . | 61 | 56 |
29,863 | public List < Vec > getDataVectors ( ) { List < Vec > vecs = new ArrayList <> ( size ( ) ) ; for ( int i = 0 ; i < size ( ) ; i ++ ) vecs . ( getDataPoint ( i ) . getNumericalValues ( ) ) ; return vecs ; } | Creates a list of the vectors values for each data point in the correct order . | 72 | 17 |
29,864 | public void setWeight ( int i , double w ) { if ( i >= size ( ) || i < 0 ) throw new IndexOutOfBoundsException ( "Dataset has only " + size ( ) + " members, can't access index " + i ) ; else if ( Double . isNaN ( w ) || Double . isInfinite ( w ) || w < 0 ) throw new ArithmeticException ( "Invalid weight assignment of " + w ) ; if ( w == 1 && weights == null ) return ; //nothing to do, already handled implicitly if ( weights == null ) //need to init? { weights = new double [ size ( ) ] ; Arrays . fill ( weights , 1.0 ) ; } //make sure we have enouh space if ( weights . length <= i ) weights = Arrays . copyOfRange ( weights , 0 , Math . max ( weights . length * 2 , i + 1 ) ) ; weights [ i ] = w ; } | Sets the weight of a given datapoint within this data set . | 207 | 15 |
29,865 | public double getWeight ( int i ) { if ( i >= size ( ) || i < 0 ) throw new IndexOutOfBoundsException ( "Dataset has only " + size ( ) + " members, can't access index " + i ) ; if ( weights == null ) return 1 ; else if ( weights . length <= i ) return 1 ; else return weights [ i ] ; } | Returns the weight of the specified data point | 83 | 8 |
29,866 | public Vec getDataWeights ( ) { final int N = this . size ( ) ; if ( N == 0 ) return new DenseVector ( 0 ) ; //assume everyone has the same weight until proven otherwise. double weight = getWeight ( 0 ) ; double [ ] weights_copy = null ; for ( int i = 1 ; i < N ; i ++ ) { double w_i = getWeight ( i ) ; if ( weights_copy != null || weight != w_i ) { if ( weights_copy == null ) //need to init storage place { weights_copy = new double [ N ] ; Arrays . fill ( weights_copy , 0 , i , weight ) ; } weights_copy [ i ] = w_i ; } } if ( weights_copy == null ) return new ConstantVector ( weight , size ( ) ) ; else return new DenseVector ( weights_copy ) ; } | This method returns the weight of each data point in a single Vector . When all data points have the same weight this will return a vector that uses fixed memory instead of allocating a full double backed array . | 193 | 41 |
29,867 | public < Type extends DataSet > OnLineStatistics [ ] evaluateFeatureImportance ( DataSet < Type > data , TreeFeatureImportanceInference imp ) { OnLineStatistics [ ] importances = new OnLineStatistics [ data . getNumFeatures ( ) ] ; for ( int i = 0 ; i < importances . length ; i ++ ) importances [ i ] = new OnLineStatistics ( ) ; for ( ExtraTree tree : forrest ) { double [ ] feats = imp . getImportanceStats ( tree , data ) ; for ( int i = 0 ; i < importances . length ; i ++ ) importances [ i ] . ( feats [ i ] ) ; } return importances ; } | Measures the statistics of feature importance from the trees in this forest . | 148 | 14 |
29,868 | @ WarmParameter ( prefLowToHigh = true ) public void setC ( double C ) { if ( C <= 0 || Double . isInfinite ( C ) || Double . isNaN ( C ) ) throw new IllegalArgumentException ( "Regularization term C must be a positive value, not " + C ) ; this . C = C ; } | Sets the regularization term where smaller values indicate a larger regularization penalty . | 75 | 16 |
29,869 | private double getM_Bar_for_w0 ( int n , int l , List < Vec > columnsOfX , double [ ] col_neg_class_sum , double col_neg_class_sum_bias ) { /** * if w=0, then D_part[i] = 0.5 for all i */ final double D_part_i = 0.5 ; //algo 3, Step 1. double M_bar = 0 ; //algo 3, Step 2. for ( int j = 0 ; j < n ; j ++ ) { final double w_j = 0 ; //2.1. Calculate H^k_{jj}, ∇_j L(w^k) and ∇^S_j f(w^k) double delta_j_L = - columnsOfX . get ( j ) . sum ( ) * 0.5 ; delta_j_L = /* (l2w * w_j) not needed b/c w_j=0*/ + C * ( delta_j_L + col_neg_class_sum [ j ] ) ; double deltaS_j_fw ; //only the w_j = 0 case applies, b/c that is what this method is for! //w_j = 0 deltaS_j_fw = signum ( delta_j_L ) * max ( abs ( delta_j_L ) - alpha , 0 ) ; //done with step 2, we have all the info M_bar += abs ( deltaS_j_fw ) ; } if ( useBias ) { //2.1. Calculate H^k_{jj}, ∇_j L(w^k) and ∇^S_j f(w^k) double delta_j_L = 0 ; for ( int i = 0 ; i < l ; i ++ ) //all have an implicit bias term delta_j_L += - D_part_i ; delta_j_L = C * ( delta_j_L + col_neg_class_sum_bias ) ; double deltaS_j_fw = delta_j_L ; M_bar += abs ( deltaS_j_fw ) ; } return M_bar ; } | When we perform a warm start we want to train to the same point that we would have if we had not done a warm start . But our stopping point is based on the initial relative error . To get around that this method computes what the error would have been for the zero weight vector | 483 | 58 |
29,870 | public void add ( double x , double weight ) { //See http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance if ( weight < 0 ) throw new ArithmeticException ( "Can not add a negative weight" ) ; else if ( weight == 0 ) return ; double n1 = n ; n += weight ; double delta = x - mean ; double delta_n = delta * weight / n ; double delta_n2 = delta_n * delta_n ; double term1 = delta * delta_n * n1 ; mean += delta_n ; m4 += term1 * delta_n2 * ( n * n - 3 * n + 3 ) + 6 * delta_n2 * m2 - 4 * delta_n * m3 ; m3 += term1 * delta_n * ( n - 2 ) - 3 * delta_n * m2 ; m2 += weight * delta * ( x - mean ) ; if ( min == null ) min = max = x ; else { min = Math . min ( min , x ) ; max = Math . max ( max , x ) ; } } | Adds a data sample the the counts with the provided weight of influence . | 245 | 14 |
29,871 | public void setBurnIn ( double burnIn ) { if ( Double . isNaN ( burnIn ) || burnIn < 0 || burnIn >= 1 ) throw new IllegalArgumentException ( "BurnInFraction must be in [0, 1), not " + burnIn ) ; this . burnIn = burnIn ; } | Sets the burn in fraction . SBP averages the intermediate solutions from each step as the final solution . The intermediate steps of SBP are highly correlated and the begging solutions are usually not as meaningful toward the converged solution . To overcome this issue a certain fraction of the iterations are not averaged into the final solution making them the burn in fraction . A value of 0 . 25 would then be ignoring the initial 25% of solutions . | 69 | 86 |
29,872 | public boolean add ( int e ) { if ( e < 0 || e >= has . length ) throw new IllegalArgumentException ( "Input must be in range [0, " + has . length + ") not " + e ) ; else if ( contains ( e ) ) return false ; else { if ( nnz == 0 ) { first = e ; next [ e ] = prev [ e ] = STOP ; } else { prev [ first ] = e ; next [ e ] = first ; prev [ e ] = STOP ; first = e ; } nnz ++ ; return has [ e ] = true ; } } | Adds a new integer into the set | 130 | 7 |
29,873 | public static List < Integer > unmodifiableView ( int [ ] array , int length ) { return Collections . unmodifiableList ( view ( array , length ) ) ; } | Creates and returns an unmodifiable view of the given int array that requires only a small object allocation . | 37 | 22 |
29,874 | public static IntList view ( int [ ] array , int length ) { if ( length > array . length || length < 0 ) throw new IllegalArgumentException ( "length must be non-negative and no more than the size of the array(" + array . length + "), not " + length ) ; return new IntList ( array , length ) ; } | Creates and returns a view of the given int array that requires only a small object allocation . Changes to the list will be reflected in the array up to a point . If the modification would require increasing the capacity of the array a new array will be allocated - at which point operations will no longer be reflected in the original array . | 75 | 66 |
29,875 | public static IntList range ( int start , int end , int step ) { IntList l = new IntList ( ( end - start ) / step + 1 ) ; for ( int i = start ; i < end ; i ++ ) l . ( i ) ; return l ; } | Returns a new IntList containing values in the given range | 59 | 11 |
29,876 | public int dataPointToCord ( DataPointPair < Integer > dataPoint , int targetClass , int [ ] cord ) { if ( cord . length != getDimensionSize ( ) ) throw new ArithmeticException ( "Storage space and CPT dimension miss match" ) ; DataPoint dp = dataPoint . getDataPoint ( ) ; int skipVal = - 1 ; //Set up cord for ( int i = 0 ; i < dimSize . length ; i ++ ) { if ( realIndexToCatIndex [ i ] == targetClass ) { if ( targetClass == dp . numCategoricalValues ( ) ) skipVal = dataPoint . getPair ( ) ; else skipVal = dp . getCategoricalValue ( realIndexToCatIndex [ i ] ) ; } if ( realIndexToCatIndex [ i ] == predictingIndex ) cord [ i ] = dataPoint . getPair ( ) ; else cord [ i ] = dp . getCategoricalValue ( realIndexToCatIndex [ i ] ) ; } return skipVal ; } | Converts a data point pair into a coordinate . The paired value contains the value for the predicting index . Though this value will not be used if the predicting class of the original data set was not used to make the table . | 228 | 45 |
29,877 | public double query ( int targetClass , int targetValue , int [ ] cord ) { double sumVal = 0 ; double targetVal = 0 ; int realTargetIndex = catIndexToRealIndex [ targetClass ] ; CategoricalData queryData = valid . get ( targetClass ) ; //Now do all other target class posibilty querys for ( int i = 0 ; i < queryData . getNumOfCategories ( ) ; i ++ ) { cord [ realTargetIndex ] = i ; double tmp = countArray [ cordToIndex ( cord ) ] ; sumVal += tmp ; if ( i == targetValue ) targetVal = tmp ; } return targetVal / sumVal ; } | Queries the CPT for the probability of the target class occurring with the specified value given the class values of the other attributes | 145 | 25 |
29,878 | public static Map < String , Parameter > toParameterMap ( List < Parameter > params ) { Map < String , Parameter > map = new HashMap < String , Parameter > ( params . size ( ) ) ; for ( Parameter param : params ) { if ( map . put ( param . getASCIIName ( ) , param ) != null ) throw new RuntimeException ( "Name collision, two parameters use the name '" + param . getASCIIName ( ) + "'" ) ; if ( ! param . getName ( ) . equals ( param . getASCIIName ( ) ) ) //Dont put it in again if ( map . put ( param . getName ( ) , param ) != null ) throw new RuntimeException ( "Name collision, two parameters use the name '" + param . getName ( ) + "'" ) ; } return map ; } | Creates a map of all possible parameter names to their corresponding object . No two parameters may have the same name . | 189 | 23 |
29,879 | private static String spaceCamelCase ( String in ) { StringBuilder sb = new StringBuilder ( in . length ( ) + 5 ) ; for ( int i = 0 ; i < in . length ( ) ; i ++ ) { char c = in . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) sb . append ( ' ' ) ; sb . append ( c ) ; } return sb . toString ( ) . trim ( ) ; } | Returns a version of the same string that has spaced inserted before each capital letter | 104 | 15 |
29,880 | public static Distribution guessNumberOfBins ( DataSet data ) { if ( data . size ( ) < 20 ) return new UniformDiscrete ( 2 , data . size ( ) - 1 ) ; else if ( data . size ( ) >= 1000000 ) return new LogUniform ( 50 , 1000 ) ; int sqrt = ( int ) Math . sqrt ( data . size ( ) ) ; return new UniformDiscrete ( Math . max ( sqrt / 3 , 2 ) , Math . min ( sqrt * 3 , data . size ( ) - 1 ) ) ; } | Attempts to guess the number of bins to use | 121 | 9 |
29,881 | private SingularValueDecomposition getSVD ( DataSet dataSet ) { Matrix cov = covarianceMatrix ( meanVector ( dataSet ) , dataSet ) ; for ( int i = 0 ; i < cov . rows ( ) ; i ++ ) //force it to be symmetric for ( int j = 0 ; j < i ; j ++ ) cov . set ( j , i , cov . get ( i , j ) ) ; EigenValueDecomposition evd = new EigenValueDecomposition ( cov ) ; //Sort form largest to smallest evd . sortByEigenValue ( new Comparator < Double > ( ) { @ Override public int compare ( Double o1 , Double o2 ) { return - Double . compare ( o1 , o2 ) ; } } ) ; return new SingularValueDecomposition ( evd . getVRaw ( ) , evd . getVRaw ( ) , evd . getRealEigenvalues ( ) ) ; } | Gets a SVD for the covariance matrix of the data set | 209 | 14 |
29,882 | public double backwardNaive ( int n , double ... args ) { double term = getA ( n , args ) / getB ( n , args ) ; for ( n = n - 1 ; n > 0 ; n -- ) { term = getA ( n , args ) / ( getB ( n , args ) + term ) ; } return term + getB ( 0 , args ) ; } | Approximates the continued fraction using a naive approximation | 84 | 10 |
29,883 | public double lentz ( double ... args ) { double f_n = getB ( 0 , args ) ; if ( f_n == 0.0 ) f_n = 1e-30 ; double c_n , c_0 = f_n ; double d_n , d_0 = 0 ; double delta = 0 ; int j = 0 ; while ( Math . abs ( delta - 1 ) > 1e-15 ) { j ++ ; d_n = getB ( j , args ) + getA ( j , args ) * d_0 ; if ( d_n == 0.0 ) d_n = 1e-30 ; c_n = getB ( j , args ) + getA ( j , args ) / c_0 ; if ( c_n == 0.0 ) c_n = 1e-30 ; d_n = 1 / d_n ; delta = c_n * d_n ; f_n *= delta ; d_0 = d_n ; c_0 = c_n ; } return f_n ; } | Uses Thompson and Barnett s modified Lentz s algorithm create an approximation that should be accurate to full precision . | 232 | 22 |
29,884 | public static List < List < DataPoint > > createClusterListFromAssignmentArray ( int [ ] assignments , DataSet dataSet ) { List < List < DataPoint >> clusterings = new ArrayList <> ( ) ; for ( int i = 0 ; i < dataSet . size ( ) ; i ++ ) { while ( clusterings . size ( ) <= assignments [ i ] ) clusterings . add ( new ArrayList <> ( ) ) ; if ( assignments [ i ] >= 0 ) clusterings . get ( assignments [ i ] ) . add ( dataSet . getDataPoint ( i ) ) ; } return clusterings ; } | Convenient helper method . A list of lists to represent a cluster may be desirable . In such a case this method will take in an array of cluster assignments and return a list of lists . | 135 | 38 |
29,885 | public static List < DataPoint > getDatapointsFromCluster ( int c , int [ ] assignments , DataSet dataSet , int [ ] indexFrom ) { List < DataPoint > list = new ArrayList <> ( ) ; int pos = 0 ; for ( int i = 0 ; i < dataSet . size ( ) ; i ++ ) if ( assignments [ i ] == c ) { list . add ( dataSet . getDataPoint ( i ) ) ; if ( indexFrom != null ) indexFrom [ pos ++ ] = i ; } return list ; } | Gets a list of the datapoints in a data set that belong to the indicated cluster | 121 | 20 |
29,886 | public Complex add ( Complex c ) { Complex ret = new Complex ( real , imag ) ; ret . mutableAdd ( c ) ; return ret ; } | Creates a new complex number containing the resulting addition of this and another | 32 | 14 |
29,887 | public Complex subtract ( Complex c ) { Complex ret = new Complex ( real , imag ) ; ret . mutableSubtract ( c ) ; return ret ; } | Creates a new complex number containing the resulting subtracting another from this one | 34 | 15 |
29,888 | public static void cMul ( double a , double b , double c , double d , double [ ] results ) { results [ 0 ] = a * c - b * d ; results [ 1 ] = b * c + a * d ; } | Performs a complex multiplication | 52 | 5 |
29,889 | public void mutableMultiply ( double c , double d ) { double newR = this . real * c - this . imag * d ; double newI = this . imag * c + this . real * d ; this . real = newR ; this . imag = newI ; } | Alters this complex number as if a multiplication of another complex number was performed . | 62 | 16 |
29,890 | public Complex multiply ( Complex c ) { Complex ret = new Complex ( real , imag ) ; ret . mutableMultiply ( c ) ; return ret ; } | Creates a new complex number containing the resulting multiplication between this and another | 34 | 14 |
29,891 | public void mutableDivide ( double c , double d ) { final double [ ] r = new double [ 2 ] ; cDiv ( real , imag , c , d , r ) ; this . real = r [ 0 ] ; this . imag = r [ 1 ] ; } | Alters this complex number as if a division by another complex number was performed . | 59 | 16 |
29,892 | public Complex divide ( Complex c ) { Complex ret = new Complex ( real , imag ) ; ret . mutableDivide ( c ) ; return ret ; } | Creates a new complex number containing the resulting division of this by another | 33 | 14 |
29,893 | public void setDelta ( double delta ) { if ( delta <= 0 || delta >= 1 || Double . isNaN ( delta ) ) throw new IllegalArgumentException ( "delta must be in (0,1), not " + delta ) ; this . delta = delta ; } | Sets the upper bound on the false positive rate for detecting concept drifts | 59 | 15 |
29,894 | private void compress ( ) { //compress ListIterator < OnLineStatistics > listIter = windows . listIterator ( ) ; double lastSizeSeen = - Double . MAX_VALUE ; int lastSizeCount = 0 ; while ( listIter . hasNext ( ) ) { OnLineStatistics window = listIter . next ( ) ; double n = window . getSumOfWeights ( ) ; if ( n == lastSizeSeen ) { if ( ++ lastSizeCount > M ) //compress, can only occur if there is a previous { listIter . previous ( ) ; window . add ( listIter . previous ( ) ) ; listIter . remove ( ) ; //remove the preivous if ( listIter . hasNext ( ) ) listIter . next ( ) ; //back to where we were, which has been modified //so nowe we must be looking at a new range since we just promoted a window lastSizeSeen = window . getSumOfWeights ( ) ; lastSizeCount = 1 ; } } else { lastSizeSeen = n ; lastSizeCount = 1 ; } } } | Compresses the current window | 233 | 5 |
29,895 | private void computeSubClusterSplit ( final int [ ] [ ] subDesignation , int originalCluster , List < DataPoint > listOfDataPointsInCluster , DataSet fullDataSet , int [ ] fullDesignations , final int [ ] [ ] originalPositions , final double [ ] splitEvaluation , PriorityQueue < Integer > clusterToSplit , boolean parallel ) { subDesignation [ originalCluster ] = new int [ listOfDataPointsInCluster . size ( ) ] ; int pos = 0 ; for ( int i = 0 ; i < fullDataSet . size ( ) ; i ++ ) { if ( fullDesignations [ i ] != originalCluster ) continue ; originalPositions [ originalCluster ] [ pos ++ ] = i ; } //Cluster the sub cluster SimpleDataSet dpSubC1DataSet = new SimpleDataSet ( listOfDataPointsInCluster ) ; try { baseClusterer . cluster ( dpSubC1DataSet , 2 , parallel , subDesignation [ originalCluster ] ) ; splitEvaluation [ originalCluster ] = clusterEvaluation . evaluate ( subDesignation [ originalCluster ] , dpSubC1DataSet ) ; clusterToSplit . add ( originalCluster ) ; } catch ( ClusterFailureException ex ) { splitEvaluation [ originalCluster ] = Double . POSITIVE_INFINITY ; } } | Takes the data set and computes the clustering of a sub cluster and stores its information and places the result in the queue | 302 | 26 |
29,896 | public static double sampleCorCoeff ( Vec xData , Vec yData ) { if ( yData . length ( ) != xData . length ( ) ) throw new ArithmeticException ( "X and Y data sets must have the same length" ) ; double xMean = xData . mean ( ) ; double yMean = yData . mean ( ) ; double topSum = 0 ; for ( int i = 0 ; i < xData . length ( ) ; i ++ ) { topSum += ( xData . get ( i ) - xMean ) * ( yData . get ( i ) - yMean ) ; } return topSum / ( ( xData . length ( ) - 1 ) * xData . standardDeviation ( ) * yData . standardDeviation ( ) ) ; } | Computes the sample correlation coefficient for two data sets X and Y . The lengths of X and Y must be the same and each element in X should correspond to the element in Y . | 172 | 37 |
29,897 | public void setRange ( double A , double B ) { if ( A == B ) throw new RuntimeException ( "Values must be different" ) ; else if ( B > A ) { double tmp = A ; A = B ; B = tmp ; } this . A = A ; this . B = B ; } | Sets the min and max value to scale the data to . If given in the wrong order this method will swap them | 66 | 24 |
29,898 | private double queryWork ( Vec x , Set < Integer > validIndecies , SparseVector logProd ) { if ( originalVecs == null ) throw new UntrainedModelException ( "Model has not yet been created, queries can not be perfomed" ) ; double logH = 0 ; for ( int i = 0 ; i < sortedDimVals . length ; i ++ ) { double [ ] X = sortedDimVals [ i ] ; double h = bandwidth [ i ] ; logH += log ( h ) ; double xi = x . get ( i ) ; //Only values within a certain range will have an effect on the result, so we will skip to that range! int from = Arrays . binarySearch ( X , xi - h * k . cutOff ( ) ) ; int to = Arrays . binarySearch ( X , xi + h * k . cutOff ( ) ) ; //Mostly likely the exact value of x is not in the list, so it retursn the inseration points from = from < 0 ? - from - 1 : from ; to = to < 0 ? - to - 1 : to ; Set < Integer > subIndecies = new IntSet ( ) ; for ( int j = max ( 0 , from ) ; j < min ( X . length , to + 1 ) ; j ++ ) { int trueIndex = sortedIndexVals [ i ] [ j ] ; if ( i == 0 ) { validIndecies . add ( trueIndex ) ; logProd . set ( trueIndex , log ( k . k ( ( xi - X [ j ] ) / h ) ) ) ; } else if ( validIndecies . contains ( trueIndex ) ) { logProd . increment ( trueIndex , log ( k . k ( ( xi - X [ j ] ) / h ) ) ) ; subIndecies . add ( trueIndex ) ; } } if ( i > 0 ) { validIndecies . retainAll ( subIndecies ) ; if ( validIndecies . isEmpty ( ) ) break ; } } return logH ; } | Performs the main work for performing a density query . | 454 | 11 |
29,899 | static private < T > void fillList ( final int listsToAdd , Stack < List < T > > reusableLists , List < List < T > > aSplit ) { for ( int j = 0 ; j < listsToAdd ; j ++ ) if ( reusableLists . isEmpty ( ) ) aSplit . add ( new ArrayList <> ( ) ) ; else aSplit . add ( reusableLists . pop ( ) ) ; } | Add lists to a list of lists | 94 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.