idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
38,400
|
public Set < String > getNames ( ) { if ( parent == null ) { return getLocalNames ( ) ; } Set < String > result = new TreeSet < > ( ) ; result . addAll ( parent . getNames ( ) ) ; result . addAll ( getLocalNames ( ) ) ; return result ; }
|
Returns all names of variables known to this scope or one of its parent scopes .
|
38,401
|
public Collection < Variable > getVariables ( ) { if ( parent == null ) { return getLocalVariables ( ) ; } List < Variable > result = new ArrayList < > ( ) ; result . addAll ( parent . getVariables ( ) ) ; result . addAll ( getLocalVariables ( ) ) ; return result ; }
|
Returns all variables known to this scope or one of its parent scopes .
|
38,402
|
public static < T > T ifNull ( final T reference , final T defaultValue ) { if ( reference == null ) { return defaultValue ; } return reference ; }
|
If our reference is null then return a default value instead .
|
38,403
|
private Buffer consumeUntil ( final Buffer name ) { try { while ( this . params . hasReadableBytes ( ) ) { SipParser . consumeSEMI ( this . params ) ; final Buffer [ ] keyValue = SipParser . consumeGenericParam ( this . params ) ; ensureParamsMap ( ) ; final Buffer value = keyValue [ 1 ] == null ? Buffers . EMPTY_BUFFER : keyValue [ 1 ] ; this . paramMap . put ( keyValue [ 0 ] , value ) ; if ( name != null && name . equals ( keyValue [ 0 ] ) ) { return value ; } } return null ; } catch ( final IndexOutOfBoundsException e ) { throw new SipParseException ( this . params . getReaderIndex ( ) , "Unable to process the value due to a IndexOutOfBoundsException" , e ) ; } catch ( final IOException e ) { throw new SipParseException ( this . params . getReaderIndex ( ) , "Could not read from the underlying stream while parsing the value" ) ; } }
|
Internal helper method that will consume all raw parameters until we find the specified name or if the name is null then that will be the same as consume all .
|
38,404
|
private void ensureParams ( ) { if ( this . isDirty ) { final Buffer restOfParams = this . params ; this . params = allcoateNewParamBuffer ( ) ; for ( final Map . Entry < Buffer , Buffer > entry : this . paramMap . entrySet ( ) ) { this . params . write ( SipParser . SEMI ) ; final Buffer key = entry . getKey ( ) ; final Buffer value = entry . getValue ( ) ; key . getBytes ( 0 , this . params ) ; if ( value != null && ! value . isEmpty ( ) ) { this . params . write ( SipParser . EQ ) ; value . getBytes ( 0 , this . params ) ; } } this . paramMap . clear ( ) ; restOfParams . getBytes ( this . params ) ; this . originalParams = this . params . slice ( ) ; this . isDirty = false ; } }
|
Make sure that the internal params buffer is actually valid etc .
|
38,405
|
public static void basicExample001 ( ) throws IOException { final String rawMessage = new StringBuilder ( "BYE sip:bob@127.0.0.1:5060 SIP/2.0\r\n" ) . append ( "Via: SIP/2.0/UDP 127.0.1.1:5061;branch=z9hG4bK-28976-1-7\r\n" ) . append ( "From: alice <sip:alice@127.0.1.1:5061>;tag=28976SIPpTag001\r\n" ) . append ( "To: bob <sip:bob@127.0.0.1:5060>;tag=28972SIPpTag011\r\n" ) . append ( "Call-ID: 1-28976@127.0.1.1\r\n" ) . append ( "CSeq: 2 BYE\r\n" ) . append ( "Contact: sip:alice@127.0.1.1:5061\r\n" ) . append ( "Max-Forwards: 70\r\n" ) . append ( "Subject: Example BYE Message\r\n" ) . append ( "Content-Length: 0\r\n" ) . append ( "\r\n" ) . toString ( ) ; final SipMessage msg = SipMessage . frame ( rawMessage ) ; final FromHeader from = msg . getFromHeader ( ) ; final ContactHeader contact = msg . getContactHeader ( ) ; if ( msg . isBye ( ) ) { System . out . println ( "Yay, this was a BYE message" ) ; } if ( msg . isRequest ( ) ) { System . out . println ( "Yay, this was SIP request" ) ; } }
|
This is the most basic example showing how you can parse a SIP message based off of a String . In this example we are the ones creating that raw message ourselves but typically you would read this off of the network or perhaps from a file if you are building a tool of some sort .
|
38,406
|
public static void basicExample003 ( ) throws Exception { final SipRequest invite = SipRequest . invite ( "sip:alice@aboutsip.com" ) . withFromHeader ( "sip:bob@pkts.io" ) . build ( ) ; final SipResponse response = invite . createResponse ( 200 ) . withHeader ( SipHeader . create ( "X-Hello" , "World" ) ) . build ( ) ; System . out . println ( response ) ; }
|
Creating responses is typically done based off a request and SIP Lib allows you to do so but of course the object returned will be a builder .
|
38,407
|
private void init ( ) { this . currentState = CallState . START ; this . callTransitions = new ArrayList < CallState > ( ) ; this . messages = new TreeSet < SipPacket > ( new PacketComparator ( ) ) ; }
|
Start over from a clean slate ...
|
38,408
|
private void handleInCancellingState ( final SipPacket msg ) throws SipPacketParseException { if ( msg . isCancel ( ) ) { transition ( CallState . CANCELLING , msg ) ; return ; } if ( msg . isRequest ( ) ) { } else { final SipResponsePacket response = msg . toResponse ( ) ; if ( response . isInvite ( ) ) { if ( response . getStatus ( ) == 487 ) { transition ( CallState . CANCELLED , msg ) ; } else if ( response . isSuccess ( ) ) { transition ( CallState . IN_CALL , msg ) ; } } } }
|
When in the cancelling state we may actually end up going back to IN_CALL in case we see a 2xx to the invite so pay attention for that .
|
38,409
|
private void handleInCompletedState ( final SipPacket msg ) throws SipPacketParseException { if ( msg . isRequest ( ) ) { } else { if ( msg . isBye ( ) ) { transition ( CallState . COMPLETED , msg ) ; } } }
|
Handle state transitions for when we are already in the completed state .
|
38,410
|
private void handleInConfirmedState ( final SipPacket msg ) throws SipPacketParseException { if ( msg . isRequest ( ) ) { if ( msg . isBye ( ) ) { if ( this . byeRequest == null ) { this . byeRequest = msg . toRequest ( ) ; } transition ( CallState . COMPLETED , msg ) ; } else if ( msg . isAck ( ) ) { this . handshakeIsComplete = true ; transition ( CallState . IN_CALL , msg ) ; } } else { final SipResponsePacket response = ( SipResponsePacket ) msg ; if ( response . isSuccess ( ) ) { this . reTransmisionsDetected = true ; } else if ( response . isBye ( ) ) { } } }
|
We will only get to the confirmed state on a 2xx response to the INVITE . From here we can stay in the confirmed state if we get an ACK or transition over to completed if we get a BYE request .
|
38,411
|
private void transition ( final CallState nextState , final SipPacket msg ) { final CallState previousState = this . currentState ; this . currentState = nextState ; if ( previousState != nextState ) { this . callTransitions . add ( nextState ) ; } if ( logger . isInfoEnabled ( ) ) { logger . info ( "[{}] {} -> {} Event: {}" , this . callId , previousState , this . currentState , msg . getInitialLine ( ) ) ; } }
|
Helper method for doing transitions .
|
38,412
|
private void setMacAddress ( final String macAddress , final boolean setSourceMacAddress ) throws IllegalArgumentException { if ( macAddress == null || macAddress . isEmpty ( ) ) { throw new IllegalArgumentException ( "Null or empty string cannot be a valid MAC Address." ) ; } final String [ ] segments = macAddress . split ( ":" ) ; if ( segments . length != 6 ) { throw new IllegalArgumentException ( "Invalid MAC Address. Not enough segments" ) ; } final int offset = setSourceMacAddress ? 6 : 0 ; for ( int i = 0 ; i < 6 ; ++ i ) { final byte b = ( byte ) ( ( Character . digit ( segments [ i ] . charAt ( 0 ) , 16 ) << 4 ) + Character . digit ( segments [ i ] . charAt ( 1 ) , 16 ) ) ; this . headers . setByte ( i + offset , b ) ; } }
|
Helper method for setting the mac address in the header buffer .
|
38,413
|
private int calculateChecksum ( ) { long sum = 0 ; for ( int i = 0 ; i < this . headers . capacity ( ) - 1 ; i += 2 ) { if ( i != 10 ) { sum += this . headers . getUnsignedShort ( i ) ; } } while ( sum >> 16 != 0 ) { sum = ( sum & 0xffff ) + ( sum >> 16 ) ; } return ( int ) ~ sum & 0xFFFF ; }
|
Algorithm adopted from RFC 1071 - Computing the Internet Checksum
|
38,414
|
private void setIP ( final int startIndex , final String address ) { final String [ ] parts = address . split ( "\\." ) ; this . headers . setByte ( startIndex + 0 , ( byte ) Integer . parseInt ( parts [ 0 ] ) ) ; this . headers . setByte ( startIndex + 1 , ( byte ) Integer . parseInt ( parts [ 1 ] ) ) ; this . headers . setByte ( startIndex + 2 , ( byte ) Integer . parseInt ( parts [ 2 ] ) ) ; this . headers . setByte ( startIndex + 3 , ( byte ) Integer . parseInt ( parts [ 3 ] ) ) ; reCalculateChecksum ( ) ; }
|
Very naive initial implementation . Should be changed to do a better job and its performance probably can go up a lot as well .
|
38,415
|
public int getHeaderLength ( ) { try { final byte b = this . headers . getByte ( 0 ) ; return ( b & 0x0F ) * 4 ; } catch ( final IOException e ) { throw new RuntimeException ( "unable to get the header length of the IP packet due to IOException" , e ) ; } }
|
The length of the ipv4 headers
|
38,416
|
public static Function < SipHeader , ? extends SipHeader > getFramer ( final Buffer b ) { final Function < SipHeader , ? extends SipHeader > framer = framers . get ( b ) ; if ( framer != null ) { return framer ; } for ( Map . Entry < Buffer , Function < SipHeader , ? extends SipHeader > > entry : framers . entrySet ( ) ) { if ( entry . getKey ( ) . equalsIgnoreCase ( b ) ) { return entry . getValue ( ) ; } } return null ; }
|
For the given header name return a function that will convert a generic header instance into one with the correct subtype .
|
38,417
|
public static boolean isUDP ( final Buffer t ) { try { return t . capacity ( ) == 3 && t . getByte ( 0 ) == 'U' && t . getByte ( 1 ) == 'D' && t . getByte ( 2 ) == 'P' ; } catch ( final IOException e ) { return false ; } }
|
Check whether the buffer is exactly three bytes long and has the bytes UDP in it .
|
38,418
|
public static boolean isUDPLower ( final Buffer t ) { try { return t . capacity ( ) == 3 && t . getByte ( 0 ) == 'u' && t . getByte ( 1 ) == 'd' && t . getByte ( 2 ) == 'p' ; } catch ( final IOException e ) { return false ; } }
|
Check whether the buffer is exactly three bytes long and has the bytes udp in it . Note in SIP there is a different between transport specified in a Via - header and a transport - param specified in a SIP URI . One is upper case one is lower case . Another really annoying thing with SIP .
|
38,419
|
public static boolean isNext ( final Buffer buffer , final byte b ) throws IOException { if ( buffer . hasReadableBytes ( ) ) { final byte actual = buffer . peekByte ( ) ; return actual == b ; } return false ; }
|
Will check whether the next readable byte in the buffer is a certain byte
|
38,420
|
public static boolean isNextDigit ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { if ( buffer . hasReadableBytes ( ) ) { final char next = ( char ) buffer . peekByte ( ) ; return next >= 48 && next <= 57 ; } return false ; }
|
Check whether the next byte is a digit or not
|
38,421
|
public static Buffer expectDigit ( final Buffer buffer ) throws SipParseException { final int start = buffer . getReaderIndex ( ) ; try { while ( buffer . hasReadableBytes ( ) && isNextDigit ( buffer ) ) { buffer . readByte ( ) ; } if ( start == buffer . getReaderIndex ( ) ) { throw new SipParseException ( start , "Expected digit" ) ; } return buffer . slice ( start , buffer . getReaderIndex ( ) ) ; } catch ( final IndexOutOfBoundsException e ) { throw new SipParseException ( start , "Expected digit but no more bytes to read" ) ; } catch ( final IOException e ) { throw new SipParseException ( start , "Expected digit unable to read from underlying stream" ) ; } }
|
Will expect at least 1 digit and will continue consuming bytes until a non - digit is encountered
|
38,422
|
public static int expectWS ( final Buffer buffer ) throws SipParseException { int consumed = 0 ; try { if ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . getByte ( buffer . getReaderIndex ( ) ) ; if ( b == SP || b == HTAB ) { buffer . readByte ( ) ; ++ consumed ; } else { throw new SipParseException ( buffer . getReaderIndex ( ) , "Expected WS" ) ; } } else { throw new SipParseException ( buffer . getReaderIndex ( ) , "Expected WS but nothing more to read in the buffer" ) ; } } catch ( final IOException e ) { throw new SipParseException ( buffer . getReaderIndex ( ) , UNABLE_TO_READ_FROM_STREAM , e ) ; } return consumed ; }
|
Expect the next byte to be a white space
|
38,423
|
public static Buffer consumeAlphaNum ( final Buffer buffer ) throws IOException { final int count = getAlphaNumCount ( buffer ) ; if ( count == 0 ) { return null ; } return buffer . readBytes ( count ) ; }
|
Consumes a alphanum .
|
38,424
|
public static int getAlphaNumCount ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { boolean done = false ; int count = 0 ; final int index = buffer . getReaderIndex ( ) ; while ( buffer . hasReadableBytes ( ) && ! done ) { final byte b = buffer . readByte ( ) ; if ( isAlphaNum ( b ) ) { ++ count ; } else { done = true ; } } buffer . setReaderIndex ( index ) ; return count ; }
|
Helper method that counts the number of bytes that are considered part of the next alphanum block .
|
38,425
|
public static boolean isNextAlphaNum ( final Buffer buffer ) throws IndexOutOfBoundsException , IOException { if ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . peekByte ( ) ; return isAlphaNum ( b ) ; } return false ; }
|
Check whether next byte is a alpha numeric one .
|
38,426
|
public static boolean isHostPortCharacter ( final char ch ) { return isAlphaNum ( ch ) || ch == DASH || ch == PERIOD || ch == COLON ; }
|
Checks whether the character could be part of the host portion of a SIP URI .
|
38,427
|
public static int consumeCRLF ( final Buffer buffer ) throws SipParseException { try { buffer . markReaderIndex ( ) ; final byte cr = buffer . readByte ( ) ; final byte lf = buffer . readByte ( ) ; if ( cr == CR && lf == LF ) { return 2 ; } } catch ( final IndexOutOfBoundsException e ) { } catch ( final IOException e ) { throw new SipParseException ( buffer . getReaderIndex ( ) , UNABLE_TO_READ_FROM_STREAM , e ) ; } buffer . resetReaderIndex ( ) ; return 0 ; }
|
Consume CR + LF
|
38,428
|
private static boolean isHeaderAllowingMultipleValues ( final Buffer headerName ) { final int size = headerName . getReadableBytes ( ) ; if ( size == 7 ) { return ! isSubjectHeader ( headerName ) ; } else if ( size == 5 ) { return ! isAllowHeader ( headerName ) ; } else if ( size == 4 ) { return ! isDateHeader ( headerName ) ; } else if ( size == 1 ) { return ! isAllowEventsHeaderShort ( headerName ) ; } else if ( size == 12 ) { return ! isAllowEventsHeader ( headerName ) ; } return true ; }
|
Not all headers allow for multiple values on a single line . This is a basic check for validating whether or not that the header allows it or not . Note for headers such as Contact it depends!
|
38,429
|
private static boolean isDateHeader ( final Buffer name ) { try { return name . getByte ( 0 ) == 'D' && name . getByte ( 1 ) == 'a' && name . getByte ( 2 ) == 't' && name . getByte ( 3 ) == 'e' ; } catch ( final IOException e ) { return false ; } }
|
The date header also allows for comma within the value of the header .
|
38,430
|
public static SipHeader nextHeader ( final Buffer buffer ) throws SipParseException { try { final int startIndex = buffer . getReaderIndex ( ) ; int nameIndex = 0 ; while ( buffer . hasReadableBytes ( ) && nameIndex == 0 ) { if ( isNext ( buffer , SP ) || isNext ( buffer , HTAB ) || isNext ( buffer , COLON ) ) { nameIndex = buffer . getReaderIndex ( ) ; } else { buffer . readByte ( ) ; } } if ( nameIndex == 0 ) { return null ; } final Buffer name = buffer . slice ( startIndex , nameIndex ) ; expectHCOLON ( buffer ) ; Buffer valueBuffer = buffer . readLine ( ) ; if ( isNext ( buffer , SP ) || isNext ( buffer , HTAB ) ) { List < Buffer > foldedLines = null ; boolean done = false ; while ( ! done ) { if ( isNext ( buffer , SP ) || isNext ( buffer , HTAB ) ) { consumeWS ( buffer ) ; if ( foldedLines == null ) { foldedLines = new ArrayList < Buffer > ( 2 ) ; } foldedLines . add ( buffer . readLine ( ) ) ; } else { done = true ; } } if ( foldedLines != null ) { String stupid = valueBuffer . toString ( ) ; for ( final Buffer line : foldedLines ) { stupid += " " + line . toString ( ) ; } valueBuffer = Buffers . wrap ( stupid . getBytes ( Charset . forName ( "UTF-8" ) ) ) ; consumeWS ( valueBuffer ) ; } } return new SipHeaderImpl ( name , valueBuffer ) ; } catch ( final IOException e ) { throw new SipParseException ( buffer . getReaderIndex ( ) , UNABLE_TO_READ_FROM_STREAM , e ) ; } }
|
Get the next header which may actually be returning multiple if there are multiple headers on the same line .
|
38,431
|
public static Buffer wrap ( final byte [ ] buffer ) { if ( buffer == null || buffer . length == 0 ) { throw new IllegalArgumentException ( "the buffer cannot be null or empty" ) ; } return new ByteBuffer ( buffer ) ; }
|
Wrap the supplied byte array
|
38,432
|
public static Buffer wrap ( final Buffer one , final Buffer two ) { final int size1 = one != null ? one . getReadableBytes ( ) : 0 ; final int size2 = two != null ? two . getReadableBytes ( ) : 0 ; if ( size1 == 0 && size2 > 0 ) { return two . slice ( ) ; } else if ( size2 == 0 && size1 > 0 ) { return one . slice ( ) ; } else if ( size2 == 0 && size1 == 0 ) { return Buffers . EMPTY_BUFFER ; } final Buffer composite = Buffers . createBuffer ( size1 + size2 ) ; one . getBytes ( composite ) ; two . getBytes ( composite ) ; return composite ; }
|
Combine two buffers into one . The resulting buffer will share the underlying byte storage so changing the value in one will affect the other . However the original two buffers will still have their own reader and writer index .
|
38,433
|
public static Buffer wrap ( final byte [ ] buffer , final int lowerBoundary , final int upperBoundary ) { if ( buffer == null || buffer . length == 0 ) { throw new IllegalArgumentException ( "the buffer cannot be null or empty" ) ; } if ( upperBoundary > buffer . length ) { throw new IllegalArgumentException ( "The upper boundary cannot exceed the length of the buffer" ) ; } if ( lowerBoundary >= upperBoundary ) { throw new IllegalArgumentException ( "The lower boundary must be lower than the upper boundary" ) ; } if ( lowerBoundary < 0 ) { throw new IllegalArgumentException ( "The lower boundary must be a equal or greater than zero" ) ; } final int readerIndex = 0 ; final int writerIndex = upperBoundary ; return new ByteBuffer ( readerIndex , lowerBoundary , upperBoundary , writerIndex , buffer ) ; }
|
Wrap the supplied byte array specifying the allowed range of visible bytes .
|
38,434
|
public void write ( final OutputStream out ) throws IOException { if ( this . byteOrder == ByteOrder . BIG_ENDIAN ) { out . write ( MAGIC_BIG_ENDIAN ) ; } else { out . write ( MAGIC_LITTLE_ENDIAN ) ; } out . write ( this . body ) ; }
|
Will write this header to the output stream .
|
38,435
|
public static PcapRecordHeader createDefaultHeader ( final long timestamp ) { final byte [ ] body = new byte [ SIZE ] ; final Buffer buffer = Buffers . wrap ( body ) ; buffer . setUnsignedInt ( 0 , timestamp / 1000L ) ; buffer . setUnsignedInt ( 4 , timestamp % 1000L * 1000L ) ; return new PcapRecordHeader ( ByteOrder . LITTLE_ENDIAN , buffer ) ; }
|
Create a default record header which you must alter later on to match whatever it is you are writing into the pcap stream .
|
38,436
|
public boolean process ( final byte [ ] newData ) { if ( newData != null ) { buffer . write ( newData ) ; } boolean done = false ; while ( ! done ) { final int index = buffer . getReaderIndex ( ) ; final State currentState = state ; state = actions [ state . ordinal ( ) ] . apply ( buffer ) ; done = state == currentState && buffer . getReaderIndex ( ) == index ; } return state == State . DONE ; }
|
Process more incoming data .
|
38,437
|
private final State onInit ( final Buffer buffer ) { try { while ( buffer . hasReadableBytes ( ) ) { final byte b = buffer . peekByte ( ) ; if ( b == SipParser . SP || b == SipParser . HTAB || b == SipParser . CR || b == SipParser . LF ) { buffer . readByte ( ) ; } else { start = buffer . getReaderIndex ( ) ; return State . GET_INITIAL_LINE ; } } } catch ( final IOException e ) { throw new RuntimeException ( "Unable to read from stream due to IOException" , e ) ; } return State . INIT ; }
|
While in the INIT state we are just consuming any empty space before heading off to start parsing the initial line
|
38,438
|
private final State onInitialLine ( final Buffer buffer ) { try { buffer . markReaderIndex ( ) ; final Buffer part1 = buffer . readUntilSafe ( config . getMaxAllowedInitialLineSize ( ) , SipParser . SP ) ; final Buffer part2 = buffer . readUntilSafe ( config . getMaxAllowedInitialLineSize ( ) , SipParser . SP ) ; final Buffer part3 = buffer . readUntilSingleCRLF ( ) ; if ( part1 == null || part2 == null || part3 == null ) { buffer . resetReaderIndex ( ) ; return State . GET_INITIAL_LINE ; } sipInitialLine = SipInitialLine . parse ( part1 , part2 , part3 ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Unable to read from stream due to IOException" , e ) ; } return State . GET_HEADER_NAME ; }
|
Since it is quite uncommon to not have enough data on the line to read the entire first line we are taking the simple approach of just resetting the entire effort and we ll retry later . This of course means that in the worst case scenario we will actually iterate over data we have already seen before . However seemed like it is worth it instead of having the extra space for keeping track of the extra state .
|
38,439
|
private final State onCheckEndHeaderSection ( final Buffer buffer ) { if ( buffer . getReadableBytes ( ) < 2 ) { return State . CHECK_FOR_END_OF_HEADER_SECTION ; } if ( SipParser . consumeCRLF ( buffer ) == 2 ) { return State . GET_PAYLOAD ; } return State . GET_HEADER_NAME ; }
|
Every time we have parsed a header we need to check if there are more headers or if we have reached the end of the section and as such there may be a body we need to take care of . We know this by checking if there is a CRLF up next or not .
|
38,440
|
private final State onPayload ( final Buffer buffer ) { if ( contentLength == 0 ) { return State . DONE ; } if ( buffer . getReadableBytes ( ) >= contentLength ) { try { payload = buffer . readBytes ( contentLength ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Unable to read from stream due to IOException" , e ) ; } return State . DONE ; } return State . GET_PAYLOAD ; }
|
We may or may not have a payload which depends on whether there is a Content - length header available or not . If yes then we will just slice out that entire thing once we have enough readable bytes in the buffer .
|
38,441
|
private java . nio . ByteBuffer getWritingRow ( ) { final int row = this . writerIndex / this . localCapacity ; if ( row >= this . storage . size ( ) ) { final java . nio . ByteBuffer buf = java . nio . ByteBuffer . allocate ( this . localCapacity ) ; this . storage . add ( buf ) ; return buf ; } return this . storage . get ( row ) ; }
|
Get which row we currently are working with for writing
|
38,442
|
private java . nio . ByteBuffer getReadingRow ( ) { final int row = this . readerIndex / this . localCapacity ; return this . storage . get ( row ) ; }
|
Get which row we currently are working with for reading
|
38,443
|
public boolean accept ( final Buffer data ) throws IOException { if ( data . getReadableBytes ( ) < 12 ) { data . markReaderIndex ( ) ; try { final Buffer b = data . readBytes ( 12 ) ; if ( b . capacity ( ) < 12 ) { return false ; } } catch ( final IndexOutOfBoundsException e ) { return false ; } finally { data . resetReaderIndex ( ) ; } } final byte b = data . getByte ( 0 ) ; if ( ! ( ( b & 0xC0 ) >> 6 == 0x02 ) ) { return false ; } final byte b2 = data . getByte ( 1 ) ; if ( b2 == ( byte ) 0xc8 || b2 == ( byte ) 0xc9 || b2 == ( byte ) 0xca || b2 == ( byte ) 0xcb || b2 == ( byte ) 0xcc ) { return false ; } return true ; }
|
There is no real good test to make sure that the data indeed is an RTP packet . Appendix 2 in RFC3550 describes one way of doing it but you really need a sequence of packets in order to be able to determine if this indeed is a RTP packet or not . The best is to analyze the session negotiation but here we are just looking at a single packet so can t do that .
|
38,444
|
public final void write ( final OutputStream out ) throws IOException { if ( this . nextPacket != null ) { this . nextPacket . write ( out ) ; } else { this . write ( out , this . payload ) ; } }
|
The write strategy is fairly simple . If we have a nextPacket it means that we have been asked to frame our payload which also means that that payload may have changed and therefore ask the nextPacket to write itself back out to the stream . If there is no nextPacket we can just take the raw payload and write it out as is since it cannot have changed since we framed this packet .
|
38,445
|
private short addTrackedHeader ( final short index , final SipHeader header ) { if ( index != - 1 ) { headers . set ( index , header . ensure ( ) ) ; return index ; } return addHeader ( header . ensure ( ) ) ; }
|
There are several headers that we want to know their position and in that case we use this method to add them since we want to either add them to a particular position or we want to remember which index we added them to .
|
38,446
|
private < T > Consumer < T > chainConsumers ( final Consumer < T > currentConsumer , final Consumer < T > consumer ) { if ( currentConsumer != null ) { return currentConsumer . andThen ( consumer ) ; } return consumer ; }
|
Helper function to chain consumers together or return the new one if the current consumer isn t set .
|
38,447
|
public EvolutionaryOperator < List < ColouredPolygon > > createEvolutionPipeline ( PolygonImageFactory factory , Dimension canvasSize , Random rng ) { List < EvolutionaryOperator < List < ColouredPolygon > > > operators = new LinkedList < EvolutionaryOperator < List < ColouredPolygon > > > ( ) ; operators . add ( new ListCrossover < ColouredPolygon > ( new ConstantGenerator < Integer > ( 2 ) , crossOverControl . getNumberGenerator ( ) ) ) ; operators . add ( new RemovePolygonMutation ( removePolygonControl . getNumberGenerator ( ) ) ) ; operators . add ( new MovePolygonMutation ( movePolygonControl . getNumberGenerator ( ) ) ) ; operators . add ( new ListOperator < ColouredPolygon > ( new RemoveVertexMutation ( canvasSize , removeVertexControl . getNumberGenerator ( ) ) ) ) ; operators . add ( new ListOperator < ColouredPolygon > ( new AdjustVertexMutation ( canvasSize , moveVertexControl . getNumberGenerator ( ) , new GaussianGenerator ( 0 , 3 , rng ) ) ) ) ; operators . add ( new ListOperator < ColouredPolygon > ( new AddVertexMutation ( canvasSize , addVertexControl . getNumberGenerator ( ) ) ) ) ; operators . add ( new ListOperator < ColouredPolygon > ( new PolygonColourMutation ( changeColourControl . getNumberGenerator ( ) , new GaussianGenerator ( 0 , 20 , rng ) ) ) ) ; operators . add ( new AddPolygonMutation ( addPolygonControl . getNumberGenerator ( ) , factory , 50 ) ) ; return new EvolutionPipeline < List < ColouredPolygon > > ( operators ) ; }
|
Construct the combination of evolutionary operators that will be used to evolve the polygon - based images .
|
38,448
|
private SwingBackgroundTask < List < String > > createTask ( final Collection < String > cities ) { final TravellingSalesmanStrategy strategy = strategyPanel . getStrategy ( ) ; return new SwingBackgroundTask < List < String > > ( ) { private long elapsedTime = 0 ; protected List < String > performTask ( ) { long startTime = System . currentTimeMillis ( ) ; List < String > result = strategy . calculateShortestRoute ( cities , executionPanel ) ; elapsedTime = System . currentTimeMillis ( ) - startTime ; return result ; } protected void postProcessing ( List < String > result ) { executionPanel . appendOutput ( createResultString ( strategy . getDescription ( ) , result , evaluator . getFitness ( result , null ) , elapsedTime ) ) ; setEnabled ( true ) ; } } ; }
|
Helper method to create a background task for running the travelling salesman algorithm .
|
38,449
|
private String createResultString ( String strategyDescription , List < String > shortestRoute , double distance , long elapsedTime ) { StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( '[' ) ; buffer . append ( strategyDescription ) ; buffer . append ( "]\n" ) ; buffer . append ( "ROUTE: " ) ; for ( String s : shortestRoute ) { buffer . append ( s ) ; buffer . append ( " -> " ) ; } buffer . append ( shortestRoute . get ( 0 ) ) ; buffer . append ( '\n' ) ; buffer . append ( "TOTAL DISTANCE: " ) ; buffer . append ( String . valueOf ( distance ) ) ; buffer . append ( "km\n" ) ; buffer . append ( "(Search Time: " ) ; double seconds = ( double ) elapsedTime / 1000 ; buffer . append ( String . valueOf ( seconds ) ) ; buffer . append ( " seconds)\n\n" ) ; return buffer . toString ( ) ; }
|
Helper method for formatting a result as a string for display .
|
38,450
|
public void setEnabled ( boolean b ) { itineraryPanel . setEnabled ( b ) ; strategyPanel . setEnabled ( b ) ; executionPanel . setEnabled ( b ) ; super . setEnabled ( b ) ; }
|
Toggles whether the controls are enabled for input or not .
|
38,451
|
public double getFitness ( String candidate , List < ? extends String > population ) { int errors = 0 ; for ( int i = 0 ; i < candidate . length ( ) ; i ++ ) { if ( candidate . charAt ( i ) != targetString . charAt ( i ) ) { ++ errors ; } } return errors ; }
|
Assigns one penalty point for every character in the candidate string that differs from the corresponding position in the target string .
|
38,452
|
public List < Node > apply ( List < Node > selectedCandidates , Random rng ) { List < Node > evolved = new ArrayList < Node > ( selectedCandidates . size ( ) ) ; for ( Node node : selectedCandidates ) { evolved . add ( probability . nextEvent ( rng ) ? node . simplify ( ) : node ) ; } return evolved ; }
|
Simplify the expressions represented by the candidates . Each expression is simplified according to the configured probability .
|
38,453
|
public < S > List < S > select ( List < EvaluatedCandidate < S > > population , boolean naturalFitnessScores , int selectionSize , Random rng ) { List < S > selection = new ArrayList < S > ( selectionSize ) ; double ratio = selectionRatio . nextValue ( ) ; assert ratio < 1 && ratio > 0 : "Selection ratio out-of-range: " + ratio ; int eligibleCount = ( int ) Math . round ( ratio * population . size ( ) ) ; eligibleCount = eligibleCount > selectionSize ? selectionSize : eligibleCount ; do { int count = Math . min ( eligibleCount , selectionSize - selection . size ( ) ) ; for ( int i = 0 ; i < count ; i ++ ) { selection . add ( population . get ( i ) . getCandidate ( ) ) ; } } while ( selection . size ( ) < selectionSize ) ; return selection ; }
|
Selects the fittest candidates . If the selectionRatio results in fewer selected candidates than required then these candidates are selected multiple times to make up the shortfall .
|
38,454
|
protected void doReplacement ( List < EvaluatedCandidate < T > > existingPopulation , List < EvaluatedCandidate < T > > newCandidates , int eliteCount , Random rng ) { assert newCandidates . size ( ) < existingPopulation . size ( ) - eliteCount : "Too many new candidates for replacement." ; if ( newCandidates . size ( ) > 1 && forceSingleCandidateUpdate ) { existingPopulation . set ( rng . nextInt ( existingPopulation . size ( ) - eliteCount ) + eliteCount , newCandidates . get ( rng . nextInt ( newCandidates . size ( ) ) ) ) ; } else { for ( EvaluatedCandidate < T > candidate : newCandidates ) { existingPopulation . set ( rng . nextInt ( existingPopulation . size ( ) - eliteCount ) + eliteCount , candidate ) ; } } }
|
Add the offspring to the population removing the same number of existing individuals to make space for them . This method randomly chooses which individuals should be replaced but it can be over - ridden in sub - classes if alternative behaviour is required .
|
38,455
|
public Biomorph generateRandomCandidate ( Random rng ) { int [ ] genes = new int [ Biomorph . GENE_COUNT ] ; for ( int i = 0 ; i < Biomorph . GENE_COUNT - 1 ; i ++ ) { genes [ i ] = rng . nextInt ( 11 ) - 5 ; } genes [ Biomorph . LENGTH_GENE_INDEX ] = rng . nextInt ( Biomorph . LENGTH_GENE_MAX ) + 1 ; return new Biomorph ( genes ) ; }
|
Generates a random biomorph by providing a random value for each gene .
|
38,456
|
public static void main ( String [ ] args ) { String target = args . length == 0 ? "HELLO WORLD" : convertArgs ( args ) ; String result = evolveString ( target ) ; System . out . println ( "Evolution result: " + result ) ; }
|
Entry point for the sample application . Any data specified on the command line is considered to be the target String . If no target is specified a default of HELLOW WORLD is used instead .
|
38,457
|
private static String convertArgs ( String [ ] args ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { result . append ( args [ i ] ) ; if ( i < args . length - 1 ) { result . append ( ' ' ) ; } } return result . toString ( ) . toUpperCase ( ) ; }
|
Converts an arguments array into a single String of words separated by spaces .
|
38,458
|
public List < Biomorph > apply ( List < Biomorph > selectedCandidates , Random rng ) { List < Biomorph > mutatedPopulation = new ArrayList < Biomorph > ( selectedCandidates . size ( ) ) ; for ( Biomorph biomorph : selectedCandidates ) { mutatedPopulation . add ( mutateBiomorph ( biomorph , rng ) ) ; } return mutatedPopulation ; }
|
Randomly mutate each selected candidate .
|
38,459
|
private Biomorph mutateBiomorph ( Biomorph biomorph , Random rng ) { int [ ] genes = biomorph . getGenotype ( ) ; assert genes . length == Biomorph . GENE_COUNT : "Biomorphs must have " + Biomorph . GENE_COUNT + " genes." ; for ( int i = 0 ; i < Biomorph . GENE_COUNT - 1 ; i ++ ) { if ( mutationProbability . nextEvent ( rng ) ) { boolean increase = rng . nextBoolean ( ) ; genes [ i ] += ( increase ? 1 : - 1 ) ; if ( genes [ i ] > Biomorph . GENE_MAX ) { genes [ i ] = Biomorph . GENE_MIN ; } else if ( genes [ i ] < Biomorph . GENE_MIN ) { genes [ i ] = Biomorph . GENE_MAX ; } } } boolean increase = rng . nextBoolean ( ) ; genes [ Biomorph . LENGTH_GENE_INDEX ] += ( increase ? 1 : - 1 ) ; if ( genes [ Biomorph . LENGTH_GENE_INDEX ] > Biomorph . LENGTH_GENE_MAX ) { genes [ Biomorph . LENGTH_GENE_INDEX ] = Biomorph . LENGTH_GENE_MIN ; } else if ( genes [ Biomorph . LENGTH_GENE_INDEX ] < Biomorph . LENGTH_GENE_MIN ) { genes [ Biomorph . LENGTH_GENE_INDEX ] = Biomorph . LENGTH_GENE_MAX ; } return new Biomorph ( genes ) ; }
|
Mutates a single biomorph .
|
38,460
|
private Node makeNode ( Random rng , int maxDepth ) { if ( functionProbability . nextEvent ( rng ) && maxDepth > 1 ) { int depth = maxDepth - 1 ; switch ( rng . nextInt ( 5 ) ) { case 0 : return new Addition ( makeNode ( rng , depth ) , makeNode ( rng , depth ) ) ; case 1 : return new Subtraction ( makeNode ( rng , depth ) , makeNode ( rng , depth ) ) ; case 2 : return new Multiplication ( makeNode ( rng , depth ) , makeNode ( rng , depth ) ) ; case 3 : return new IfThenElse ( makeNode ( rng , depth ) , makeNode ( rng , depth ) , makeNode ( rng , depth ) ) ; default : return new IsGreater ( makeNode ( rng , depth ) , makeNode ( rng , depth ) ) ; } } else if ( parameterProbability . nextEvent ( rng ) ) { return new Parameter ( rng . nextInt ( parameterCount ) ) ; } else { return new Constant ( rng . nextInt ( 11 ) ) ; } }
|
Recursively constructs a tree of Nodes up to the specified maximum depth .
|
38,461
|
public List < List < T > > apply ( List < List < T > > selectedCandidates , Random rng ) { List < List < T > > output = new ArrayList < List < T > > ( selectedCandidates . size ( ) ) ; for ( List < T > item : selectedCandidates ) { output . add ( delegate . apply ( item , rng ) ) ; } return output ; }
|
Applies the configured operator to each list candidate operating on the elements that make up a candidate rather than on the list of candidates . candidates and returns the results .
|
38,462
|
public List < Biomorph > apply ( List < Biomorph > selectedCandidates , Random rng ) { List < Biomorph > mutatedPopulation = new ArrayList < Biomorph > ( selectedCandidates . size ( ) ) ; int mutatedGene = 0 ; int mutation = 1 ; for ( Biomorph b : selectedCandidates ) { int [ ] genes = b . getGenotype ( ) ; mutation *= - 1 ; if ( mutation == 1 ) { mutatedGene = ( mutatedGene + 1 ) % Biomorph . GENE_COUNT ; } genes [ mutatedGene ] += mutation ; int min = mutatedGene == Biomorph . LENGTH_GENE_INDEX ? Biomorph . LENGTH_GENE_MIN : Biomorph . GENE_MIN ; int max = mutatedGene == Biomorph . LENGTH_GENE_INDEX ? Biomorph . LENGTH_GENE_MAX : Biomorph . GENE_MAX ; if ( genes [ mutatedGene ] > max ) { genes [ mutatedGene ] = min ; } else if ( genes [ mutatedGene ] < min ) { genes [ mutatedGene ] = max ; } mutatedPopulation . add ( new Biomorph ( genes ) ) ; } return mutatedPopulation ; }
|
Mutate a population of biomorphs non - randomly ensuring that each selected candidate is mutated differently .
|
38,463
|
private Color mutateColour ( Color colour , Random rng ) { if ( mutationProbability . nextValue ( ) . nextEvent ( rng ) ) { return new Color ( mutateColourComponent ( colour . getRed ( ) ) , mutateColourComponent ( colour . getGreen ( ) ) , mutateColourComponent ( colour . getBlue ( ) ) , mutateColourComponent ( colour . getAlpha ( ) ) ) ; } else { return colour ; } }
|
Mutate the specified colour .
|
38,464
|
public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable , nameGenerator . nextID ( ) ) ; thread . setPriority ( priority ) ; thread . setDaemon ( daemon ) ; thread . setUncaughtExceptionHandler ( uncaughtExceptionHandler ) ; return thread ; }
|
Creates a new thread configured according to this factory s parameters .
|
38,465
|
public List < T > apply ( List < T > selectedCandidates , Random rng ) { List < T > output = new ArrayList < T > ( selectedCandidates . size ( ) ) ; for ( T candidate : selectedCandidates ) { output . add ( replacementProbability . nextValue ( ) . nextEvent ( rng ) ? factory . generateRandomCandidate ( rng ) : candidate ) ; } return output ; }
|
Randomly replace zero or more of the selected candidates with new independent individuals that are randomly created .
|
38,466
|
public void paintBorder ( Component component , Graphics graphics , int x , int y , int width , int height ) { if ( top ) { graphics . fillRect ( x , y , width , thickness ) ; } if ( bottom ) { graphics . fillRect ( x , y + height - thickness , width , thickness ) ; } if ( left ) { graphics . fillRect ( x , y , thickness , height ) ; } if ( right ) { graphics . fillRect ( x + width - thickness , y , thickness , height ) ; } }
|
Renders borders for the specified component based on the configuration of this border object .
|
38,467
|
private void updateDomainAxisRange ( ) { int count = dataSet . getSeries ( 0 ) . getItemCount ( ) ; if ( count < SHOW_FIXED_GENERATIONS ) { domainAxis . setRangeWithMargins ( 0 , SHOW_FIXED_GENERATIONS ) ; } else if ( allDataButton . isSelected ( ) ) { domainAxis . setRangeWithMargins ( 0 , Math . max ( SHOW_FIXED_GENERATIONS , count ) ) ; } else { domainAxis . setRangeWithMargins ( count - SHOW_FIXED_GENERATIONS , count ) ; } }
|
If all data is selected set the range of the domain axis to include all values . Otherwise set it to show the most recent 200 generations .
|
38,468
|
private BufferedImage convertImage ( BufferedImage image ) { if ( image . getType ( ) == BufferedImage . TYPE_INT_RGB ) { return image ; } else { BufferedImage newImage = new BufferedImage ( image . getWidth ( ) , image . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; newImage . getGraphics ( ) . drawImage ( image , 0 , 0 , null ) ; return newImage ; } }
|
Make sure that the image is in the most efficient format for reading from . This avoids having to convert pixels every time we access them .
|
38,469
|
public double getFitness ( List < ColouredPolygon > candidate , List < ? extends List < ColouredPolygon > > population ) { Renderer < List < ColouredPolygon > , BufferedImage > renderer = threadLocalRenderer . get ( ) ; if ( renderer == null ) { renderer = new PolygonImageRenderer ( new Dimension ( width , height ) , false , transform ) ; threadLocalRenderer . set ( renderer ) ; } BufferedImage candidateImage = renderer . render ( candidate ) ; Raster candidateImageData = candidateImage . getData ( ) ; int [ ] candidatePixelValues = new int [ targetPixels . length ] ; candidatePixelValues = ( int [ ] ) candidateImageData . getDataElements ( 0 , 0 , candidateImageData . getWidth ( ) , candidateImageData . getHeight ( ) , candidatePixelValues ) ; double fitness = 0 ; for ( int i = 0 ; i < targetPixels . length ; i ++ ) { fitness += comparePixels ( targetPixels [ i ] , candidatePixelValues [ i ] ) ; } return fitness ; }
|
Render the polygons as an image and then do a pixel - by - pixel comparison against the target image . The fitness score is the total error . A lower score means a closer match .
|
38,470
|
public List < T > apply ( List < T > selectedCandidates , Random rng ) { double ratio = weightVariable . nextValue ( ) ; int size = ( int ) Math . round ( ratio * selectedCandidates . size ( ) ) ; List < T > selectionClone = new ArrayList < T > ( selectedCandidates ) ; Collections . shuffle ( selectionClone , rng ) ; List < T > list1 = selectionClone . subList ( 0 , size ) ; List < T > list2 = selectionClone . subList ( size , selectedCandidates . size ( ) ) ; List < T > result = new ArrayList < T > ( selectedCandidates . size ( ) ) ; result . addAll ( operator1 . apply ( list1 , rng ) ) ; result . addAll ( operator2 . apply ( list2 , rng ) ) ; return result ; }
|
Applies one evolutionary operator to part of the population and another to the remainder . Returns a list combining the output of both . Which candidates are submitted to which stream is determined randomly .
|
38,471
|
public static void main ( String [ ] args ) throws IOException { MonaLisaApplet gui = new MonaLisaApplet ( ) ; URL imageURL = args . length > 0 ? new URL ( args [ 0 ] ) : MonaLisaApplet . class . getClassLoader ( ) . getResource ( IMAGE_PATH ) ; gui . targetImage = ImageIO . read ( imageURL ) ; gui . displayInFrame ( "Watchmaker Framework - Mona Lisa Example" ) ; }
|
Entry point for running this example as an application rather than an applet .
|
38,472
|
public List < T > apply ( List < T > selectedCandidates , Random rng ) { return new ArrayList < T > ( selectedCandidates ) ; }
|
Returns the selected candidates unaltered .
|
38,473
|
protected List < Node > mate ( Node parent1 , Node parent2 , int numberOfCrossoverPoints , Random rng ) { List < Node > offspring = new ArrayList < Node > ( 2 ) ; Node offspring1 = parent1 ; Node offspring2 = parent2 ; for ( int i = 0 ; i < numberOfCrossoverPoints ; i ++ ) { int crossoverPoint1 = rng . nextInt ( parent1 . countNodes ( ) ) ; Node subTree1 = parent1 . getNode ( crossoverPoint1 ) ; int crossoverPoint2 = rng . nextInt ( parent2 . countNodes ( ) ) ; Node subTree2 = parent2 . getNode ( crossoverPoint2 ) ; offspring1 = parent1 . replaceNode ( crossoverPoint1 , subTree2 ) ; offspring2 = parent2 . replaceNode ( crossoverPoint2 , subTree1 ) ; } offspring . add ( offspring1 ) ; offspring . add ( offspring2 ) ; return offspring ; }
|
Swaps randomly selected sub - trees between the two parents .
|
38,474
|
public String generateRandomCandidate ( Random rng ) { char [ ] chars = new char [ stringLength ] ; for ( int i = 0 ; i < stringLength ; i ++ ) { chars [ i ] = alphabet [ rng . nextInt ( alphabet . length ) ] ; } return new String ( chars ) ; }
|
Generates a random string of a pre - configured length . Each character is randomly selected from the pre - configured alphabet . The same character may appear multiple times and some characters may not appear at all .
|
38,475
|
public static Method findKnownMethod ( Class < ? > aClass , String name , Class < ? > ... paramTypes ) { try { return aClass . getMethod ( name , paramTypes ) ; } catch ( NoSuchMethodException ex ) { throw new IllegalArgumentException ( "Method " + name + " does not exist in class " + aClass . getName ( ) , ex ) ; } }
|
Looks up a method that is explicitly identified . This method should only be used for methods that definitely exist . It does not throw the checked NoSuchMethodException . If the method does not exist it will instead fail with an unchecked IllegalArgumentException .
|
38,476
|
public static < T > Constructor < T > findKnownConstructor ( Class < T > aClass , Class < ? > ... paramTypes ) { try { return aClass . getConstructor ( paramTypes ) ; } catch ( NoSuchMethodException ex ) { throw new IllegalArgumentException ( "Specified constructor does not exist in class " + aClass . getName ( ) , ex ) ; } }
|
Looks up a constructor that is explicitly identified . This method should only be used for constructors that definitely exist . It does not throw the checked NoSuchMethodException . If the constructor does not exist it will instead fail with an unchecked IllegalArgumentException .
|
38,477
|
private List < Callable < List < EvaluatedCandidate < T > > > > createEpochTasks ( int populationSize , int eliteCount , int epochLength , List < List < T > > islandPopulations ) { List < Callable < List < EvaluatedCandidate < T > > > > islandEpochs = new ArrayList < Callable < List < EvaluatedCandidate < T > > > > ( islands . size ( ) ) ; for ( int i = 0 ; i < islands . size ( ) ; i ++ ) { islandEpochs . add ( new Epoch < T > ( islands . get ( i ) , populationSize , eliteCount , islandPopulations . isEmpty ( ) ? Collections . < T > emptyList ( ) : islandPopulations . get ( i ) , new GenerationCount ( epochLength ) ) ) ; } return islandEpochs ; }
|
Create the concurrently - executed tasks that perform evolution on each island .
|
38,478
|
public List < T > apply ( List < T > selectedCandidates , Random rng ) { List < T > selectionClone = new ArrayList < T > ( selectedCandidates ) ; Collections . shuffle ( selectionClone , rng ) ; List < T > result = new ArrayList < T > ( selectedCandidates . size ( ) ) ; Iterator < T > iterator = selectionClone . iterator ( ) ; while ( iterator . hasNext ( ) ) { T parent1 = iterator . next ( ) ; if ( iterator . hasNext ( ) ) { T parent2 = iterator . next ( ) ; int crossoverPoints = crossoverProbabilityVariable . nextValue ( ) . nextEvent ( rng ) ? crossoverPointsVariable . nextValue ( ) : 0 ; if ( crossoverPoints > 0 ) { result . addAll ( mate ( parent1 , parent2 , crossoverPoints , rng ) ) ; } else { result . add ( parent1 ) ; result . add ( parent2 ) ; } } else { result . add ( parent1 ) ; } } return result ; }
|
Applies the cross - over operation to the selected candidates . Pairs of candidates are chosen randomly and subjected to cross - over to produce a pair of offspring candidates .
|
38,479
|
private Border getBorder ( int row , int column ) { if ( row % 3 == 2 ) { switch ( column % 3 ) { case 2 : return BOTTOM_RIGHT_BORDER ; case 0 : return BOTTOM_LEFT_BORDER ; default : return BOTTOM_BORDER ; } } else if ( row % 3 == 0 ) { switch ( column % 3 ) { case 2 : return TOP_RIGHT_BORDER ; case 0 : return TOP_LEFT_BORDER ; default : return TOP_BORDER ; } } switch ( column % 3 ) { case 2 : return RIGHT_BORDER ; case 0 : return LEFT_BORDER ; default : return null ; } }
|
Get appropriate border for cell based on its position in the grid .
|
38,480
|
public static < T > List < TerminationCondition > shouldContinue ( PopulationData < T > data , TerminationCondition ... conditions ) { if ( Thread . currentThread ( ) . isInterrupted ( ) ) { return Collections . emptyList ( ) ; } List < TerminationCondition > satisfiedConditions = new LinkedList < TerminationCondition > ( ) ; for ( TerminationCondition condition : conditions ) { if ( condition . shouldTerminate ( data ) ) { satisfiedConditions . add ( condition ) ; } } return satisfiedConditions . isEmpty ( ) ? null : satisfiedConditions ; }
|
Given data about the current population and a set of termination conditions determines whether or not the evolution should continue .
|
38,481
|
public static < T > PopulationData < T > getPopulationData ( List < EvaluatedCandidate < T > > evaluatedPopulation , boolean naturalFitness , int eliteCount , int iterationNumber , long startTime ) { DataSet stats = new DataSet ( evaluatedPopulation . size ( ) ) ; for ( EvaluatedCandidate < T > candidate : evaluatedPopulation ) { stats . addValue ( candidate . getFitness ( ) ) ; } return new PopulationData < T > ( evaluatedPopulation . get ( 0 ) . getCandidate ( ) , evaluatedPopulation . get ( 0 ) . getFitness ( ) , stats . getArithmeticMean ( ) , stats . getStandardDeviation ( ) , naturalFitness , stats . getSize ( ) , eliteCount , iterationNumber , System . currentTimeMillis ( ) - startTime ) ; }
|
Gets data about the current population including the fittest candidate and statistics about the population as a whole .
|
38,482
|
public BufferedImage render ( List < ColouredPolygon > entity ) { graphics . setTransform ( IDENTITY_TRANSFORM ) ; graphics . setColor ( Color . GRAY ) ; graphics . fillRect ( 0 , 0 , targetSize . width , targetSize . height ) ; if ( transform != null ) { graphics . setTransform ( transform ) ; } for ( ColouredPolygon polygon : entity ) { graphics . setColor ( polygon . getColour ( ) ) ; graphics . fillPolygon ( polygon . getPolygon ( ) ) ; } return image ; }
|
Renders the specified polygons as an image .
|
38,483
|
public < S extends Object > void migrate ( List < List < EvaluatedCandidate < S > > > islandPopulations , int migrantCount , Random rng ) { List < EvaluatedCandidate < S > > lastIsland = islandPopulations . get ( islandPopulations . size ( ) - 1 ) ; Collections . shuffle ( lastIsland , rng ) ; List < EvaluatedCandidate < S > > migrants = lastIsland . subList ( lastIsland . size ( ) - migrantCount , lastIsland . size ( ) ) ; for ( List < EvaluatedCandidate < S > > island : islandPopulations ) { List < EvaluatedCandidate < S > > immigrants = migrants ; if ( island != lastIsland ) { Collections . shuffle ( island , rng ) ; migrants = new ArrayList < EvaluatedCandidate < S > > ( island . subList ( island . size ( ) - migrantCount , island . size ( ) ) ) ; } for ( int i = 0 ; i < immigrants . size ( ) ; i ++ ) { island . set ( island . size ( ) - migrantCount + i , immigrants . get ( i ) ) ; } } }
|
Migrates a fixed number of individuals from each island to the adjacent island . Operates as if the islands are arranged in a ring with migration occurring in a clockwise direction . The individuals to be migrated are chosen completely at random .
|
38,484
|
public Collection < String > getSelectedCities ( ) { Set < String > cities = new TreeSet < String > ( ) ; for ( JCheckBox checkBox : checkBoxes ) { if ( checkBox . isSelected ( ) ) { cities . add ( checkBox . getText ( ) ) ; } } return cities ; }
|
Returns the cities that have been selected as part of the itinerary .
|
38,485
|
protected List < Point > mutateVertices ( List < Point > vertices , Random rng ) { if ( vertices . size ( ) < MAX_VERTEX_COUNT && getMutationProbability ( ) . nextValue ( ) . nextEvent ( rng ) ) { List < Point > newVertices = new ArrayList < Point > ( vertices ) ; newVertices . add ( rng . nextInt ( newVertices . size ( ) ) , new Point ( rng . nextInt ( getCanvasSize ( ) . width ) , rng . nextInt ( getCanvasSize ( ) . height ) ) ) ; return newVertices ; } else { return vertices ; } }
|
Mutates the list of vertices for a given polygon by adding a new random point . Whether or not a point is actually added is determined by the configured mutation probability .
|
38,486
|
public int [ ] [ ] getPatternPhenotype ( ) { if ( phenotype == null ) { int [ ] dx = new int [ GENE_COUNT - 1 ] ; dx [ 3 ] = genes [ 0 ] ; dx [ 4 ] = genes [ 1 ] ; dx [ 5 ] = genes [ 2 ] ; dx [ 1 ] = - dx [ 3 ] ; dx [ 0 ] = - dx [ 4 ] ; dx [ 7 ] = - dx [ 5 ] ; dx [ 2 ] = 0 ; dx [ 6 ] = 0 ; int [ ] dy = new int [ GENE_COUNT - 1 ] ; dy [ 2 ] = genes [ 3 ] ; dy [ 3 ] = genes [ 4 ] ; dy [ 4 ] = genes [ 5 ] ; dy [ 5 ] = genes [ 6 ] ; dy [ 6 ] = genes [ 7 ] ; dy [ 0 ] = dy [ 4 ] ; dy [ 1 ] = dy [ 3 ] ; dy [ 7 ] = dy [ 5 ] ; phenotype = new int [ ] [ ] { dx , dy } ; } return phenotype ; }
|
Returns an array of integers that represent the graphical pattern determined by the biomorph s genes .
|
38,487
|
private boolean isIntroducingFixedConflict ( Sudoku sudoku , int row , int fromIndex , int toIndex ) { return columnFixedValues [ fromIndex ] [ sudoku . getValue ( row , toIndex ) - 1 ] || columnFixedValues [ toIndex ] [ sudoku . getValue ( row , fromIndex ) - 1 ] || subGridFixedValues [ convertToSubGrid ( row , fromIndex ) ] [ sudoku . getValue ( row , toIndex ) - 1 ] || subGridFixedValues [ convertToSubGrid ( row , toIndex ) ] [ sudoku . getValue ( row , fromIndex ) - 1 ] ; }
|
Checks whether the proposed mutation would introduce a duplicate of a fixed value into a column or sub - grid .
|
38,488
|
public List < T > apply ( List < T > selectedCandidates , Random rng ) { List < T > population = selectedCandidates ; for ( EvolutionaryOperator < T > operator : pipeline ) { population = operator . apply ( population , rng ) ; } return population ; }
|
Applies each operation in the pipeline in turn to the selection .
|
38,489
|
public double getFitness ( List < String > candidate , List < ? extends List < String > > population ) { int totalDistance = 0 ; int cityCount = candidate . size ( ) ; for ( int i = 0 ; i < cityCount ; i ++ ) { int nextIndex = i < cityCount - 1 ? i + 1 : 0 ; totalDistance += distances . getDistance ( candidate . get ( i ) , candidate . get ( nextIndex ) ) ; } return totalDistance ; }
|
Calculates the length of an evolved route .
|
38,490
|
public static void main ( String [ ] args ) { Class < ? > exampleClass = args . length > 0 ? EXAMPLES . get ( args [ 0 ] ) : null ; if ( exampleClass == null ) { System . err . println ( "First argument must be the name of an example, i.e. one of " + Arrays . toString ( EXAMPLES . keySet ( ) . toArray ( ) ) ) ; System . exit ( 1 ) ; } String [ ] appArgs = new String [ args . length - 1 ] ; System . arraycopy ( args , 1 , appArgs , 0 , appArgs . length ) ; Method main = ReflectionUtils . findKnownMethod ( exampleClass , "main" , String [ ] . class ) ; ReflectionUtils . invokeUnchecked ( main , exampleClass , new Object [ ] { appArgs } ) ; }
|
Launch the specified example application from the command - line .
|
38,491
|
private String mutateString ( String s , Random rng ) { StringBuilder buffer = new StringBuilder ( s ) ; for ( int i = 0 ; i < buffer . length ( ) ; i ++ ) { if ( mutationProbability . nextValue ( ) . nextEvent ( rng ) ) { buffer . setCharAt ( i , alphabet [ rng . nextInt ( alphabet . length ) ] ) ; } } return buffer . toString ( ) ; }
|
Mutate a single string . Zero or more characters may be modified . The probability of any given character being modified is governed by the probability generator configured for this mutation operator .
|
38,492
|
public static Node evolveProgram ( Map < double [ ] , Double > data ) { TreeFactory factory = new TreeFactory ( 2 , 4 , Probability . EVENS , new Probability ( 0.6d ) ) ; List < EvolutionaryOperator < Node > > operators = new ArrayList < EvolutionaryOperator < Node > > ( 3 ) ; operators . add ( new TreeMutation ( factory , new Probability ( 0.4d ) ) ) ; operators . add ( new TreeCrossover ( ) ) ; operators . add ( new Simplification ( ) ) ; TreeEvaluator evaluator = new TreeEvaluator ( data ) ; EvolutionEngine < Node > engine = new GenerationalEvolutionEngine < Node > ( factory , new EvolutionPipeline < Node > ( operators ) , evaluator , new RouletteWheelSelection ( ) , new MersenneTwisterRNG ( ) ) ; engine . addEvolutionObserver ( new EvolutionLogger < Node > ( ) ) ; return engine . evolve ( 1000 , 5 , new TargetFitness ( 0d , evaluator . isNatural ( ) ) ) ; }
|
Evolve a function to fit the specified data .
|
38,493
|
private void showWindow ( Window newWindow ) { if ( window != null ) { window . remove ( getGUIComponent ( ) ) ; window . setVisible ( false ) ; window . dispose ( ) ; window = null ; } newWindow . add ( getGUIComponent ( ) , BorderLayout . CENTER ) ; newWindow . pack ( ) ; newWindow . setVisible ( true ) ; this . window = newWindow ; }
|
Helper method for showing the evolution monitor in a frame or dialog .
|
38,494
|
private void checkUnmappedElements ( List < T > offspring , Map < T , T > mapping , int mappingStart , int mappingEnd ) { for ( int i = 0 ; i < offspring . size ( ) ; i ++ ) { if ( ! isInsideMappedRegion ( i , mappingStart , mappingEnd ) ) { T mapped = offspring . get ( i ) ; while ( mapping . containsKey ( mapped ) ) { mapped = mapping . get ( mapped ) ; } offspring . set ( i , mapped ) ; } } }
|
Checks elements that are outside of the partially mapped section to see if there are any duplicate items in the list . If there are they are mapped appropriately .
|
38,495
|
private boolean isInsideMappedRegion ( int position , int startPoint , int endPoint ) { boolean enclosed = ( position < endPoint && position >= startPoint ) ; boolean wrapAround = ( startPoint > endPoint && ( position >= startPoint || position < endPoint ) ) ; return enclosed || wrapAround ; }
|
Checks whether a given list position is within the partially mapped region used for cross - over .
|
38,496
|
private void configure ( final Container container ) { try { SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception ex ) { System . err . println ( "Failed to load System look-and-feel." ) ; } prepareGUI ( container ) ; } } ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( InvocationTargetException ex ) { ex . getCause ( ) . printStackTrace ( ) ; JOptionPane . showMessageDialog ( container , ex . getCause ( ) , "Error Occurred" , JOptionPane . ERROR_MESSAGE ) ; } }
|
Configure the program to display its GUI in the specified container .
|
38,497
|
private BitString mutateBitString ( BitString bitString , Random rng ) { if ( mutationProbability . nextValue ( ) . nextEvent ( rng ) ) { BitString mutatedBitString = bitString . clone ( ) ; int mutations = mutationCount . nextValue ( ) ; for ( int i = 0 ; i < mutations ; i ++ ) { mutatedBitString . flipBit ( rng . nextInt ( mutatedBitString . getLength ( ) ) ) ; } return mutatedBitString ; } return bitString ; }
|
Mutate a single bit string . Zero or more bits may be flipped . The probability of any given bit being flipped is governed by the probability generator configured for this mutation operator .
|
38,498
|
public static < T > T run ( HTablePool pool , byte [ ] tableName , HTableRunnable < T > runnable ) throws IOException { HTableInterface hTable = null ; try { hTable = pool . getTable ( tableName ) ; return runnable . runWith ( hTable ) ; } catch ( Exception e ) { if ( e instanceof IOException ) { throw ( IOException ) e ; } else { throw new RuntimeException ( e ) ; } } finally { if ( hTable != null ) { pool . putTable ( hTable ) ; } } }
|
Take an htable from the pool use it with the given HTableRunnable and return it to the pool . This is the loan pattern where the htable resource is used temporarily by the runnable .
|
38,499
|
public static void put ( HTablePool pool , byte [ ] tableName , final Put put ) throws IOException { run ( pool , tableName , new HTableRunnable < Object > ( ) { public Object runWith ( HTableInterface hTable ) throws IOException { hTable . put ( put ) ; return null ; } } ) ; }
|
Do an HBase put and return null .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.