id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
27,700
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.checkFileExists
public static void checkFileExists(final File file, final String name) { if (!file.exists()) { final String msg = "missing file for " + name + " : " + file.getAbsolutePath(); throw new IllegalStateException(msg); } }
java
public static void checkFileExists(final File file, final String name) { if (!file.exists()) { final String msg = "missing file for " + name + " : " + file.getAbsolutePath(); throw new IllegalStateException(msg); } }
[ "public", "static", "void", "checkFileExists", "(", "final", "File", "file", ",", "final", "String", "name", ")", "{", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "final", "String", "msg", "=", "\"missing file for \"", "+", "name", "+", "\" : \"", "+", "file", ".", "getAbsolutePath", "(", ")", ";", "throw", "new", "IllegalStateException", "(", "msg", ")", ";", "}", "}" ]
Check that a file exists and throw an exception if not. @param file to check existence of. @param name to associate for the exception
[ "Check", "that", "a", "file", "exists", "and", "throw", "an", "exception", "if", "not", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L425-L432
27,701
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.map
public static long map( final FileChannel fileChannel, final FileChannel.MapMode mode, final long offset, final long length) { try { return (long)MappingMethods.MAP_ADDRESS.invoke(fileChannel, getMode(mode), offset, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } return 0; }
java
public static long map( final FileChannel fileChannel, final FileChannel.MapMode mode, final long offset, final long length) { try { return (long)MappingMethods.MAP_ADDRESS.invoke(fileChannel, getMode(mode), offset, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } return 0; }
[ "public", "static", "long", "map", "(", "final", "FileChannel", "fileChannel", ",", "final", "FileChannel", ".", "MapMode", "mode", ",", "final", "long", "offset", ",", "final", "long", "length", ")", "{", "try", "{", "return", "(", "long", ")", "MappingMethods", ".", "MAP_ADDRESS", ".", "invoke", "(", "fileChannel", ",", "getMode", "(", "mode", ")", ",", "offset", ",", "length", ")", ";", "}", "catch", "(", "final", "IllegalAccessException", "|", "InvocationTargetException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "return", "0", ";", "}" ]
Map a range of a file and return the address at which the range begins. @param fileChannel to be mapped. @param mode for the mapped region. @param offset within the file the mapped region should start. @param length of the mapped region. @return the address at which the mapping starts.
[ "Map", "a", "range", "of", "a", "file", "and", "return", "the", "address", "at", "which", "the", "range", "begins", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L463-L476
27,702
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.unmap
public static void unmap(final FileChannel fileChannel, final long address, final long length) { try { MappingMethods.UNMAP_ADDRESS.invoke(fileChannel, address, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } }
java
public static void unmap(final FileChannel fileChannel, final long address, final long length) { try { MappingMethods.UNMAP_ADDRESS.invoke(fileChannel, address, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } }
[ "public", "static", "void", "unmap", "(", "final", "FileChannel", "fileChannel", ",", "final", "long", "address", ",", "final", "long", "length", ")", "{", "try", "{", "MappingMethods", ".", "UNMAP_ADDRESS", ".", "invoke", "(", "fileChannel", ",", "address", ",", "length", ")", ";", "}", "catch", "(", "final", "IllegalAccessException", "|", "InvocationTargetException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}" ]
Unmap a region of a file. @param fileChannel which has been mapped. @param address at which the mapping begins. @param length of the mapped region.
[ "Unmap", "a", "region", "of", "a", "file", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L485-L495
27,703
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/CountersManager.java
CountersManager.allocate
public int allocate(final String label, final int typeId) { final int counterId = nextCounterId(); checkCountersCapacity(counterId); final int recordOffset = metaDataOffset(counterId); checkMetaDataCapacity(recordOffset); try { metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId); metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE); putLabel(recordOffset, label); metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED); } catch (final Exception ex) { freeList.pushInt(counterId); LangUtil.rethrowUnchecked(ex); } return counterId; }
java
public int allocate(final String label, final int typeId) { final int counterId = nextCounterId(); checkCountersCapacity(counterId); final int recordOffset = metaDataOffset(counterId); checkMetaDataCapacity(recordOffset); try { metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId); metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE); putLabel(recordOffset, label); metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED); } catch (final Exception ex) { freeList.pushInt(counterId); LangUtil.rethrowUnchecked(ex); } return counterId; }
[ "public", "int", "allocate", "(", "final", "String", "label", ",", "final", "int", "typeId", ")", "{", "final", "int", "counterId", "=", "nextCounterId", "(", ")", ";", "checkCountersCapacity", "(", "counterId", ")", ";", "final", "int", "recordOffset", "=", "metaDataOffset", "(", "counterId", ")", ";", "checkMetaDataCapacity", "(", "recordOffset", ")", ";", "try", "{", "metaDataBuffer", ".", "putInt", "(", "recordOffset", "+", "TYPE_ID_OFFSET", ",", "typeId", ")", ";", "metaDataBuffer", ".", "putLong", "(", "recordOffset", "+", "FREE_FOR_REUSE_DEADLINE_OFFSET", ",", "NOT_FREE_TO_REUSE", ")", ";", "putLabel", "(", "recordOffset", ",", "label", ")", ";", "metaDataBuffer", ".", "putIntOrdered", "(", "recordOffset", ",", "RECORD_ALLOCATED", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "freeList", ".", "pushInt", "(", "counterId", ")", ";", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "return", "counterId", ";", "}" ]
Allocate a new counter with a given label and type. @param label to describe the counter. @param typeId for the type of counter. @return the id allocated for the counter.
[ "Allocate", "a", "new", "counter", "with", "a", "given", "label", "and", "type", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/CountersManager.java#L171-L194
27,704
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/CountersManager.java
CountersManager.free
public void free(final int counterId) { final int recordOffset = metaDataOffset(counterId); metaDataBuffer.putLong( recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, epochClock.time() + freeToReuseTimeoutMs); metaDataBuffer.putIntOrdered(recordOffset, RECORD_RECLAIMED); freeList.addInt(counterId); }
java
public void free(final int counterId) { final int recordOffset = metaDataOffset(counterId); metaDataBuffer.putLong( recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, epochClock.time() + freeToReuseTimeoutMs); metaDataBuffer.putIntOrdered(recordOffset, RECORD_RECLAIMED); freeList.addInt(counterId); }
[ "public", "void", "free", "(", "final", "int", "counterId", ")", "{", "final", "int", "recordOffset", "=", "metaDataOffset", "(", "counterId", ")", ";", "metaDataBuffer", ".", "putLong", "(", "recordOffset", "+", "FREE_FOR_REUSE_DEADLINE_OFFSET", ",", "epochClock", ".", "time", "(", ")", "+", "freeToReuseTimeoutMs", ")", ";", "metaDataBuffer", ".", "putIntOrdered", "(", "recordOffset", ",", "RECORD_RECLAIMED", ")", ";", "freeList", ".", "addInt", "(", "counterId", ")", ";", "}" ]
Free the counter identified by counterId. @param counterId the counter to freed
[ "Free", "the", "counter", "identified", "by", "counterId", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/CountersManager.java#L359-L367
27,705
real-logic/agrona
agrona/src/main/java/org/agrona/BitUtil.java
BitUtil.fromHexByteArray
public static byte[] fromHexByteArray(final byte[] buffer) { final byte[] outputBuffer = new byte[buffer.length >> 1]; for (int i = 0; i < buffer.length; i += 2) { final int hi = FROM_HEX_DIGIT_TABLE[buffer[i]] << 4; final int lo = FROM_HEX_DIGIT_TABLE[buffer[i + 1]]; // lgtm [java/index-out-of-bounds] outputBuffer[i >> 1] = (byte)(hi | lo); } return outputBuffer; }
java
public static byte[] fromHexByteArray(final byte[] buffer) { final byte[] outputBuffer = new byte[buffer.length >> 1]; for (int i = 0; i < buffer.length; i += 2) { final int hi = FROM_HEX_DIGIT_TABLE[buffer[i]] << 4; final int lo = FROM_HEX_DIGIT_TABLE[buffer[i + 1]]; // lgtm [java/index-out-of-bounds] outputBuffer[i >> 1] = (byte)(hi | lo); } return outputBuffer; }
[ "public", "static", "byte", "[", "]", "fromHexByteArray", "(", "final", "byte", "[", "]", "buffer", ")", "{", "final", "byte", "[", "]", "outputBuffer", "=", "new", "byte", "[", "buffer", ".", "length", ">>", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "buffer", ".", "length", ";", "i", "+=", "2", ")", "{", "final", "int", "hi", "=", "FROM_HEX_DIGIT_TABLE", "[", "buffer", "[", "i", "]", "]", "<<", "4", ";", "final", "int", "lo", "=", "FROM_HEX_DIGIT_TABLE", "[", "buffer", "[", "i", "+", "1", "]", "]", ";", "// lgtm [java/index-out-of-bounds]", "outputBuffer", "[", "i", ">>", "1", "]", "=", "(", "byte", ")", "(", "hi", "|", "lo", ")", ";", "}", "return", "outputBuffer", ";", "}" ]
Generate a byte array from the hex representation of the given byte array. @param buffer to convert from a hex representation (in Big Endian). @return new byte array that is decimal representation of the passed array.
[ "Generate", "a", "byte", "array", "from", "the", "hex", "representation", "of", "the", "given", "byte", "array", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/BitUtil.java#L147-L159
27,706
real-logic/agrona
agrona/src/main/java/org/agrona/BitUtil.java
BitUtil.toHexByteArray
public static byte[] toHexByteArray(final byte[] buffer, final int offset, final int length) { final byte[] outputBuffer = new byte[length << 1]; for (int i = 0; i < (length << 1); i += 2) { final byte b = buffer[offset + (i >> 1)]; outputBuffer[i] = HEX_DIGIT_TABLE[(b >> 4) & 0x0F]; outputBuffer[i + 1] = HEX_DIGIT_TABLE[b & 0x0F]; } return outputBuffer; }
java
public static byte[] toHexByteArray(final byte[] buffer, final int offset, final int length) { final byte[] outputBuffer = new byte[length << 1]; for (int i = 0; i < (length << 1); i += 2) { final byte b = buffer[offset + (i >> 1)]; outputBuffer[i] = HEX_DIGIT_TABLE[(b >> 4) & 0x0F]; outputBuffer[i + 1] = HEX_DIGIT_TABLE[b & 0x0F]; } return outputBuffer; }
[ "public", "static", "byte", "[", "]", "toHexByteArray", "(", "final", "byte", "[", "]", "buffer", ",", "final", "int", "offset", ",", "final", "int", "length", ")", "{", "final", "byte", "[", "]", "outputBuffer", "=", "new", "byte", "[", "length", "<<", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "(", "length", "<<", "1", ")", ";", "i", "+=", "2", ")", "{", "final", "byte", "b", "=", "buffer", "[", "offset", "+", "(", "i", ">>", "1", ")", "]", ";", "outputBuffer", "[", "i", "]", "=", "HEX_DIGIT_TABLE", "[", "(", "b", ">>", "4", ")", "&", "0x0F", "]", ";", "outputBuffer", "[", "i", "+", "1", "]", "=", "HEX_DIGIT_TABLE", "[", "b", "&", "0x0F", "]", ";", "}", "return", "outputBuffer", ";", "}" ]
Generate a byte array that is a hex representation of a given byte array. @param buffer to convert to a hex representation. @param offset the offset into the buffer. @param length the number of bytes to convert. @return new byte array that is hex representation (in Big Endian) of the passed array.
[ "Generate", "a", "byte", "array", "that", "is", "a", "hex", "representation", "of", "a", "given", "byte", "array", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/BitUtil.java#L180-L193
27,707
real-logic/agrona
agrona/src/main/java/org/agrona/BitUtil.java
BitUtil.toHex
public static String toHex(final byte[] buffer, final int offset, final int length) { return new String(toHexByteArray(buffer, offset, length), UTF_8); }
java
public static String toHex(final byte[] buffer, final int offset, final int length) { return new String(toHexByteArray(buffer, offset, length), UTF_8); }
[ "public", "static", "String", "toHex", "(", "final", "byte", "[", "]", "buffer", ",", "final", "int", "offset", ",", "final", "int", "length", ")", "{", "return", "new", "String", "(", "toHexByteArray", "(", "buffer", ",", "offset", ",", "length", ")", ",", "UTF_8", ")", ";", "}" ]
Generate a string that is the hex representation of a given byte array. @param buffer to convert to a hex representation. @param offset the offset into the buffer. @param length the number of bytes to convert. @return new String holding the hex representation (in Big Endian) of the passed array.
[ "Generate", "a", "string", "that", "is", "the", "hex", "representation", "of", "a", "given", "byte", "array", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/BitUtil.java#L214-L217
27,708
real-logic/agrona
agrona/src/main/java/org/agrona/BitUtil.java
BitUtil.isAligned
public static boolean isAligned(final long address, final int alignment) { if (!BitUtil.isPowerOfTwo(alignment)) { throw new IllegalArgumentException("alignment must be a power of 2: alignment=" + alignment); } return (address & (alignment - 1)) == 0; }
java
public static boolean isAligned(final long address, final int alignment) { if (!BitUtil.isPowerOfTwo(alignment)) { throw new IllegalArgumentException("alignment must be a power of 2: alignment=" + alignment); } return (address & (alignment - 1)) == 0; }
[ "public", "static", "boolean", "isAligned", "(", "final", "long", "address", ",", "final", "int", "alignment", ")", "{", "if", "(", "!", "BitUtil", ".", "isPowerOfTwo", "(", "alignment", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"alignment must be a power of 2: alignment=\"", "+", "alignment", ")", ";", "}", "return", "(", "address", "&", "(", "alignment", "-", "1", ")", ")", "==", "0", ";", "}" ]
Is an address aligned on a boundary. @param address to be tested. @param alignment boundary the address is tested against. @return true if the address is on the aligned boundary otherwise false. @throws IllegalArgumentException if the alignment is not a power of 2.
[ "Is", "an", "address", "aligned", "on", "a", "boundary", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/BitUtil.java#L325-L333
27,709
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java
AtomicCounter.incrementOrdered
public long incrementOrdered() { final long currentValue = UnsafeAccess.UNSAFE.getLong(byteArray, addressOffset); UnsafeAccess.UNSAFE.putOrderedLong(byteArray, addressOffset, currentValue + 1); return currentValue; }
java
public long incrementOrdered() { final long currentValue = UnsafeAccess.UNSAFE.getLong(byteArray, addressOffset); UnsafeAccess.UNSAFE.putOrderedLong(byteArray, addressOffset, currentValue + 1); return currentValue; }
[ "public", "long", "incrementOrdered", "(", ")", "{", "final", "long", "currentValue", "=", "UnsafeAccess", ".", "UNSAFE", ".", "getLong", "(", "byteArray", ",", "addressOffset", ")", ";", "UnsafeAccess", ".", "UNSAFE", ".", "putOrderedLong", "(", "byteArray", ",", "addressOffset", ",", "currentValue", "+", "1", ")", ";", "return", "currentValue", ";", "}" ]
Perform an atomic increment that is not safe across threads. @return the previous value of the counter
[ "Perform", "an", "atomic", "increment", "that", "is", "not", "safe", "across", "threads", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java#L104-L110
27,710
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java
AtomicCounter.getAndAddOrdered
public long getAndAddOrdered(final long increment) { final long currentValue = UnsafeAccess.UNSAFE.getLong(byteArray, addressOffset); UnsafeAccess.UNSAFE.putOrderedLong(byteArray, addressOffset, currentValue + increment); return currentValue; }
java
public long getAndAddOrdered(final long increment) { final long currentValue = UnsafeAccess.UNSAFE.getLong(byteArray, addressOffset); UnsafeAccess.UNSAFE.putOrderedLong(byteArray, addressOffset, currentValue + increment); return currentValue; }
[ "public", "long", "getAndAddOrdered", "(", "final", "long", "increment", ")", "{", "final", "long", "currentValue", "=", "UnsafeAccess", ".", "UNSAFE", ".", "getLong", "(", "byteArray", ",", "addressOffset", ")", ";", "UnsafeAccess", ".", "UNSAFE", ".", "putOrderedLong", "(", "byteArray", ",", "addressOffset", ",", "currentValue", "+", "increment", ")", ";", "return", "currentValue", ";", "}" ]
Add an increment to the counter with ordered store semantics. @param increment to be added with ordered store semantics. @return the previous value of the counter
[ "Add", "an", "increment", "to", "the", "counter", "with", "ordered", "store", "semantics", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java#L159-L165
27,711
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java
AtomicCounter.compareAndSet
public boolean compareAndSet(final long expectedValue, final long updateValue) { return UnsafeAccess.UNSAFE.compareAndSwapLong(byteArray, addressOffset, expectedValue, updateValue); }
java
public boolean compareAndSet(final long expectedValue, final long updateValue) { return UnsafeAccess.UNSAFE.compareAndSwapLong(byteArray, addressOffset, expectedValue, updateValue); }
[ "public", "boolean", "compareAndSet", "(", "final", "long", "expectedValue", ",", "final", "long", "updateValue", ")", "{", "return", "UnsafeAccess", ".", "UNSAFE", ".", "compareAndSwapLong", "(", "byteArray", ",", "addressOffset", ",", "expectedValue", ",", "updateValue", ")", ";", "}" ]
Compare the current value to expected and if true then set to the update value atomically. @param expectedValue for the counter. @param updateValue for the counter. @return true if successful otherwise false.
[ "Compare", "the", "current", "value", "to", "expected", "and", "if", "true", "then", "set", "to", "the", "update", "value", "atomically", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/AtomicCounter.java#L185-L188
27,712
real-logic/agrona
agrona/src/main/java/org/agrona/collections/CollectionUtil.java
CollectionUtil.getOrDefault
public static <K, V> V getOrDefault(final Map<K, V> map, final K key, final Function<K, V> supplier) { V value = map.get(key); if (value == null) { value = supplier.apply(key); map.put(key, value); } return value; }
java
public static <K, V> V getOrDefault(final Map<K, V> map, final K key, final Function<K, V> supplier) { V value = map.get(key); if (value == null) { value = supplier.apply(key); map.put(key, value); } return value; }
[ "public", "static", "<", "K", ",", "V", ">", "V", "getOrDefault", "(", "final", "Map", "<", "K", ",", "V", ">", "map", ",", "final", "K", "key", ",", "final", "Function", "<", "K", ",", "V", ">", "supplier", ")", "{", "V", "value", "=", "map", ".", "get", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "value", "=", "supplier", ".", "apply", "(", "key", ")", ";", "map", ".", "put", "(", "key", ",", "value", ")", ";", "}", "return", "value", ";", "}" ]
A getOrDefault that doesn't create garbage if its suppler is non-capturing. @param map to perform the lookup on. @param key on which the lookup is done. @param supplier of the default value if one is not found. @param <K> type of the key @param <V> type of the value @return the value if found or a new default which as been added to the map.
[ "A", "getOrDefault", "that", "doesn", "t", "create", "garbage", "if", "its", "suppler", "is", "non", "-", "capturing", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/CollectionUtil.java#L39-L49
27,713
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java
MappedResizeableBuffer.wrap
public void wrap(final long offset, final long length) { if (offset == addressOffset && length == capacity) { return; } wrap(fileChannel, offset, length); }
java
public void wrap(final long offset, final long length) { if (offset == addressOffset && length == capacity) { return; } wrap(fileChannel, offset, length); }
[ "public", "void", "wrap", "(", "final", "long", "offset", ",", "final", "long", "length", ")", "{", "if", "(", "offset", "==", "addressOffset", "&&", "length", "==", "capacity", ")", "{", "return", ";", "}", "wrap", "(", "fileChannel", ",", "offset", ",", "length", ")", ";", "}" ]
Remap the buffer using the existing file based on a new offset and length @param offset the offset of the file to start the mapping @param length of the buffer from the given address
[ "Remap", "the", "buffer", "using", "the", "existing", "file", "based", "on", "a", "new", "offset", "and", "length" ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java#L100-L108
27,714
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java
MappedResizeableBuffer.wrap
public void wrap(final FileChannel fileChannel, final long offset, final long length) { unmap(); this.fileChannel = fileChannel; map(offset, length); }
java
public void wrap(final FileChannel fileChannel, final long offset, final long length) { unmap(); this.fileChannel = fileChannel; map(offset, length); }
[ "public", "void", "wrap", "(", "final", "FileChannel", "fileChannel", ",", "final", "long", "offset", ",", "final", "long", "length", ")", "{", "unmap", "(", ")", ";", "this", ".", "fileChannel", "=", "fileChannel", ";", "map", "(", "offset", ",", "length", ")", ";", "}" ]
Remap the buffer based on a new file, offset, and a length @param fileChannel the file to map @param offset the offset of the file to start the mapping @param length of the buffer from the given address
[ "Remap", "the", "buffer", "based", "on", "a", "new", "file", "offset", "and", "a", "length" ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java#L117-L122
27,715
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java
MappedResizeableBuffer.wrap
public void wrap( final FileChannel fileChannel, final FileChannel.MapMode mapMode, final long offset, final long length) { unmap(); this.fileChannel = fileChannel; this.mapMode = mapMode; map(offset, length); }
java
public void wrap( final FileChannel fileChannel, final FileChannel.MapMode mapMode, final long offset, final long length) { unmap(); this.fileChannel = fileChannel; this.mapMode = mapMode; map(offset, length); }
[ "public", "void", "wrap", "(", "final", "FileChannel", "fileChannel", ",", "final", "FileChannel", ".", "MapMode", "mapMode", ",", "final", "long", "offset", ",", "final", "long", "length", ")", "{", "unmap", "(", ")", ";", "this", ".", "fileChannel", "=", "fileChannel", ";", "this", ".", "mapMode", "=", "mapMode", ";", "map", "(", "offset", ",", "length", ")", ";", "}" ]
Remap the buffer based on a new file, mapping mode, offset, and a length @param fileChannel the file to map @param mapMode for the file when mapping. @param offset the offset of the file to start the mapping @param length of the buffer from the given address
[ "Remap", "the", "buffer", "based", "on", "a", "new", "file", "mapping", "mode", "offset", "and", "a", "length" ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/MappedResizeableBuffer.java#L132-L139
27,716
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/errors/DistinctErrorLog.java
DistinctErrorLog.record
public boolean record(final Throwable observation) { final long timestamp = clock.time(); DistinctObservation distinctObservation; synchronized (this) { distinctObservation = find(distinctObservations, observation); if (null == distinctObservation) { distinctObservation = newObservation(timestamp, observation); if (INSUFFICIENT_SPACE == distinctObservation) { return false; } } } final int offset = distinctObservation.offset; buffer.getAndAddInt(offset + OBSERVATION_COUNT_OFFSET, 1); buffer.putLongOrdered(offset + LAST_OBSERVATION_TIMESTAMP_OFFSET, timestamp); return true; }
java
public boolean record(final Throwable observation) { final long timestamp = clock.time(); DistinctObservation distinctObservation; synchronized (this) { distinctObservation = find(distinctObservations, observation); if (null == distinctObservation) { distinctObservation = newObservation(timestamp, observation); if (INSUFFICIENT_SPACE == distinctObservation) { return false; } } } final int offset = distinctObservation.offset; buffer.getAndAddInt(offset + OBSERVATION_COUNT_OFFSET, 1); buffer.putLongOrdered(offset + LAST_OBSERVATION_TIMESTAMP_OFFSET, timestamp); return true; }
[ "public", "boolean", "record", "(", "final", "Throwable", "observation", ")", "{", "final", "long", "timestamp", "=", "clock", ".", "time", "(", ")", ";", "DistinctObservation", "distinctObservation", ";", "synchronized", "(", "this", ")", "{", "distinctObservation", "=", "find", "(", "distinctObservations", ",", "observation", ")", ";", "if", "(", "null", "==", "distinctObservation", ")", "{", "distinctObservation", "=", "newObservation", "(", "timestamp", ",", "observation", ")", ";", "if", "(", "INSUFFICIENT_SPACE", "==", "distinctObservation", ")", "{", "return", "false", ";", "}", "}", "}", "final", "int", "offset", "=", "distinctObservation", ".", "offset", ";", "buffer", ".", "getAndAddInt", "(", "offset", "+", "OBSERVATION_COUNT_OFFSET", ",", "1", ")", ";", "buffer", ".", "putLongOrdered", "(", "offset", "+", "LAST_OBSERVATION_TIMESTAMP_OFFSET", ",", "timestamp", ")", ";", "return", "true", ";", "}" ]
Record an observation of an error. If it is the first observation of this error type for a stack trace then a new entry will be created. For subsequent observations of the same error type and stack trace a counter and time of last observation will be updated. @param observation to be logged as an error observation. @return true if successfully logged otherwise false if insufficient space remaining in the log.
[ "Record", "an", "observation", "of", "an", "error", ".", "If", "it", "is", "the", "first", "observation", "of", "this", "error", "type", "for", "a", "stack", "trace", "then", "a", "new", "entry", "will", "be", "created", ".", "For", "subsequent", "observations", "of", "the", "same", "error", "type", "and", "stack", "trace", "a", "counter", "and", "time", "of", "last", "observation", "will", "be", "updated", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/errors/DistinctErrorLog.java#L120-L143
27,717
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java
CountersReader.forEach
public void forEach(final IntObjConsumer<String> consumer) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { consumer.accept(counterId, labelValue(metaDataBuffer, i)); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
java
public void forEach(final IntObjConsumer<String> consumer) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { consumer.accept(counterId, labelValue(metaDataBuffer, i)); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
[ "public", "void", "forEach", "(", "final", "IntObjConsumer", "<", "String", ">", "consumer", ")", "{", "int", "counterId", "=", "0", ";", "final", "AtomicBuffer", "metaDataBuffer", "=", "this", ".", "metaDataBuffer", ";", "for", "(", "int", "i", "=", "0", ",", "capacity", "=", "metaDataBuffer", ".", "capacity", "(", ")", ";", "i", "<", "capacity", ";", "i", "+=", "METADATA_LENGTH", ")", "{", "final", "int", "recordStatus", "=", "metaDataBuffer", ".", "getIntVolatile", "(", "i", ")", ";", "if", "(", "RECORD_ALLOCATED", "==", "recordStatus", ")", "{", "consumer", ".", "accept", "(", "counterId", ",", "labelValue", "(", "metaDataBuffer", ",", "i", ")", ")", ";", "}", "else", "if", "(", "RECORD_UNUSED", "==", "recordStatus", ")", "{", "break", ";", "}", "counterId", "++", ";", "}", "}" ]
Iterate over all labels in the label buffer. @param consumer function to be called for each label.
[ "Iterate", "over", "all", "labels", "in", "the", "label", "buffer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java#L285-L305
27,718
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java
CountersReader.forEach
public void forEach(final CounterConsumer consumer) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; final AtomicBuffer valuesBuffer = this.valuesBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { consumer.accept( valuesBuffer.getLongVolatile(counterOffset(counterId)), counterId, labelValue(metaDataBuffer, i)); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
java
public void forEach(final CounterConsumer consumer) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; final AtomicBuffer valuesBuffer = this.valuesBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { consumer.accept( valuesBuffer.getLongVolatile(counterOffset(counterId)), counterId, labelValue(metaDataBuffer, i)); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
[ "public", "void", "forEach", "(", "final", "CounterConsumer", "consumer", ")", "{", "int", "counterId", "=", "0", ";", "final", "AtomicBuffer", "metaDataBuffer", "=", "this", ".", "metaDataBuffer", ";", "final", "AtomicBuffer", "valuesBuffer", "=", "this", ".", "valuesBuffer", ";", "for", "(", "int", "i", "=", "0", ",", "capacity", "=", "metaDataBuffer", ".", "capacity", "(", ")", ";", "i", "<", "capacity", ";", "i", "+=", "METADATA_LENGTH", ")", "{", "final", "int", "recordStatus", "=", "metaDataBuffer", ".", "getIntVolatile", "(", "i", ")", ";", "if", "(", "RECORD_ALLOCATED", "==", "recordStatus", ")", "{", "consumer", ".", "accept", "(", "valuesBuffer", ".", "getLongVolatile", "(", "counterOffset", "(", "counterId", ")", ")", ",", "counterId", ",", "labelValue", "(", "metaDataBuffer", ",", "i", ")", ")", ";", "}", "else", "if", "(", "RECORD_UNUSED", "==", "recordStatus", ")", "{", "break", ";", "}", "counterId", "++", ";", "}", "}" ]
Iterate over the counters and provide the value and basic metadata. @param consumer for each allocated counter.
[ "Iterate", "over", "the", "counters", "and", "provide", "the", "value", "and", "basic", "metadata", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java#L312-L335
27,719
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java
CountersReader.forEach
public void forEach(final MetaData metaData) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { final int typeId = metaDataBuffer.getInt(i + TYPE_ID_OFFSET); final String label = labelValue(metaDataBuffer, i); final DirectBuffer keyBuffer = new UnsafeBuffer(metaDataBuffer, i + KEY_OFFSET, MAX_KEY_LENGTH); metaData.accept(counterId, typeId, keyBuffer, label); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
java
public void forEach(final MetaData metaData) { int counterId = 0; final AtomicBuffer metaDataBuffer = this.metaDataBuffer; for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH) { final int recordStatus = metaDataBuffer.getIntVolatile(i); if (RECORD_ALLOCATED == recordStatus) { final int typeId = metaDataBuffer.getInt(i + TYPE_ID_OFFSET); final String label = labelValue(metaDataBuffer, i); final DirectBuffer keyBuffer = new UnsafeBuffer(metaDataBuffer, i + KEY_OFFSET, MAX_KEY_LENGTH); metaData.accept(counterId, typeId, keyBuffer, label); } else if (RECORD_UNUSED == recordStatus) { break; } counterId++; } }
[ "public", "void", "forEach", "(", "final", "MetaData", "metaData", ")", "{", "int", "counterId", "=", "0", ";", "final", "AtomicBuffer", "metaDataBuffer", "=", "this", ".", "metaDataBuffer", ";", "for", "(", "int", "i", "=", "0", ",", "capacity", "=", "metaDataBuffer", ".", "capacity", "(", ")", ";", "i", "<", "capacity", ";", "i", "+=", "METADATA_LENGTH", ")", "{", "final", "int", "recordStatus", "=", "metaDataBuffer", ".", "getIntVolatile", "(", "i", ")", ";", "if", "(", "RECORD_ALLOCATED", "==", "recordStatus", ")", "{", "final", "int", "typeId", "=", "metaDataBuffer", ".", "getInt", "(", "i", "+", "TYPE_ID_OFFSET", ")", ";", "final", "String", "label", "=", "labelValue", "(", "metaDataBuffer", ",", "i", ")", ";", "final", "DirectBuffer", "keyBuffer", "=", "new", "UnsafeBuffer", "(", "metaDataBuffer", ",", "i", "+", "KEY_OFFSET", ",", "MAX_KEY_LENGTH", ")", ";", "metaData", ".", "accept", "(", "counterId", ",", "typeId", ",", "keyBuffer", ",", "label", ")", ";", "}", "else", "if", "(", "RECORD_UNUSED", "==", "recordStatus", ")", "{", "break", ";", "}", "counterId", "++", ";", "}", "}" ]
Iterate over all the metadata in the buffer. @param metaData function to be called for each metadata record.
[ "Iterate", "over", "all", "the", "metadata", "in", "the", "buffer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/status/CountersReader.java#L342-L366
27,720
real-logic/agrona
agrona/src/main/java/org/agrona/io/ExpandableDirectBufferOutputStream.java
ExpandableDirectBufferOutputStream.wrap
public void wrap(final MutableDirectBuffer buffer, final int offset) { Objects.requireNonNull(buffer, "Buffer must not be null"); if (!buffer.isExpandable()) { throw new IllegalStateException("buffer must be expandable."); } this.buffer = buffer; this.offset = offset; this.position = 0; }
java
public void wrap(final MutableDirectBuffer buffer, final int offset) { Objects.requireNonNull(buffer, "Buffer must not be null"); if (!buffer.isExpandable()) { throw new IllegalStateException("buffer must be expandable."); } this.buffer = buffer; this.offset = offset; this.position = 0; }
[ "public", "void", "wrap", "(", "final", "MutableDirectBuffer", "buffer", ",", "final", "int", "offset", ")", "{", "Objects", ".", "requireNonNull", "(", "buffer", ",", "\"Buffer must not be null\"", ")", ";", "if", "(", "!", "buffer", ".", "isExpandable", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"buffer must be expandable.\"", ")", ";", "}", "this", ".", "buffer", "=", "buffer", ";", "this", ".", "offset", "=", "offset", ";", "this", ".", "position", "=", "0", ";", "}" ]
Wrap a given buffer beginning at an offset. @param buffer to wrap @param offset at which the puts will occur.
[ "Wrap", "a", "given", "buffer", "beginning", "at", "an", "offset", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/io/ExpandableDirectBufferOutputStream.java#L62-L73
27,721
real-logic/agrona
agrona/src/main/java/org/agrona/Verify.java
Verify.present
public static void present(final Map<?, ?> map, final Object key, final String name) { if (null == map.get(key)) { throw new IllegalStateException(name + " not found in map for key: " + key); } }
java
public static void present(final Map<?, ?> map, final Object key, final String name) { if (null == map.get(key)) { throw new IllegalStateException(name + " not found in map for key: " + key); } }
[ "public", "static", "void", "present", "(", "final", "Map", "<", "?", ",", "?", ">", "map", ",", "final", "Object", "key", ",", "final", "String", "name", ")", "{", "if", "(", "null", "==", "map", ".", "get", "(", "key", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "name", "+", "\" not found in map for key: \"", "+", "key", ")", ";", "}", "}" ]
Verify that a map contains an entry for a given key. @param map to be checked. @param key to get by. @param name of entry. @throws NullPointerException if map or key is null @throws IllegalStateException if the entry does not exist.
[ "Verify", "that", "a", "map", "contains", "an", "entry", "for", "a", "given", "key", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/Verify.java#L62-L68
27,722
real-logic/agrona
agrona/src/main/java/org/agrona/BufferUtil.java
BufferUtil.address
public static long address(final ByteBuffer buffer) { if (!buffer.isDirect()) { throw new IllegalArgumentException("buffer.isDirect() must be true"); } return UNSAFE.getLong(buffer, BYTE_BUFFER_ADDRESS_FIELD_OFFSET); }
java
public static long address(final ByteBuffer buffer) { if (!buffer.isDirect()) { throw new IllegalArgumentException("buffer.isDirect() must be true"); } return UNSAFE.getLong(buffer, BYTE_BUFFER_ADDRESS_FIELD_OFFSET); }
[ "public", "static", "long", "address", "(", "final", "ByteBuffer", "buffer", ")", "{", "if", "(", "!", "buffer", ".", "isDirect", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"buffer.isDirect() must be true\"", ")", ";", "}", "return", "UNSAFE", ".", "getLong", "(", "buffer", ",", "BYTE_BUFFER_ADDRESS_FIELD_OFFSET", ")", ";", "}" ]
Get the address at which the underlying buffer storage begins. @param buffer that wraps the underlying storage. @return the memory address at which the buffer storage begins.
[ "Get", "the", "address", "at", "which", "the", "underlying", "buffer", "storage", "begins", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/BufferUtil.java#L94-L102
27,723
real-logic/agrona
agrona/src/main/java/org/agrona/nio/TransportPoller.java
TransportPoller.close
public void close() { selector.wakeup(); try { selector.close(); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
java
public void close() { selector.wakeup(); try { selector.close(); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
[ "public", "void", "close", "(", ")", "{", "selector", ".", "wakeup", "(", ")", ";", "try", "{", "selector", ".", "close", "(", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}" ]
Close NioSelector down. Returns immediately.
[ "Close", "NioSelector", "down", ".", "Returns", "immediately", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/nio/TransportPoller.java#L85-L96
27,724
real-logic/agrona
agrona/src/main/java/org/agrona/nio/TransportPoller.java
TransportPoller.selectNowWithoutProcessing
public void selectNowWithoutProcessing() { try { selector.selectNow(); selectedKeySet.reset(); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
java
public void selectNowWithoutProcessing() { try { selector.selectNow(); selectedKeySet.reset(); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
[ "public", "void", "selectNowWithoutProcessing", "(", ")", "{", "try", "{", "selector", ".", "selectNow", "(", ")", ";", "selectedKeySet", ".", "reset", "(", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}" ]
Explicit call to selectNow but without processing of selected keys.
[ "Explicit", "call", "to", "selectNow", "but", "without", "processing", "of", "selected", "keys", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/nio/TransportPoller.java#L101-L112
27,725
real-logic/agrona
agrona/src/main/java/org/agrona/collections/ArrayUtil.java
ArrayUtil.add
public static <T> T[] add(final T[] oldElements, final T elementToAdd) { final int length = oldElements.length; final T[] newElements = Arrays.copyOf(oldElements, length + 1); newElements[length] = elementToAdd; return newElements; }
java
public static <T> T[] add(final T[] oldElements, final T elementToAdd) { final int length = oldElements.length; final T[] newElements = Arrays.copyOf(oldElements, length + 1); newElements[length] = elementToAdd; return newElements; }
[ "public", "static", "<", "T", ">", "T", "[", "]", "add", "(", "final", "T", "[", "]", "oldElements", ",", "final", "T", "elementToAdd", ")", "{", "final", "int", "length", "=", "oldElements", ".", "length", ";", "final", "T", "[", "]", "newElements", "=", "Arrays", ".", "copyOf", "(", "oldElements", ",", "length", "+", "1", ")", ";", "newElements", "[", "length", "]", "=", "elementToAdd", ";", "return", "newElements", ";", "}" ]
Add an element to an array resulting in a new array. @param oldElements to have the new element added. @param elementToAdd for the new array. @param <T> type of the array. @return a new array that is one bigger and containing the new element at the end.
[ "Add", "an", "element", "to", "an", "array", "resulting", "in", "a", "new", "array", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/ArrayUtil.java#L67-L74
27,726
real-logic/agrona
agrona/src/main/java/org/agrona/collections/ArrayUtil.java
ArrayUtil.newArray
@SuppressWarnings("unchecked") public static <T> T[] newArray(final T[] oldElements, final int length) { return (T[])Array.newInstance(oldElements.getClass().getComponentType(), length); }
java
@SuppressWarnings("unchecked") public static <T> T[] newArray(final T[] oldElements, final int length) { return (T[])Array.newInstance(oldElements.getClass().getComponentType(), length); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "[", "]", "newArray", "(", "final", "T", "[", "]", "oldElements", ",", "final", "int", "length", ")", "{", "return", "(", "T", "[", "]", ")", "Array", ".", "newInstance", "(", "oldElements", ".", "getClass", "(", ")", ".", "getComponentType", "(", ")", ",", "length", ")", ";", "}" ]
Allocate a new array of the same type as another array. @param oldElements on which the new array is based. @param length of the new array. @param <T> type of the array. @return the new array of requested length.
[ "Allocate", "a", "new", "array", "of", "the", "same", "type", "as", "another", "array", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/ArrayUtil.java#L132-L136
27,727
real-logic/agrona
agrona/src/main/java/org/agrona/collections/ArrayUtil.java
ArrayUtil.ensureCapacity
public static <T> T[] ensureCapacity(final T[] oldElements, final int requiredLength) { T[] result = oldElements; if (oldElements.length < requiredLength) { result = Arrays.copyOf(oldElements, requiredLength); } return result; }
java
public static <T> T[] ensureCapacity(final T[] oldElements, final int requiredLength) { T[] result = oldElements; if (oldElements.length < requiredLength) { result = Arrays.copyOf(oldElements, requiredLength); } return result; }
[ "public", "static", "<", "T", ">", "T", "[", "]", "ensureCapacity", "(", "final", "T", "[", "]", "oldElements", ",", "final", "int", "requiredLength", ")", "{", "T", "[", "]", "result", "=", "oldElements", ";", "if", "(", "oldElements", ".", "length", "<", "requiredLength", ")", "{", "result", "=", "Arrays", ".", "copyOf", "(", "oldElements", ",", "requiredLength", ")", ";", "}", "return", "result", ";", "}" ]
Ensure an array has the required capacity. Resizing only if needed. @param oldElements to ensure that are long enough. @param requiredLength to ensure. @param <T> type of the array. @return an array of the required length.
[ "Ensure", "an", "array", "has", "the", "required", "capacity", ".", "Resizing", "only", "if", "needed", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/ArrayUtil.java#L146-L156
27,728
real-logic/agrona
agrona/src/main/java/org/agrona/collections/Object2ObjectHashMap.java
Object2ObjectHashMap.put
public V put(final Object key, final Object value) { final Object val = mapNullValue(value); requireNonNull(val, "value cannot be null"); final Object[] entries = this.entries; final int mask = entries.length - 1; int index = Hashing.evenHash(key.hashCode(), mask); Object oldValue = null; while (entries[index + 1] != null) { if (entries[index] == key || entries[index].equals(key)) { oldValue = entries[index + 1]; break; } index = next(index, mask); } if (oldValue == null) { ++size; entries[index] = key; } entries[index + 1] = val; increaseCapacity(); return unmapNullValue(oldValue); }
java
public V put(final Object key, final Object value) { final Object val = mapNullValue(value); requireNonNull(val, "value cannot be null"); final Object[] entries = this.entries; final int mask = entries.length - 1; int index = Hashing.evenHash(key.hashCode(), mask); Object oldValue = null; while (entries[index + 1] != null) { if (entries[index] == key || entries[index].equals(key)) { oldValue = entries[index + 1]; break; } index = next(index, mask); } if (oldValue == null) { ++size; entries[index] = key; } entries[index + 1] = val; increaseCapacity(); return unmapNullValue(oldValue); }
[ "public", "V", "put", "(", "final", "Object", "key", ",", "final", "Object", "value", ")", "{", "final", "Object", "val", "=", "mapNullValue", "(", "value", ")", ";", "requireNonNull", "(", "val", ",", "\"value cannot be null\"", ")", ";", "final", "Object", "[", "]", "entries", "=", "this", ".", "entries", ";", "final", "int", "mask", "=", "entries", ".", "length", "-", "1", ";", "int", "index", "=", "Hashing", ".", "evenHash", "(", "key", ".", "hashCode", "(", ")", ",", "mask", ")", ";", "Object", "oldValue", "=", "null", ";", "while", "(", "entries", "[", "index", "+", "1", "]", "!=", "null", ")", "{", "if", "(", "entries", "[", "index", "]", "==", "key", "||", "entries", "[", "index", "]", ".", "equals", "(", "key", ")", ")", "{", "oldValue", "=", "entries", "[", "index", "+", "1", "]", ";", "break", ";", "}", "index", "=", "next", "(", "index", ",", "mask", ")", ";", "}", "if", "(", "oldValue", "==", "null", ")", "{", "++", "size", ";", "entries", "[", "index", "]", "=", "key", ";", "}", "entries", "[", "index", "+", "1", "]", "=", "val", ";", "increaseCapacity", "(", ")", ";", "return", "unmapNullValue", "(", "oldValue", ")", ";", "}" ]
Put a key value pair into the map. @param key lookup key @param value new value, must not be null @return current value associated with key, or null if none found @throws IllegalArgumentException if value is null
[ "Put", "a", "key", "value", "pair", "into", "the", "map", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/Object2ObjectHashMap.java#L152-L184
27,729
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/AgentRunner.java
AgentRunner.startOnThread
public static Thread startOnThread(final AgentRunner runner, final ThreadFactory threadFactory) { final Thread thread = threadFactory.newThread(runner); thread.setName(runner.agent().roleName()); thread.start(); return thread; }
java
public static Thread startOnThread(final AgentRunner runner, final ThreadFactory threadFactory) { final Thread thread = threadFactory.newThread(runner); thread.setName(runner.agent().roleName()); thread.start(); return thread; }
[ "public", "static", "Thread", "startOnThread", "(", "final", "AgentRunner", "runner", ",", "final", "ThreadFactory", "threadFactory", ")", "{", "final", "Thread", "thread", "=", "threadFactory", ".", "newThread", "(", "runner", ")", ";", "thread", ".", "setName", "(", "runner", ".", "agent", "(", ")", ".", "roleName", "(", ")", ")", ";", "thread", ".", "start", "(", ")", ";", "return", "thread", ";", "}" ]
Start the given agent runner on a new thread. @param runner the agent runner to start. @param threadFactory the factory to use to create the thread. @return the new thread that has been started.
[ "Start", "the", "given", "agent", "runner", "on", "a", "new", "thread", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/AgentRunner.java#L95-L102
27,730
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/broadcast/BroadcastBufferDescriptor.java
BroadcastBufferDescriptor.checkCapacity
public static void checkCapacity(final int capacity) { if (!BitUtil.isPowerOfTwo(capacity)) { final String msg = "capacity must be a positive power of 2 + TRAILER_LENGTH: capacity=" + capacity; throw new IllegalStateException(msg); } }
java
public static void checkCapacity(final int capacity) { if (!BitUtil.isPowerOfTwo(capacity)) { final String msg = "capacity must be a positive power of 2 + TRAILER_LENGTH: capacity=" + capacity; throw new IllegalStateException(msg); } }
[ "public", "static", "void", "checkCapacity", "(", "final", "int", "capacity", ")", "{", "if", "(", "!", "BitUtil", ".", "isPowerOfTwo", "(", "capacity", ")", ")", "{", "final", "String", "msg", "=", "\"capacity must be a positive power of 2 + TRAILER_LENGTH: capacity=\"", "+", "capacity", ";", "throw", "new", "IllegalStateException", "(", "msg", ")", ";", "}", "}" ]
Check the the buffer capacity is the correct size. @param capacity to be checked. @throws IllegalStateException if the buffer capacity is not a power of 2.
[ "Check", "the", "the", "buffer", "capacity", "is", "the", "correct", "size", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/broadcast/BroadcastBufferDescriptor.java#L66-L73
27,731
real-logic/agrona
agrona/src/main/java/org/agrona/io/DirectBufferOutputStream.java
DirectBufferOutputStream.write
public void write(final int b) { if (position == length) { throw new IllegalStateException("position has reached the end of underlying buffer"); } buffer.putByte(offset + position, (byte)b); ++position; }
java
public void write(final int b) { if (position == length) { throw new IllegalStateException("position has reached the end of underlying buffer"); } buffer.putByte(offset + position, (byte)b); ++position; }
[ "public", "void", "write", "(", "final", "int", "b", ")", "{", "if", "(", "position", "==", "length", ")", "{", "throw", "new", "IllegalStateException", "(", "\"position has reached the end of underlying buffer\"", ")", ";", "}", "buffer", ".", "putByte", "(", "offset", "+", "position", ",", "(", "byte", ")", "b", ")", ";", "++", "position", ";", "}" ]
Write a byte to buffer. @param b to be written. @throws IllegalStateException if insufficient capacity remains in the buffer.
[ "Write", "a", "byte", "to", "buffer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/io/DirectBufferOutputStream.java#L111-L120
27,732
real-logic/agrona
agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
DeadlineTimerWheel.cancelTimer
public boolean cancelTimer(final long timerId) { final int wheelIndex = tickForTimerId(timerId); final int arrayIndex = indexInTickArray(timerId); if (wheelIndex < wheel.length) { final long[] array = wheel[wheelIndex]; if (arrayIndex < array.length && NULL_TIMER != array[arrayIndex]) { array[arrayIndex] = NULL_TIMER; timerCount--; return true; } } return false; }
java
public boolean cancelTimer(final long timerId) { final int wheelIndex = tickForTimerId(timerId); final int arrayIndex = indexInTickArray(timerId); if (wheelIndex < wheel.length) { final long[] array = wheel[wheelIndex]; if (arrayIndex < array.length && NULL_TIMER != array[arrayIndex]) { array[arrayIndex] = NULL_TIMER; timerCount--; return true; } } return false; }
[ "public", "boolean", "cancelTimer", "(", "final", "long", "timerId", ")", "{", "final", "int", "wheelIndex", "=", "tickForTimerId", "(", "timerId", ")", ";", "final", "int", "arrayIndex", "=", "indexInTickArray", "(", "timerId", ")", ";", "if", "(", "wheelIndex", "<", "wheel", ".", "length", ")", "{", "final", "long", "[", "]", "array", "=", "wheel", "[", "wheelIndex", "]", ";", "if", "(", "arrayIndex", "<", "array", ".", "length", "&&", "NULL_TIMER", "!=", "array", "[", "arrayIndex", "]", ")", "{", "array", "[", "arrayIndex", "]", "=", "NULL_TIMER", ";", "timerCount", "--", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Cancel a previously scheduled timer. @param timerId of the timer to cancel. @return true if successful otherwise false if the timerId did not exist.
[ "Cancel", "a", "previously", "scheduled", "timer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java#L237-L256
27,733
real-logic/agrona
agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
DeadlineTimerWheel.poll
public int poll(final long now, final TimerHandler handler, final int maxTimersToExpire) { int timersExpired = 0; if (timerCount > 0) { final long[] array = wheel[currentTick & wheelMask]; for (int i = 0, length = array.length; i < length && maxTimersToExpire > timersExpired; i++) { final long deadline = array[pollIndex]; if (deadline <= now) { array[pollIndex] = NULL_TIMER; timerCount--; timersExpired++; if (!handler.onTimerExpiry(timeUnit, now, timerIdForSlot(currentTick & wheelMask, pollIndex))) { array[pollIndex] = deadline; timerCount++; return timersExpired; } } pollIndex = (pollIndex + 1) >= length ? 0 : (pollIndex + 1); } if (maxTimersToExpire > timersExpired && currentTickTime() <= now) { currentTick++; pollIndex = 0; } else if (pollIndex >= array.length) { pollIndex = 0; } } else if (currentTickTime() <= now) { currentTick++; pollIndex = 0; } return timersExpired; }
java
public int poll(final long now, final TimerHandler handler, final int maxTimersToExpire) { int timersExpired = 0; if (timerCount > 0) { final long[] array = wheel[currentTick & wheelMask]; for (int i = 0, length = array.length; i < length && maxTimersToExpire > timersExpired; i++) { final long deadline = array[pollIndex]; if (deadline <= now) { array[pollIndex] = NULL_TIMER; timerCount--; timersExpired++; if (!handler.onTimerExpiry(timeUnit, now, timerIdForSlot(currentTick & wheelMask, pollIndex))) { array[pollIndex] = deadline; timerCount++; return timersExpired; } } pollIndex = (pollIndex + 1) >= length ? 0 : (pollIndex + 1); } if (maxTimersToExpire > timersExpired && currentTickTime() <= now) { currentTick++; pollIndex = 0; } else if (pollIndex >= array.length) { pollIndex = 0; } } else if (currentTickTime() <= now) { currentTick++; pollIndex = 0; } return timersExpired; }
[ "public", "int", "poll", "(", "final", "long", "now", ",", "final", "TimerHandler", "handler", ",", "final", "int", "maxTimersToExpire", ")", "{", "int", "timersExpired", "=", "0", ";", "if", "(", "timerCount", ">", "0", ")", "{", "final", "long", "[", "]", "array", "=", "wheel", "[", "currentTick", "&", "wheelMask", "]", ";", "for", "(", "int", "i", "=", "0", ",", "length", "=", "array", ".", "length", ";", "i", "<", "length", "&&", "maxTimersToExpire", ">", "timersExpired", ";", "i", "++", ")", "{", "final", "long", "deadline", "=", "array", "[", "pollIndex", "]", ";", "if", "(", "deadline", "<=", "now", ")", "{", "array", "[", "pollIndex", "]", "=", "NULL_TIMER", ";", "timerCount", "--", ";", "timersExpired", "++", ";", "if", "(", "!", "handler", ".", "onTimerExpiry", "(", "timeUnit", ",", "now", ",", "timerIdForSlot", "(", "currentTick", "&", "wheelMask", ",", "pollIndex", ")", ")", ")", "{", "array", "[", "pollIndex", "]", "=", "deadline", ";", "timerCount", "++", ";", "return", "timersExpired", ";", "}", "}", "pollIndex", "=", "(", "pollIndex", "+", "1", ")", ">=", "length", "?", "0", ":", "(", "pollIndex", "+", "1", ")", ";", "}", "if", "(", "maxTimersToExpire", ">", "timersExpired", "&&", "currentTickTime", "(", ")", "<=", "now", ")", "{", "currentTick", "++", ";", "pollIndex", "=", "0", ";", "}", "else", "if", "(", "pollIndex", ">=", "array", ".", "length", ")", "{", "pollIndex", "=", "0", ";", "}", "}", "else", "if", "(", "currentTickTime", "(", ")", "<=", "now", ")", "{", "currentTick", "++", ";", "pollIndex", "=", "0", ";", "}", "return", "timersExpired", ";", "}" ]
Poll for timers expired by the deadline passing. @param now current time to compare deadlines against. @param handler to call for each expired timer. @param maxTimersToExpire to process in one poll operation. @return number of expired timers.
[ "Poll", "for", "timers", "expired", "by", "the", "deadline", "passing", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java#L266-L313
27,734
real-logic/agrona
agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
DeadlineTimerWheel.forEach
public void forEach(final TimerConsumer consumer) { long numTimersLeft = timerCount; for (int j = currentTick, end = currentTick + wheel.length; j <= end; j++) { final long[] array = wheel[j & wheelMask]; for (int i = 0, length = array.length; i < length; i++) { final long deadline = array[i]; if (deadline != NULL_TIMER) { consumer.accept(deadline, timerIdForSlot(j & wheelMask, i)); if (--numTimersLeft == 0) { return; } } } } }
java
public void forEach(final TimerConsumer consumer) { long numTimersLeft = timerCount; for (int j = currentTick, end = currentTick + wheel.length; j <= end; j++) { final long[] array = wheel[j & wheelMask]; for (int i = 0, length = array.length; i < length; i++) { final long deadline = array[i]; if (deadline != NULL_TIMER) { consumer.accept(deadline, timerIdForSlot(j & wheelMask, i)); if (--numTimersLeft == 0) { return; } } } } }
[ "public", "void", "forEach", "(", "final", "TimerConsumer", "consumer", ")", "{", "long", "numTimersLeft", "=", "timerCount", ";", "for", "(", "int", "j", "=", "currentTick", ",", "end", "=", "currentTick", "+", "wheel", ".", "length", ";", "j", "<=", "end", ";", "j", "++", ")", "{", "final", "long", "[", "]", "array", "=", "wheel", "[", "j", "&", "wheelMask", "]", ";", "for", "(", "int", "i", "=", "0", ",", "length", "=", "array", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "final", "long", "deadline", "=", "array", "[", "i", "]", ";", "if", "(", "deadline", "!=", "NULL_TIMER", ")", "{", "consumer", ".", "accept", "(", "deadline", ",", "timerIdForSlot", "(", "j", "&", "wheelMask", ",", "i", ")", ")", ";", "if", "(", "--", "numTimersLeft", "==", "0", ")", "{", "return", ";", "}", "}", "}", "}", "}" ]
Iterate over wheel so all active timers can be consumed without expiring them. @param consumer to call for each active timer.
[ "Iterate", "over", "wheel", "so", "all", "active", "timers", "can", "be", "consumed", "without", "expiring", "them", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java#L320-L343
27,735
real-logic/agrona
agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
DeadlineTimerWheel.deadline
public long deadline(final long timerId) { final int wheelIndex = tickForTimerId(timerId); final int arrayIndex = indexInTickArray(timerId); if (wheelIndex < wheel.length) { final long[] array = wheel[wheelIndex]; if (arrayIndex < array.length) { return array[arrayIndex]; } } return NULL_TIMER; }
java
public long deadline(final long timerId) { final int wheelIndex = tickForTimerId(timerId); final int arrayIndex = indexInTickArray(timerId); if (wheelIndex < wheel.length) { final long[] array = wheel[wheelIndex]; if (arrayIndex < array.length) { return array[arrayIndex]; } } return NULL_TIMER; }
[ "public", "long", "deadline", "(", "final", "long", "timerId", ")", "{", "final", "int", "wheelIndex", "=", "tickForTimerId", "(", "timerId", ")", ";", "final", "int", "arrayIndex", "=", "indexInTickArray", "(", "timerId", ")", ";", "if", "(", "wheelIndex", "<", "wheel", ".", "length", ")", "{", "final", "long", "[", "]", "array", "=", "wheel", "[", "wheelIndex", "]", ";", "if", "(", "arrayIndex", "<", "array", ".", "length", ")", "{", "return", "array", "[", "arrayIndex", "]", ";", "}", "}", "return", "NULL_TIMER", ";", "}" ]
Return the deadline for the given timerId. @param timerId of the timer to return the deadline of. @return deadline for the given timerId or {@link #NULL_TIMER} if timerId is not running.
[ "Return", "the", "deadline", "for", "the", "given", "timerId", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java#L351-L367
27,736
real-logic/agrona
agrona/src/main/java/org/agrona/AsciiSequenceView.java
AsciiSequenceView.wrap
public AsciiSequenceView wrap(final DirectBuffer buffer, final int offset, final int length) { this.buffer = buffer; this.offset = offset; this.length = length; return this; }
java
public AsciiSequenceView wrap(final DirectBuffer buffer, final int offset, final int length) { this.buffer = buffer; this.offset = offset; this.length = length; return this; }
[ "public", "AsciiSequenceView", "wrap", "(", "final", "DirectBuffer", "buffer", ",", "final", "int", "offset", ",", "final", "int", "length", ")", "{", "this", ".", "buffer", "=", "buffer", ";", "this", ".", "offset", "=", "offset", ";", "this", ".", "length", "=", "length", ";", "return", "this", ";", "}" ]
Wrap a range of an existing buffer containing an ASCII sequence. @param buffer containing the ASCII sequence. @param offset at which the ASCII sequence begins. @param length of the ASCII sequence in bytes. @return this for a fluent API.
[ "Wrap", "a", "range", "of", "an", "existing", "buffer", "containing", "an", "ASCII", "sequence", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/AsciiSequenceView.java#L97-L104
27,737
real-logic/agrona
agrona/src/main/java/org/agrona/collections/Hashing.java
Hashing.hash
public static <K> int hash(final K value, final int mask) { final int hash = value.hashCode(); return hash & mask; }
java
public static <K> int hash(final K value, final int mask) { final int hash = value.hashCode(); return hash & mask; }
[ "public", "static", "<", "K", ">", "int", "hash", "(", "final", "K", "value", ",", "final", "int", "mask", ")", "{", "final", "int", "hash", "=", "value", ".", "hashCode", "(", ")", ";", "return", "hash", "&", "mask", ";", "}" ]
Generate a hash for a K value. @param <K> is the type of value @param value to be hashed. @param mask mask to be applied that must be a power of 2 - 1. @return the hash of the value.
[ "Generate", "a", "hash", "for", "a", "K", "value", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/Hashing.java#L75-L80
27,738
real-logic/agrona
agrona/src/main/java/org/agrona/collections/Hashing.java
Hashing.hash
public static int hash(final long value, final int mask) { long hash = value * 31; hash = (int)hash ^ (int)(hash >>> 32); return (int)hash & mask; }
java
public static int hash(final long value, final int mask) { long hash = value * 31; hash = (int)hash ^ (int)(hash >>> 32); return (int)hash & mask; }
[ "public", "static", "int", "hash", "(", "final", "long", "value", ",", "final", "int", "mask", ")", "{", "long", "hash", "=", "value", "*", "31", ";", "hash", "=", "(", "int", ")", "hash", "^", "(", "int", ")", "(", "hash", ">>>", "32", ")", ";", "return", "(", "int", ")", "hash", "&", "mask", ";", "}" ]
Generate a hash for a long value. @param value to be hashed. @param mask mask to be applied that must be a power of 2 - 1. @return the hash of the value.
[ "Generate", "a", "hash", "for", "a", "long", "value", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/Hashing.java#L89-L95
27,739
real-logic/agrona
agrona/src/main/java/org/agrona/collections/Hashing.java
Hashing.evenHash
public static int evenHash(final long value, final int mask) { int hash = (int)value ^ (int)(value >>> 32); hash = (hash << 1) - (hash << 8); return hash & mask; }
java
public static int evenHash(final long value, final int mask) { int hash = (int)value ^ (int)(value >>> 32); hash = (hash << 1) - (hash << 8); return hash & mask; }
[ "public", "static", "int", "evenHash", "(", "final", "long", "value", ",", "final", "int", "mask", ")", "{", "int", "hash", "=", "(", "int", ")", "value", "^", "(", "int", ")", "(", "value", ">>>", "32", ")", ";", "hash", "=", "(", "hash", "<<", "1", ")", "-", "(", "hash", "<<", "8", ")", ";", "return", "hash", "&", "mask", ";", "}" ]
Generate an even hash for a long value. @param value to be hashed. @param mask mask to be applied that must be a power of 2 - 1. @return the hash of the value which is always even.
[ "Generate", "an", "even", "hash", "for", "a", "long", "value", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/Hashing.java#L118-L124
27,740
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java
RecordBuffer.forEach
public void forEach(final RecordHandler handler) { int offset = endOfPositionField; final int position = position(); while (offset < position) { if (statusVolatile(offset) == COMMITTED) { final int key = key(offset); handler.onRecord(key, offset + SIZE_OF_RECORD_FRAME); } offset += slotSize; } }
java
public void forEach(final RecordHandler handler) { int offset = endOfPositionField; final int position = position(); while (offset < position) { if (statusVolatile(offset) == COMMITTED) { final int key = key(offset); handler.onRecord(key, offset + SIZE_OF_RECORD_FRAME); } offset += slotSize; } }
[ "public", "void", "forEach", "(", "final", "RecordHandler", "handler", ")", "{", "int", "offset", "=", "endOfPositionField", ";", "final", "int", "position", "=", "position", "(", ")", ";", "while", "(", "offset", "<", "position", ")", "{", "if", "(", "statusVolatile", "(", "offset", ")", "==", "COMMITTED", ")", "{", "final", "int", "key", "=", "key", "(", "offset", ")", ";", "handler", ".", "onRecord", "(", "key", ",", "offset", "+", "SIZE_OF_RECORD_FRAME", ")", ";", "}", "offset", "+=", "slotSize", ";", "}", "}" ]
Read each record out of the buffer in turn. @param handler the handler is called once for each record in the buffer.
[ "Read", "each", "record", "out", "of", "the", "buffer", "in", "turn", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java#L145-L160
27,741
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java
RecordBuffer.get
public int get(final int key) { int offset = endOfPositionField; final int position = position(); while (offset < position) { if (statusVolatile(offset) == COMMITTED && key == key(offset)) { return offset + SIZE_OF_RECORD_FRAME; } offset += slotSize; } return DID_NOT_CLAIM_RECORD; }
java
public int get(final int key) { int offset = endOfPositionField; final int position = position(); while (offset < position) { if (statusVolatile(offset) == COMMITTED && key == key(offset)) { return offset + SIZE_OF_RECORD_FRAME; } offset += slotSize; } return DID_NOT_CLAIM_RECORD; }
[ "public", "int", "get", "(", "final", "int", "key", ")", "{", "int", "offset", "=", "endOfPositionField", ";", "final", "int", "position", "=", "position", "(", ")", ";", "while", "(", "offset", "<", "position", ")", "{", "if", "(", "statusVolatile", "(", "offset", ")", "==", "COMMITTED", "&&", "key", "==", "key", "(", "offset", ")", ")", "{", "return", "offset", "+", "SIZE_OF_RECORD_FRAME", ";", "}", "offset", "+=", "slotSize", ";", "}", "return", "DID_NOT_CLAIM_RECORD", ";", "}" ]
Search for the first record with the specified key. @param key the key to search for. @return the offset of the start of the record within the buffer or {@code DID_NOT_CLAIM_RECORD} if no record with the specified key.
[ "Search", "for", "the", "first", "record", "with", "the", "specified", "key", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java#L169-L185
27,742
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java
RecordBuffer.withRecord
public boolean withRecord(final int key, final RecordWriter writer) { final int claimedOffset = claimRecord(key); if (claimedOffset == DID_NOT_CLAIM_RECORD) { return false; } try { writer.writeRecord(claimedOffset); } finally { commit(claimedOffset); } return true; }
java
public boolean withRecord(final int key, final RecordWriter writer) { final int claimedOffset = claimRecord(key); if (claimedOffset == DID_NOT_CLAIM_RECORD) { return false; } try { writer.writeRecord(claimedOffset); } finally { commit(claimedOffset); } return true; }
[ "public", "boolean", "withRecord", "(", "final", "int", "key", ",", "final", "RecordWriter", "writer", ")", "{", "final", "int", "claimedOffset", "=", "claimRecord", "(", "key", ")", ";", "if", "(", "claimedOffset", "==", "DID_NOT_CLAIM_RECORD", ")", "{", "return", "false", ";", "}", "try", "{", "writer", ".", "writeRecord", "(", "claimedOffset", ")", ";", "}", "finally", "{", "commit", "(", "claimedOffset", ")", ";", "}", "return", "true", ";", "}" ]
High level and safe way of writing a record to the buffer. @param key the key to associate the record with @param writer the callback which is passed the record to write. @return whether the write succeeded or not.
[ "High", "level", "and", "safe", "way", "of", "writing", "a", "record", "to", "the", "buffer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java#L194-L212
27,743
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java
RecordBuffer.claimRecord
public int claimRecord(final int key) { int offset = endOfPositionField; while (offset < position()) { if (key == key(offset)) { // If someone else is writing something with the same key then abort if (statusVolatile(offset) == PENDING) { return DID_NOT_CLAIM_RECORD; } else // state == COMMITTED { compareAndSetStatus(offset, COMMITTED, PENDING); return offset + SIZE_OF_RECORD_FRAME; } } offset += slotSize; } if ((offset + slotSize) > buffer.capacity()) { return DID_NOT_CLAIM_RECORD; } final int claimOffset = movePosition(slotSize); compareAndSetStatus(claimOffset, UNUSED, PENDING); key(claimOffset, key); return claimOffset + SIZE_OF_RECORD_FRAME; }
java
public int claimRecord(final int key) { int offset = endOfPositionField; while (offset < position()) { if (key == key(offset)) { // If someone else is writing something with the same key then abort if (statusVolatile(offset) == PENDING) { return DID_NOT_CLAIM_RECORD; } else // state == COMMITTED { compareAndSetStatus(offset, COMMITTED, PENDING); return offset + SIZE_OF_RECORD_FRAME; } } offset += slotSize; } if ((offset + slotSize) > buffer.capacity()) { return DID_NOT_CLAIM_RECORD; } final int claimOffset = movePosition(slotSize); compareAndSetStatus(claimOffset, UNUSED, PENDING); key(claimOffset, key); return claimOffset + SIZE_OF_RECORD_FRAME; }
[ "public", "int", "claimRecord", "(", "final", "int", "key", ")", "{", "int", "offset", "=", "endOfPositionField", ";", "while", "(", "offset", "<", "position", "(", ")", ")", "{", "if", "(", "key", "==", "key", "(", "offset", ")", ")", "{", "// If someone else is writing something with the same key then abort", "if", "(", "statusVolatile", "(", "offset", ")", "==", "PENDING", ")", "{", "return", "DID_NOT_CLAIM_RECORD", ";", "}", "else", "// state == COMMITTED", "{", "compareAndSetStatus", "(", "offset", ",", "COMMITTED", ",", "PENDING", ")", ";", "return", "offset", "+", "SIZE_OF_RECORD_FRAME", ";", "}", "}", "offset", "+=", "slotSize", ";", "}", "if", "(", "(", "offset", "+", "slotSize", ")", ">", "buffer", ".", "capacity", "(", ")", ")", "{", "return", "DID_NOT_CLAIM_RECORD", ";", "}", "final", "int", "claimOffset", "=", "movePosition", "(", "slotSize", ")", ";", "compareAndSetStatus", "(", "claimOffset", ",", "UNUSED", ",", "PENDING", ")", ";", "key", "(", "claimOffset", ",", "key", ")", ";", "return", "claimOffset", "+", "SIZE_OF_RECORD_FRAME", ";", "}" ]
Claim a record in the buffer. Each record has a unique key. @param key the key to claim the record with. @return the offset at which record was claimed or {@code DID_NOT_CLAIM_RECORD} if the claim failed. @see RecordBuffer#commit(int)
[ "Claim", "a", "record", "in", "the", "buffer", ".", "Each", "record", "has", "a", "unique", "key", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/RecordBuffer.java#L221-L254
27,744
real-logic/agrona
agrona/src/main/java/org/agrona/SemanticVersion.java
SemanticVersion.compose
public static int compose(final int major, final int minor, final int patch) { if (major < 0 || major > 255) { throw new IllegalArgumentException("major must be 0-255: " + major); } if (minor < 0 || minor > 255) { throw new IllegalArgumentException("minor must be 0-255: " + minor); } if (patch < 0 || patch > 255) { throw new IllegalArgumentException("patch must be 0-255: " + patch); } if (major + minor + patch == 0) { throw new IllegalArgumentException("all parts cannot be zero"); } return (major << 16) | (minor << 8) | patch; }
java
public static int compose(final int major, final int minor, final int patch) { if (major < 0 || major > 255) { throw new IllegalArgumentException("major must be 0-255: " + major); } if (minor < 0 || minor > 255) { throw new IllegalArgumentException("minor must be 0-255: " + minor); } if (patch < 0 || patch > 255) { throw new IllegalArgumentException("patch must be 0-255: " + patch); } if (major + minor + patch == 0) { throw new IllegalArgumentException("all parts cannot be zero"); } return (major << 16) | (minor << 8) | patch; }
[ "public", "static", "int", "compose", "(", "final", "int", "major", ",", "final", "int", "minor", ",", "final", "int", "patch", ")", "{", "if", "(", "major", "<", "0", "||", "major", ">", "255", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"major must be 0-255: \"", "+", "major", ")", ";", "}", "if", "(", "minor", "<", "0", "||", "minor", ">", "255", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"minor must be 0-255: \"", "+", "minor", ")", ";", "}", "if", "(", "patch", "<", "0", "||", "patch", ">", "255", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"patch must be 0-255: \"", "+", "patch", ")", ";", "}", "if", "(", "major", "+", "minor", "+", "patch", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"all parts cannot be zero\"", ")", ";", "}", "return", "(", "major", "<<", "16", ")", "|", "(", "minor", "<<", "8", ")", "|", "patch", ";", "}" ]
Compose a 4-byte integer with major, minor, and patch version stored in the least significant 3 bytes. The sum of the components must be greater than zero. @param major version in the range 0-255. @param minor version in the range 0-255 @param patch version in the range 0-255. @return the semantic version made from the three components. @throws IllegalArgumentException if the values are outside acceptable range.
[ "Compose", "a", "4", "-", "byte", "integer", "with", "major", "minor", "and", "patch", "version", "stored", "in", "the", "least", "significant", "3", "bytes", ".", "The", "sum", "of", "the", "components", "must", "be", "greater", "than", "zero", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SemanticVersion.java#L33-L56
27,745
real-logic/agrona
agrona/src/main/java/org/agrona/nio/NioSelectedKeySet.java
NioSelectedKeySet.forEach
public int forEach(final ToIntFunction<SelectionKey> function) { int handledFrames = 0; final SelectionKey[] keys = this.keys; for (int i = size - 1; i >= 0; i--) { handledFrames += function.applyAsInt(keys[i]); } size = 0; return handledFrames; }
java
public int forEach(final ToIntFunction<SelectionKey> function) { int handledFrames = 0; final SelectionKey[] keys = this.keys; for (int i = size - 1; i >= 0; i--) { handledFrames += function.applyAsInt(keys[i]); } size = 0; return handledFrames; }
[ "public", "int", "forEach", "(", "final", "ToIntFunction", "<", "SelectionKey", ">", "function", ")", "{", "int", "handledFrames", "=", "0", ";", "final", "SelectionKey", "[", "]", "keys", "=", "this", ".", "keys", ";", "for", "(", "int", "i", "=", "size", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "handledFrames", "+=", "function", ".", "applyAsInt", "(", "keys", "[", "i", "]", ")", ";", "}", "size", "=", "0", ";", "return", "handledFrames", ";", "}" ]
Iterate over the key set and apply the given function. @param function to apply to each {@link java.nio.channels.SelectionKey} @return number of handled frames
[ "Iterate", "over", "the", "key", "set", "and", "apply", "the", "given", "function", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/nio/NioSelectedKeySet.java#L134-L147
27,746
real-logic/agrona
agrona/src/main/java/org/agrona/collections/BiInt2ObjectMap.java
BiInt2ObjectMap.compact
public void compact() { final int idealCapacity = (int)Math.round(size() * (1.0 / loadFactor)); rehash(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, idealCapacity))); }
java
public void compact() { final int idealCapacity = (int)Math.round(size() * (1.0 / loadFactor)); rehash(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, idealCapacity))); }
[ "public", "void", "compact", "(", ")", "{", "final", "int", "idealCapacity", "=", "(", "int", ")", "Math", ".", "round", "(", "size", "(", ")", "*", "(", "1.0", "/", "loadFactor", ")", ")", ";", "rehash", "(", "findNextPositivePowerOfTwo", "(", "Math", ".", "max", "(", "MIN_CAPACITY", ",", "idealCapacity", ")", ")", ")", ";", "}" ]
Compact the backing arrays by rehashing with a capacity just larger than current size and giving consideration to the load factor.
[ "Compact", "the", "backing", "arrays", "by", "rehashing", "with", "a", "capacity", "just", "larger", "than", "current", "size", "and", "giving", "consideration", "to", "the", "load", "factor", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/BiInt2ObjectMap.java#L149-L153
27,747
real-logic/agrona
agrona/src/main/java/org/agrona/console/ContinueBarrier.java
ContinueBarrier.await
public boolean await() { System.out.format("%n%s (y/n): ", label).flush(); final Scanner in = new Scanner(System.in); final String line = in.nextLine(); return "y".equalsIgnoreCase(line); }
java
public boolean await() { System.out.format("%n%s (y/n): ", label).flush(); final Scanner in = new Scanner(System.in); final String line = in.nextLine(); return "y".equalsIgnoreCase(line); }
[ "public", "boolean", "await", "(", ")", "{", "System", ".", "out", ".", "format", "(", "\"%n%s (y/n): \"", ",", "label", ")", ".", "flush", "(", ")", ";", "final", "Scanner", "in", "=", "new", "Scanner", "(", "System", ".", "in", ")", ";", "final", "String", "line", "=", "in", ".", "nextLine", "(", ")", ";", "return", "\"y\"", ".", "equalsIgnoreCase", "(", "line", ")", ";", "}" ]
Await for input that matches the provided command. @return true if y otherwise false
[ "Await", "for", "input", "that", "matches", "the", "provided", "command", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/console/ContinueBarrier.java#L43-L50
27,748
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.addInt
public void addInt( @DoNotSub final int index, final int element) { checkIndexForAdd(index); @DoNotSub final int requiredSize = size + 1; ensureCapacityPrivate(requiredSize); if (index < size) { System.arraycopy(elements, index, elements, index + 1, size - index); } elements[index] = element; size++; }
java
public void addInt( @DoNotSub final int index, final int element) { checkIndexForAdd(index); @DoNotSub final int requiredSize = size + 1; ensureCapacityPrivate(requiredSize); if (index < size) { System.arraycopy(elements, index, elements, index + 1, size - index); } elements[index] = element; size++; }
[ "public", "void", "addInt", "(", "@", "DoNotSub", "final", "int", "index", ",", "final", "int", "element", ")", "{", "checkIndexForAdd", "(", "index", ")", ";", "@", "DoNotSub", "final", "int", "requiredSize", "=", "size", "+", "1", ";", "ensureCapacityPrivate", "(", "requiredSize", ")", ";", "if", "(", "index", "<", "size", ")", "{", "System", ".", "arraycopy", "(", "elements", ",", "index", ",", "elements", ",", "index", "+", "1", ",", "size", "-", "index", ")", ";", "}", "elements", "[", "index", "]", "=", "element", ";", "size", "++", ";", "}" ]
Add a element without boxing at a given index. @param index at which the element should be added. @param element to be added.
[ "Add", "a", "element", "without", "boxing", "at", "a", "given", "index", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L196-L212
27,749
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.setInt
public int setInt( @DoNotSub final int index, final int element) { checkIndex(index); final int previous = elements[index]; elements[index] = element; return previous; }
java
public int setInt( @DoNotSub final int index, final int element) { checkIndex(index); final int previous = elements[index]; elements[index] = element; return previous; }
[ "public", "int", "setInt", "(", "@", "DoNotSub", "final", "int", "index", ",", "final", "int", "element", ")", "{", "checkIndex", "(", "index", ")", ";", "final", "int", "previous", "=", "elements", "[", "index", "]", ";", "elements", "[", "index", "]", "=", "element", ";", "return", "previous", ";", "}" ]
Set an element at a given index without boxing. @param index at which to set the element. @param element to be added. @return the previous element at the index.
[ "Set", "an", "element", "at", "a", "given", "index", "without", "boxing", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L230-L240
27,750
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.remove
public Integer remove( @DoNotSub final int index) { checkIndex(index); final int value = elements[index]; @DoNotSub final int moveCount = size - index - 1; if (moveCount > 0) { System.arraycopy(elements, index + 1, elements, index, moveCount); } size--; return value; }
java
public Integer remove( @DoNotSub final int index) { checkIndex(index); final int value = elements[index]; @DoNotSub final int moveCount = size - index - 1; if (moveCount > 0) { System.arraycopy(elements, index + 1, elements, index, moveCount); } size--; return value; }
[ "public", "Integer", "remove", "(", "@", "DoNotSub", "final", "int", "index", ")", "{", "checkIndex", "(", "index", ")", ";", "final", "int", "value", "=", "elements", "[", "index", "]", ";", "@", "DoNotSub", "final", "int", "moveCount", "=", "size", "-", "index", "-", "1", ";", "if", "(", "moveCount", ">", "0", ")", "{", "System", ".", "arraycopy", "(", "elements", ",", "index", "+", "1", ",", "elements", ",", "index", ",", "moveCount", ")", ";", "}", "size", "--", ";", "return", "value", ";", "}" ]
Remove at a given index. @param index of the element to be removed. @return the existing value at this index.
[ "Remove", "at", "a", "given", "index", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L299-L315
27,751
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.fastUnorderedRemove
public int fastUnorderedRemove( @DoNotSub final int index) { checkIndex(index); final int value = elements[index]; elements[index] = elements[--size]; return value; }
java
public int fastUnorderedRemove( @DoNotSub final int index) { checkIndex(index); final int value = elements[index]; elements[index] = elements[--size]; return value; }
[ "public", "int", "fastUnorderedRemove", "(", "@", "DoNotSub", "final", "int", "index", ")", "{", "checkIndex", "(", "index", ")", ";", "final", "int", "value", "=", "elements", "[", "index", "]", ";", "elements", "[", "index", "]", "=", "elements", "[", "--", "size", "]", ";", "return", "value", ";", "}" ]
Removes element at index, but instead of copying all elements to the left, it replaces the item in the slot with the last item in the list. This avoids the copy costs at the expense of preserving list order. If index is the last element it is just removed. @param index of the element to be removed. @return the existing value at this index. @throws IndexOutOfBoundsException if index is out of bounds.
[ "Removes", "element", "at", "index", "but", "instead", "of", "copying", "all", "elements", "to", "the", "left", "it", "replaces", "the", "item", "in", "the", "slot", "with", "the", "last", "item", "in", "the", "list", ".", "This", "avoids", "the", "copy", "costs", "at", "the", "expense", "of", "preserving", "list", "order", ".", "If", "index", "is", "the", "last", "element", "it", "is", "just", "removed", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L326-L335
27,752
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.removeInt
public boolean removeInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { remove(index); return true; } return false; }
java
public boolean removeInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { remove(index); return true; } return false; }
[ "public", "boolean", "removeInt", "(", "final", "int", "value", ")", "{", "@", "DoNotSub", "final", "int", "index", "=", "indexOf", "(", "value", ")", ";", "if", "(", "-", "1", "!=", "index", ")", "{", "remove", "(", "index", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Remove the first instance of a value if found in the list. @param value to be removed. @return true if successful otherwise false.
[ "Remove", "the", "first", "instance", "of", "a", "value", "if", "found", "in", "the", "list", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L343-L354
27,753
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.fastUnorderedRemoveInt
public boolean fastUnorderedRemoveInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { elements[index] = elements[--size]; return true; } return false; }
java
public boolean fastUnorderedRemoveInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { elements[index] = elements[--size]; return true; } return false; }
[ "public", "boolean", "fastUnorderedRemoveInt", "(", "final", "int", "value", ")", "{", "@", "DoNotSub", "final", "int", "index", "=", "indexOf", "(", "value", ")", ";", "if", "(", "-", "1", "!=", "index", ")", "{", "elements", "[", "index", "]", "=", "elements", "[", "--", "size", "]", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Remove the first instance of a value if found in the list and replaces it with the last item in the list. This saves a copy down of all items at the expense of not preserving list order. @param value to be removed. @return true if successful otherwise false.
[ "Remove", "the", "first", "instance", "of", "a", "value", "if", "found", "in", "the", "list", "and", "replaces", "it", "with", "the", "last", "item", "in", "the", "list", ".", "This", "saves", "a", "copy", "down", "of", "all", "items", "at", "the", "expense", "of", "not", "preserving", "list", "order", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L363-L374
27,754
real-logic/agrona
agrona/src/main/java/org/agrona/collections/IntArrayList.java
IntArrayList.toIntArray
public int[] toIntArray(final int[] dst) { if (dst.length == size) { System.arraycopy(elements, 0, dst, 0, dst.length); return dst; } else { return Arrays.copyOf(elements, size); } }
java
public int[] toIntArray(final int[] dst) { if (dst.length == size) { System.arraycopy(elements, 0, dst, 0, dst.length); return dst; } else { return Arrays.copyOf(elements, size); } }
[ "public", "int", "[", "]", "toIntArray", "(", "final", "int", "[", "]", "dst", ")", "{", "if", "(", "dst", ".", "length", "==", "size", ")", "{", "System", ".", "arraycopy", "(", "elements", ",", "0", ",", "dst", ",", "0", ",", "dst", ".", "length", ")", ";", "return", "dst", ";", "}", "else", "{", "return", "Arrays", ".", "copyOf", "(", "elements", ",", "size", ")", ";", "}", "}" ]
Create a new array that is a copy of the elements. @param dst destination array for the copy if it is the correct size. @return a copy of the elements.
[ "Create", "a", "new", "array", "that", "is", "a", "copy", "of", "the", "elements", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/IntArrayList.java#L444-L455
27,755
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/errors/ErrorLogReader.java
ErrorLogReader.read
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer, final long sinceTimestamp) { int entries = 0; int offset = 0; final int capacity = buffer.capacity(); while (offset < capacity) { final int length = buffer.getIntVolatile(offset + LENGTH_OFFSET); if (0 == length) { break; } final long lastObservationTimestamp = buffer.getLongVolatile(offset + LAST_OBSERVATION_TIMESTAMP_OFFSET); if (lastObservationTimestamp >= sinceTimestamp) { ++entries; consumer.accept( buffer.getInt(offset + OBSERVATION_COUNT_OFFSET), buffer.getLong(offset + FIRST_OBSERVATION_TIMESTAMP_OFFSET), lastObservationTimestamp, buffer.getStringWithoutLengthUtf8(offset + ENCODED_ERROR_OFFSET, length - ENCODED_ERROR_OFFSET)); } offset += align(length, RECORD_ALIGNMENT); } return entries; }
java
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer, final long sinceTimestamp) { int entries = 0; int offset = 0; final int capacity = buffer.capacity(); while (offset < capacity) { final int length = buffer.getIntVolatile(offset + LENGTH_OFFSET); if (0 == length) { break; } final long lastObservationTimestamp = buffer.getLongVolatile(offset + LAST_OBSERVATION_TIMESTAMP_OFFSET); if (lastObservationTimestamp >= sinceTimestamp) { ++entries; consumer.accept( buffer.getInt(offset + OBSERVATION_COUNT_OFFSET), buffer.getLong(offset + FIRST_OBSERVATION_TIMESTAMP_OFFSET), lastObservationTimestamp, buffer.getStringWithoutLengthUtf8(offset + ENCODED_ERROR_OFFSET, length - ENCODED_ERROR_OFFSET)); } offset += align(length, RECORD_ALIGNMENT); } return entries; }
[ "public", "static", "int", "read", "(", "final", "AtomicBuffer", "buffer", ",", "final", "ErrorConsumer", "consumer", ",", "final", "long", "sinceTimestamp", ")", "{", "int", "entries", "=", "0", ";", "int", "offset", "=", "0", ";", "final", "int", "capacity", "=", "buffer", ".", "capacity", "(", ")", ";", "while", "(", "offset", "<", "capacity", ")", "{", "final", "int", "length", "=", "buffer", ".", "getIntVolatile", "(", "offset", "+", "LENGTH_OFFSET", ")", ";", "if", "(", "0", "==", "length", ")", "{", "break", ";", "}", "final", "long", "lastObservationTimestamp", "=", "buffer", ".", "getLongVolatile", "(", "offset", "+", "LAST_OBSERVATION_TIMESTAMP_OFFSET", ")", ";", "if", "(", "lastObservationTimestamp", ">=", "sinceTimestamp", ")", "{", "++", "entries", ";", "consumer", ".", "accept", "(", "buffer", ".", "getInt", "(", "offset", "+", "OBSERVATION_COUNT_OFFSET", ")", ",", "buffer", ".", "getLong", "(", "offset", "+", "FIRST_OBSERVATION_TIMESTAMP_OFFSET", ")", ",", "lastObservationTimestamp", ",", "buffer", ".", "getStringWithoutLengthUtf8", "(", "offset", "+", "ENCODED_ERROR_OFFSET", ",", "length", "-", "ENCODED_ERROR_OFFSET", ")", ")", ";", "}", "offset", "+=", "align", "(", "length", ",", "RECORD_ALIGNMENT", ")", ";", "}", "return", "entries", ";", "}" ]
Read all the errors in a log since a given timestamp. @param buffer containing the {@link DistinctErrorLog}. @param consumer to be called for each exception encountered. @param sinceTimestamp for filtering errors that have been recorded since this time. @return the number of entries that has been read.
[ "Read", "all", "the", "errors", "in", "a", "log", "since", "a", "given", "timestamp", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/errors/ErrorLogReader.java#L61-L91
27,756
real-logic/agrona
agrona/src/main/java/org/agrona/collections/ArrayListUtil.java
ArrayListUtil.fastUnorderedRemove
public static <T> void fastUnorderedRemove(final ArrayList<T> list, final int index) { final int lastIndex = list.size() - 1; if (index != lastIndex) { list.set(index, list.remove(lastIndex)); } else { list.remove(index); } }
java
public static <T> void fastUnorderedRemove(final ArrayList<T> list, final int index) { final int lastIndex = list.size() - 1; if (index != lastIndex) { list.set(index, list.remove(lastIndex)); } else { list.remove(index); } }
[ "public", "static", "<", "T", ">", "void", "fastUnorderedRemove", "(", "final", "ArrayList", "<", "T", ">", "list", ",", "final", "int", "index", ")", "{", "final", "int", "lastIndex", "=", "list", ".", "size", "(", ")", "-", "1", ";", "if", "(", "index", "!=", "lastIndex", ")", "{", "list", ".", "set", "(", "index", ",", "list", ".", "remove", "(", "lastIndex", ")", ")", ";", "}", "else", "{", "list", ".", "remove", "(", "index", ")", ";", "}", "}" ]
Removes element at index, but instead of copying all elements to the left, moves into the same slot the last element. This avoids the copy costs, but spoils the list order. If index is the last element it is just removed. @param list to be modified. @param index to be removed. @param <T> element type. @throws IndexOutOfBoundsException if index is out of bounds.
[ "Removes", "element", "at", "index", "but", "instead", "of", "copying", "all", "elements", "to", "the", "left", "moves", "into", "the", "same", "slot", "the", "last", "element", ".", "This", "avoids", "the", "copy", "costs", "but", "spoils", "the", "list", "order", ".", "If", "index", "is", "the", "last", "element", "it", "is", "just", "removed", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/ArrayListUtil.java#L34-L45
27,757
real-logic/agrona
agrona/src/main/java/org/agrona/collections/ArrayListUtil.java
ArrayListUtil.fastUnorderedRemove
public static <T> boolean fastUnorderedRemove(final ArrayList<T> list, final T e) { for (int i = 0, size = list.size(); i < size; i++) { if (e == list.get(i)) { fastUnorderedRemove(list, i, size - 1); return true; } } return false; }
java
public static <T> boolean fastUnorderedRemove(final ArrayList<T> list, final T e) { for (int i = 0, size = list.size(); i < size; i++) { if (e == list.get(i)) { fastUnorderedRemove(list, i, size - 1); return true; } } return false; }
[ "public", "static", "<", "T", ">", "boolean", "fastUnorderedRemove", "(", "final", "ArrayList", "<", "T", ">", "list", ",", "final", "T", "e", ")", "{", "for", "(", "int", "i", "=", "0", ",", "size", "=", "list", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "e", "==", "list", ".", "get", "(", "i", ")", ")", "{", "fastUnorderedRemove", "(", "list", ",", "i", ",", "size", "-", "1", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Removes element but instead of copying all elements to the left, moves into the same slot the last element. This avoids the copy costs, but spoils the list order. If element is the last element then it is just removed. @param list to be modified. @param e to be removed. @param <T> element type. @return true if found and removed, false otherwise.
[ "Removes", "element", "but", "instead", "of", "copying", "all", "elements", "to", "the", "left", "moves", "into", "the", "same", "slot", "the", "last", "element", ".", "This", "avoids", "the", "copy", "costs", "but", "spoils", "the", "list", "order", ".", "If", "element", "is", "the", "last", "element", "then", "it", "is", "just", "removed", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/ArrayListUtil.java#L78-L90
27,758
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/HighResolutionTimer.java
HighResolutionTimer.enable
public static synchronized void enable() { if (null != thread) { thread = new Thread(HighResolutionTimer::run); thread.setDaemon(true); thread.setName("high-resolution-timer-hack"); thread.start(); } }
java
public static synchronized void enable() { if (null != thread) { thread = new Thread(HighResolutionTimer::run); thread.setDaemon(true); thread.setName("high-resolution-timer-hack"); thread.start(); } }
[ "public", "static", "synchronized", "void", "enable", "(", ")", "{", "if", "(", "null", "!=", "thread", ")", "{", "thread", "=", "new", "Thread", "(", "HighResolutionTimer", "::", "run", ")", ";", "thread", ".", "setDaemon", "(", "true", ")", ";", "thread", ".", "setName", "(", "\"high-resolution-timer-hack\"", ")", ";", "thread", ".", "start", "(", ")", ";", "}", "}" ]
Attempt to enable high resolution timers.
[ "Attempt", "to", "enable", "high", "resolution", "timers", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/HighResolutionTimer.java#L38-L47
27,759
firebase/geofire-java
common/src/main/java/com/firebase/geofire/GeoQuery.java
GeoQuery.addGeoQueryDataEventListener
public synchronized void addGeoQueryDataEventListener(final GeoQueryDataEventListener listener) { if (eventListeners.contains(listener)) { throw new IllegalArgumentException("Added the same listener twice to a GeoQuery!"); } eventListeners.add(listener); if (this.queries == null) { this.setupQueries(); } else { for (final Map.Entry<String, LocationInfo> entry: this.locationInfos.entrySet()) { final String key = entry.getKey(); final LocationInfo info = entry.getValue(); if (info.inGeoQuery) { this.geoFire.raiseEvent(new Runnable() { @Override public void run() { listener.onDataEntered(info.dataSnapshot, info.location); } }); } } if (this.canFireReady()) { this.geoFire.raiseEvent(new Runnable() { @Override public void run() { listener.onGeoQueryReady(); } }); } } }
java
public synchronized void addGeoQueryDataEventListener(final GeoQueryDataEventListener listener) { if (eventListeners.contains(listener)) { throw new IllegalArgumentException("Added the same listener twice to a GeoQuery!"); } eventListeners.add(listener); if (this.queries == null) { this.setupQueries(); } else { for (final Map.Entry<String, LocationInfo> entry: this.locationInfos.entrySet()) { final String key = entry.getKey(); final LocationInfo info = entry.getValue(); if (info.inGeoQuery) { this.geoFire.raiseEvent(new Runnable() { @Override public void run() { listener.onDataEntered(info.dataSnapshot, info.location); } }); } } if (this.canFireReady()) { this.geoFire.raiseEvent(new Runnable() { @Override public void run() { listener.onGeoQueryReady(); } }); } } }
[ "public", "synchronized", "void", "addGeoQueryDataEventListener", "(", "final", "GeoQueryDataEventListener", "listener", ")", "{", "if", "(", "eventListeners", ".", "contains", "(", "listener", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Added the same listener twice to a GeoQuery!\"", ")", ";", "}", "eventListeners", ".", "add", "(", "listener", ")", ";", "if", "(", "this", ".", "queries", "==", "null", ")", "{", "this", ".", "setupQueries", "(", ")", ";", "}", "else", "{", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "LocationInfo", ">", "entry", ":", "this", ".", "locationInfos", ".", "entrySet", "(", ")", ")", "{", "final", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "final", "LocationInfo", "info", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "info", ".", "inGeoQuery", ")", "{", "this", ".", "geoFire", ".", "raiseEvent", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "listener", ".", "onDataEntered", "(", "info", ".", "dataSnapshot", ",", "info", ".", "location", ")", ";", "}", "}", ")", ";", "}", "}", "if", "(", "this", ".", "canFireReady", "(", ")", ")", "{", "this", ".", "geoFire", ".", "raiseEvent", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "listener", ".", "onGeoQueryReady", "(", ")", ";", "}", "}", ")", ";", "}", "}", "}" ]
Adds a new GeoQueryEventListener to this GeoQuery. @throws IllegalArgumentException If this listener was already added @param listener The listener to add
[ "Adds", "a", "new", "GeoQueryEventListener", "to", "this", "GeoQuery", "." ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoQuery.java#L351-L381
27,760
firebase/geofire-java
common/src/main/java/com/firebase/geofire/GeoQuery.java
GeoQuery.removeGeoQueryEventListener
public synchronized void removeGeoQueryEventListener(final GeoQueryDataEventListener listener) { if (!eventListeners.contains(listener)) { throw new IllegalArgumentException("Trying to remove listener that was removed or not added!"); } eventListeners.remove(listener); if (!this.hasListeners()) { reset(); } }
java
public synchronized void removeGeoQueryEventListener(final GeoQueryDataEventListener listener) { if (!eventListeners.contains(listener)) { throw new IllegalArgumentException("Trying to remove listener that was removed or not added!"); } eventListeners.remove(listener); if (!this.hasListeners()) { reset(); } }
[ "public", "synchronized", "void", "removeGeoQueryEventListener", "(", "final", "GeoQueryDataEventListener", "listener", ")", "{", "if", "(", "!", "eventListeners", ".", "contains", "(", "listener", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Trying to remove listener that was removed or not added!\"", ")", ";", "}", "eventListeners", ".", "remove", "(", "listener", ")", ";", "if", "(", "!", "this", ".", "hasListeners", "(", ")", ")", "{", "reset", "(", ")", ";", "}", "}" ]
Removes an event listener. @throws IllegalArgumentException If the listener was removed already or never added @param listener The listener to remove
[ "Removes", "an", "event", "listener", "." ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoQuery.java#L401-L409
27,761
firebase/geofire-java
common/src/main/java/com/firebase/geofire/GeoFire.java
GeoFire.setLocation
public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); GeoHash geoHash = new GeoHash(location); Map<String, Object> updates = new HashMap<>(); updates.put("g", geoHash.getGeoHashString()); updates.put("l", Arrays.asList(location.latitude, location.longitude)); if (completionListener != null) { keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { keyRef.setValue(updates, geoHash.getGeoHashString()); } }
java
public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); GeoHash geoHash = new GeoHash(location); Map<String, Object> updates = new HashMap<>(); updates.put("g", geoHash.getGeoHashString()); updates.put("l", Arrays.asList(location.latitude, location.longitude)); if (completionListener != null) { keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { keyRef.setValue(updates, geoHash.getGeoHashString()); } }
[ "public", "void", "setLocation", "(", "final", "String", "key", ",", "final", "GeoLocation", "location", ",", "final", "CompletionListener", "completionListener", ")", "{", "if", "(", "key", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "DatabaseReference", "keyRef", "=", "this", ".", "getDatabaseRefForKey", "(", "key", ")", ";", "GeoHash", "geoHash", "=", "new", "GeoHash", "(", "location", ")", ";", "Map", "<", "String", ",", "Object", ">", "updates", "=", "new", "HashMap", "<>", "(", ")", ";", "updates", ".", "put", "(", "\"g\"", ",", "geoHash", ".", "getGeoHashString", "(", ")", ")", ";", "updates", ".", "put", "(", "\"l\"", ",", "Arrays", ".", "asList", "(", "location", ".", "latitude", ",", "location", ".", "longitude", ")", ")", ";", "if", "(", "completionListener", "!=", "null", ")", "{", "keyRef", ".", "setValue", "(", "updates", ",", "geoHash", ".", "getGeoHashString", "(", ")", ",", "new", "DatabaseReference", ".", "CompletionListener", "(", ")", "{", "@", "Override", "public", "void", "onComplete", "(", "DatabaseError", "databaseError", ",", "DatabaseReference", "databaseReference", ")", "{", "completionListener", ".", "onComplete", "(", "key", ",", "databaseError", ")", ";", "}", "}", ")", ";", "}", "else", "{", "keyRef", ".", "setValue", "(", "updates", ",", "geoHash", ".", "getGeoHashString", "(", ")", ")", ";", "}", "}" ]
Sets the location for a given key. @param key The key to save the location for @param location The location of this key @param completionListener A listener that is called once the location was successfully saved on the server or an error occurred
[ "Sets", "the", "location", "for", "a", "given", "key", "." ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoFire.java#L165-L184
27,762
firebase/geofire-java
common/src/main/java/com/firebase/geofire/GeoFire.java
GeoFire.removeLocation
public void removeLocation(final String key, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); if (completionListener != null) { keyRef.setValue(null, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { keyRef.setValue(null); } }
java
public void removeLocation(final String key, final CompletionListener completionListener) { if (key == null) { throw new NullPointerException(); } DatabaseReference keyRef = this.getDatabaseRefForKey(key); if (completionListener != null) { keyRef.setValue(null, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { completionListener.onComplete(key, databaseError); } }); } else { keyRef.setValue(null); } }
[ "public", "void", "removeLocation", "(", "final", "String", "key", ",", "final", "CompletionListener", "completionListener", ")", "{", "if", "(", "key", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "DatabaseReference", "keyRef", "=", "this", ".", "getDatabaseRefForKey", "(", "key", ")", ";", "if", "(", "completionListener", "!=", "null", ")", "{", "keyRef", ".", "setValue", "(", "null", ",", "new", "DatabaseReference", ".", "CompletionListener", "(", ")", "{", "@", "Override", "public", "void", "onComplete", "(", "DatabaseError", "databaseError", ",", "DatabaseReference", "databaseReference", ")", "{", "completionListener", ".", "onComplete", "(", "key", ",", "databaseError", ")", ";", "}", "}", ")", ";", "}", "else", "{", "keyRef", ".", "setValue", "(", "null", ")", ";", "}", "}" ]
Removes the location for a key from this GeoFire. @param key The key to remove from this GeoFire @param completionListener A completion listener that is called once the location is successfully removed from the server or an error occurred
[ "Removes", "the", "location", "for", "a", "key", "from", "this", "GeoFire", "." ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoFire.java#L202-L217
27,763
firebase/geofire-java
common/src/main/java/com/firebase/geofire/GeoFire.java
GeoFire.getLocation
public void getLocation(String key, LocationCallback callback) { DatabaseReference keyRef = this.getDatabaseRefForKey(key); LocationValueEventListener valueListener = new LocationValueEventListener(callback); keyRef.addListenerForSingleValueEvent(valueListener); }
java
public void getLocation(String key, LocationCallback callback) { DatabaseReference keyRef = this.getDatabaseRefForKey(key); LocationValueEventListener valueListener = new LocationValueEventListener(callback); keyRef.addListenerForSingleValueEvent(valueListener); }
[ "public", "void", "getLocation", "(", "String", "key", ",", "LocationCallback", "callback", ")", "{", "DatabaseReference", "keyRef", "=", "this", ".", "getDatabaseRefForKey", "(", "key", ")", ";", "LocationValueEventListener", "valueListener", "=", "new", "LocationValueEventListener", "(", "callback", ")", ";", "keyRef", ".", "addListenerForSingleValueEvent", "(", "valueListener", ")", ";", "}" ]
Gets the current location for a key and calls the callback with the current value. @param key The key whose location to get @param callback The callback that is called once the location is retrieved
[ "Gets", "the", "current", "location", "for", "a", "key", "and", "calls", "the", "callback", "with", "the", "current", "value", "." ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoFire.java#L225-L229
27,764
firebase/geofire-java
examples/SFVehicles/SF Vehicles/src/main/java/com/firebase/sfvehicles/SFVehiclesActivity.java
SFVehiclesActivity.animateMarkerTo
private void animateMarkerTo(final Marker marker, final double lat, final double lng) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); final long DURATION_MS = 3000; final Interpolator interpolator = new AccelerateDecelerateInterpolator(); final LatLng startPosition = marker.getPosition(); handler.post(new Runnable() { @Override public void run() { float elapsed = SystemClock.uptimeMillis() - start; float t = elapsed/DURATION_MS; float v = interpolator.getInterpolation(t); double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude; double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude; marker.setPosition(new LatLng(currentLat, currentLng)); // if animation is not finished yet, repeat if (t < 1) { handler.postDelayed(this, 16); } } }); }
java
private void animateMarkerTo(final Marker marker, final double lat, final double lng) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); final long DURATION_MS = 3000; final Interpolator interpolator = new AccelerateDecelerateInterpolator(); final LatLng startPosition = marker.getPosition(); handler.post(new Runnable() { @Override public void run() { float elapsed = SystemClock.uptimeMillis() - start; float t = elapsed/DURATION_MS; float v = interpolator.getInterpolation(t); double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude; double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude; marker.setPosition(new LatLng(currentLat, currentLng)); // if animation is not finished yet, repeat if (t < 1) { handler.postDelayed(this, 16); } } }); }
[ "private", "void", "animateMarkerTo", "(", "final", "Marker", "marker", ",", "final", "double", "lat", ",", "final", "double", "lng", ")", "{", "final", "Handler", "handler", "=", "new", "Handler", "(", ")", ";", "final", "long", "start", "=", "SystemClock", ".", "uptimeMillis", "(", ")", ";", "final", "long", "DURATION_MS", "=", "3000", ";", "final", "Interpolator", "interpolator", "=", "new", "AccelerateDecelerateInterpolator", "(", ")", ";", "final", "LatLng", "startPosition", "=", "marker", ".", "getPosition", "(", ")", ";", "handler", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "float", "elapsed", "=", "SystemClock", ".", "uptimeMillis", "(", ")", "-", "start", ";", "float", "t", "=", "elapsed", "/", "DURATION_MS", ";", "float", "v", "=", "interpolator", ".", "getInterpolation", "(", "t", ")", ";", "double", "currentLat", "=", "(", "lat", "-", "startPosition", ".", "latitude", ")", "*", "v", "+", "startPosition", ".", "latitude", ";", "double", "currentLng", "=", "(", "lng", "-", "startPosition", ".", "longitude", ")", "*", "v", "+", "startPosition", ".", "longitude", ";", "marker", ".", "setPosition", "(", "new", "LatLng", "(", "currentLat", ",", "currentLng", ")", ")", ";", "// if animation is not finished yet, repeat", "if", "(", "t", "<", "1", ")", "{", "handler", ".", "postDelayed", "(", "this", ",", "16", ")", ";", "}", "}", "}", ")", ";", "}" ]
Animation handler for old APIs without animation support
[ "Animation", "handler", "for", "old", "APIs", "without", "animation", "support" ]
c46ff339060d150741a8d0d40c8e73b78edca6c3
https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/examples/SFVehicles/SF Vehicles/src/main/java/com/firebase/sfvehicles/SFVehiclesActivity.java#L127-L150
27,765
square/dagger
core/src/main/java/dagger/internal/Modules.java
Modules.loadModules
public static Map<ModuleAdapter<?>, Object> loadModules(Loader loader, Object[] seedModulesOrClasses) { Map<ModuleAdapter<?>, Object> seedAdapters = new LinkedHashMap<ModuleAdapter<?>, Object>(seedModulesOrClasses.length); for (int i = 0; i < seedModulesOrClasses.length; i++) { if (seedModulesOrClasses[i] instanceof Class<?>) { ModuleAdapter<?> adapter = loader.getModuleAdapter((Class<?>) seedModulesOrClasses[i]); seedAdapters.put(adapter, adapter.newModule()); } else { ModuleAdapter<?> adapter = loader.getModuleAdapter(seedModulesOrClasses[i].getClass()); seedAdapters.put(adapter, seedModulesOrClasses[i]); } } // Add the adapters that we have module instances for. This way we won't // construct module objects when we have a user-supplied instance. Map<ModuleAdapter<?>, Object> result = new LinkedHashMap<ModuleAdapter<?>, Object>(seedAdapters); // Next collect included modules Map<Class<?>, ModuleAdapter<?>> transitiveInclusions = new LinkedHashMap<Class<?>, ModuleAdapter<?>>(); for (ModuleAdapter<?> adapter : seedAdapters.keySet()) { collectIncludedModulesRecursively(loader, adapter, transitiveInclusions); } // and create them if necessary for (ModuleAdapter<?> dependency : transitiveInclusions.values()) { if (!result.containsKey(dependency)) { result.put(dependency, dependency.newModule()); } } return result; }
java
public static Map<ModuleAdapter<?>, Object> loadModules(Loader loader, Object[] seedModulesOrClasses) { Map<ModuleAdapter<?>, Object> seedAdapters = new LinkedHashMap<ModuleAdapter<?>, Object>(seedModulesOrClasses.length); for (int i = 0; i < seedModulesOrClasses.length; i++) { if (seedModulesOrClasses[i] instanceof Class<?>) { ModuleAdapter<?> adapter = loader.getModuleAdapter((Class<?>) seedModulesOrClasses[i]); seedAdapters.put(adapter, adapter.newModule()); } else { ModuleAdapter<?> adapter = loader.getModuleAdapter(seedModulesOrClasses[i].getClass()); seedAdapters.put(adapter, seedModulesOrClasses[i]); } } // Add the adapters that we have module instances for. This way we won't // construct module objects when we have a user-supplied instance. Map<ModuleAdapter<?>, Object> result = new LinkedHashMap<ModuleAdapter<?>, Object>(seedAdapters); // Next collect included modules Map<Class<?>, ModuleAdapter<?>> transitiveInclusions = new LinkedHashMap<Class<?>, ModuleAdapter<?>>(); for (ModuleAdapter<?> adapter : seedAdapters.keySet()) { collectIncludedModulesRecursively(loader, adapter, transitiveInclusions); } // and create them if necessary for (ModuleAdapter<?> dependency : transitiveInclusions.values()) { if (!result.containsKey(dependency)) { result.put(dependency, dependency.newModule()); } } return result; }
[ "public", "static", "Map", "<", "ModuleAdapter", "<", "?", ">", ",", "Object", ">", "loadModules", "(", "Loader", "loader", ",", "Object", "[", "]", "seedModulesOrClasses", ")", "{", "Map", "<", "ModuleAdapter", "<", "?", ">", ",", "Object", ">", "seedAdapters", "=", "new", "LinkedHashMap", "<", "ModuleAdapter", "<", "?", ">", ",", "Object", ">", "(", "seedModulesOrClasses", ".", "length", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "seedModulesOrClasses", ".", "length", ";", "i", "++", ")", "{", "if", "(", "seedModulesOrClasses", "[", "i", "]", "instanceof", "Class", "<", "?", ">", ")", "{", "ModuleAdapter", "<", "?", ">", "adapter", "=", "loader", ".", "getModuleAdapter", "(", "(", "Class", "<", "?", ">", ")", "seedModulesOrClasses", "[", "i", "]", ")", ";", "seedAdapters", ".", "put", "(", "adapter", ",", "adapter", ".", "newModule", "(", ")", ")", ";", "}", "else", "{", "ModuleAdapter", "<", "?", ">", "adapter", "=", "loader", ".", "getModuleAdapter", "(", "seedModulesOrClasses", "[", "i", "]", ".", "getClass", "(", ")", ")", ";", "seedAdapters", ".", "put", "(", "adapter", ",", "seedModulesOrClasses", "[", "i", "]", ")", ";", "}", "}", "// Add the adapters that we have module instances for. This way we won't", "// construct module objects when we have a user-supplied instance.", "Map", "<", "ModuleAdapter", "<", "?", ">", ",", "Object", ">", "result", "=", "new", "LinkedHashMap", "<", "ModuleAdapter", "<", "?", ">", ",", "Object", ">", "(", "seedAdapters", ")", ";", "// Next collect included modules", "Map", "<", "Class", "<", "?", ">", ",", "ModuleAdapter", "<", "?", ">", ">", "transitiveInclusions", "=", "new", "LinkedHashMap", "<", "Class", "<", "?", ">", ",", "ModuleAdapter", "<", "?", ">", ">", "(", ")", ";", "for", "(", "ModuleAdapter", "<", "?", ">", "adapter", ":", "seedAdapters", ".", "keySet", "(", ")", ")", "{", "collectIncludedModulesRecursively", "(", "loader", ",", "adapter", ",", "transitiveInclusions", ")", ";", "}", "// and create them if necessary", "for", "(", "ModuleAdapter", "<", "?", ">", "dependency", ":", "transitiveInclusions", ".", "values", "(", ")", ")", "{", "if", "(", "!", "result", ".", "containsKey", "(", "dependency", ")", ")", "{", "result", ".", "put", "(", "dependency", ",", "dependency", ".", "newModule", "(", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns a full set of module adapters, including module adapters for included modules.
[ "Returns", "a", "full", "set", "of", "module", "adapters", "including", "module", "adapters", "for", "included", "modules", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/Modules.java#L34-L66
27,766
square/dagger
core/src/main/java/dagger/internal/Linker.java
Linker.linkRequested
public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferred = (DeferredBinding) binding; String key = deferred.deferredKey; boolean mustHaveInjections = deferred.mustHaveInjections; if (bindings.containsKey(key)) { continue; // A binding for this key has since been linked. } try { Binding<?> resolvedBinding = createBinding(key, binding.requiredBy, deferred.classLoader, mustHaveInjections); resolvedBinding.setLibrary(binding.library()); resolvedBinding.setDependedOn(binding.dependedOn()); // Fail if the type of binding we got wasn't capable of what was requested. if (!key.equals(resolvedBinding.provideKey) && !key.equals(resolvedBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } // Enqueue the JIT binding so its own dependencies can be linked. Binding<?> scopedBinding = scope(resolvedBinding); toLink.add(scopedBinding); putBinding(scopedBinding); } catch (InvalidBindingException e) { addError(e.type + " " + e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (UnsupportedOperationException e) { addError("Unsupported: " + e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (IllegalArgumentException e) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } else { // Attempt to attach the binding to its dependencies. If any dependency // is not available, the attach will fail. We'll enqueue creation of // that dependency and retry the attachment later. attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }
java
public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferred = (DeferredBinding) binding; String key = deferred.deferredKey; boolean mustHaveInjections = deferred.mustHaveInjections; if (bindings.containsKey(key)) { continue; // A binding for this key has since been linked. } try { Binding<?> resolvedBinding = createBinding(key, binding.requiredBy, deferred.classLoader, mustHaveInjections); resolvedBinding.setLibrary(binding.library()); resolvedBinding.setDependedOn(binding.dependedOn()); // Fail if the type of binding we got wasn't capable of what was requested. if (!key.equals(resolvedBinding.provideKey) && !key.equals(resolvedBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } // Enqueue the JIT binding so its own dependencies can be linked. Binding<?> scopedBinding = scope(resolvedBinding); toLink.add(scopedBinding); putBinding(scopedBinding); } catch (InvalidBindingException e) { addError(e.type + " " + e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (UnsupportedOperationException e) { addError("Unsupported: " + e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (IllegalArgumentException e) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } else { // Attempt to attach the binding to its dependencies. If any dependency // is not available, the attach will fail. We'll enqueue creation of // that dependency and retry the attachment later. attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }
[ "public", "void", "linkRequested", "(", ")", "{", "assertLockHeld", "(", ")", ";", "Binding", "<", "?", ">", "binding", ";", "while", "(", "(", "binding", "=", "toLink", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "binding", "instanceof", "DeferredBinding", ")", "{", "DeferredBinding", "deferred", "=", "(", "DeferredBinding", ")", "binding", ";", "String", "key", "=", "deferred", ".", "deferredKey", ";", "boolean", "mustHaveInjections", "=", "deferred", ".", "mustHaveInjections", ";", "if", "(", "bindings", ".", "containsKey", "(", "key", ")", ")", "{", "continue", ";", "// A binding for this key has since been linked.", "}", "try", "{", "Binding", "<", "?", ">", "resolvedBinding", "=", "createBinding", "(", "key", ",", "binding", ".", "requiredBy", ",", "deferred", ".", "classLoader", ",", "mustHaveInjections", ")", ";", "resolvedBinding", ".", "setLibrary", "(", "binding", ".", "library", "(", ")", ")", ";", "resolvedBinding", ".", "setDependedOn", "(", "binding", ".", "dependedOn", "(", ")", ")", ";", "// Fail if the type of binding we got wasn't capable of what was requested.", "if", "(", "!", "key", ".", "equals", "(", "resolvedBinding", ".", "provideKey", ")", "&&", "!", "key", ".", "equals", "(", "resolvedBinding", ".", "membersKey", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unable to create binding for \"", "+", "key", ")", ";", "}", "// Enqueue the JIT binding so its own dependencies can be linked.", "Binding", "<", "?", ">", "scopedBinding", "=", "scope", "(", "resolvedBinding", ")", ";", "toLink", ".", "add", "(", "scopedBinding", ")", ";", "putBinding", "(", "scopedBinding", ")", ";", "}", "catch", "(", "InvalidBindingException", "e", ")", "{", "addError", "(", "e", ".", "type", "+", "\" \"", "+", "e", ".", "getMessage", "(", ")", "+", "\" required by \"", "+", "binding", ".", "requiredBy", ")", ";", "bindings", ".", "put", "(", "key", ",", "Binding", ".", "UNRESOLVED", ")", ";", "}", "catch", "(", "UnsupportedOperationException", "e", ")", "{", "addError", "(", "\"Unsupported: \"", "+", "e", ".", "getMessage", "(", ")", "+", "\" required by \"", "+", "binding", ".", "requiredBy", ")", ";", "bindings", ".", "put", "(", "key", ",", "Binding", ".", "UNRESOLVED", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "addError", "(", "e", ".", "getMessage", "(", ")", "+", "\" required by \"", "+", "binding", ".", "requiredBy", ")", ";", "bindings", ".", "put", "(", "key", ",", "Binding", ".", "UNRESOLVED", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "else", "{", "// Attempt to attach the binding to its dependencies. If any dependency", "// is not available, the attach will fail. We'll enqueue creation of", "// that dependency and retry the attachment later.", "attachSuccess", "=", "true", ";", "binding", ".", "attach", "(", "this", ")", ";", "if", "(", "attachSuccess", ")", "{", "binding", ".", "setLinked", "(", ")", ";", "}", "else", "{", "toLink", ".", "add", "(", "binding", ")", ";", "}", "}", "}", "try", "{", "errorHandler", ".", "handleErrors", "(", "errors", ")", ";", "}", "finally", "{", "errors", ".", "clear", "(", ")", ";", "}", "}" ]
Links all requested bindings plus their transitive dependencies. This creates JIT bindings as necessary to fill in the gaps. @throws AssertionError if this method is not called within a synchronized block which holds this {@link Linker} as the lock object.
[ "Links", "all", "requested", "bindings", "plus", "their", "transitive", "dependencies", ".", "This", "creates", "JIT", "bindings", "as", "necessary", "to", "fill", "in", "the", "gaps", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/Linker.java#L129-L186
27,767
square/dagger
compiler/src/main/java/dagger/internal/codegen/AdapterJavadocs.java
AdapterJavadocs.bindingTypeDocs
static CodeBlock bindingTypeDocs( TypeName type, boolean abstrakt, boolean members, boolean dependent) { CodeBlock.Builder result = CodeBlock.builder() .add("A {@code Binding<$T>} implementation which satisfies\n", type) .add("Dagger's infrastructure requirements including:\n"); if (dependent) { result.add("\n") .add("Owning the dependency links between {@code $T} and its\n", type) .add("dependencies.\n"); } if (!abstrakt) { result.add("\n") .add("Being a {@code Provider<$T>} and handling creation and\n", type) .add("preparation of object instances.\n"); } if (members) { result.add("\n") .add("Being a {@code MembersInjector<$T>} and handling injection\n", type) .add("of annotated fields.\n"); } return result.build(); }
java
static CodeBlock bindingTypeDocs( TypeName type, boolean abstrakt, boolean members, boolean dependent) { CodeBlock.Builder result = CodeBlock.builder() .add("A {@code Binding<$T>} implementation which satisfies\n", type) .add("Dagger's infrastructure requirements including:\n"); if (dependent) { result.add("\n") .add("Owning the dependency links between {@code $T} and its\n", type) .add("dependencies.\n"); } if (!abstrakt) { result.add("\n") .add("Being a {@code Provider<$T>} and handling creation and\n", type) .add("preparation of object instances.\n"); } if (members) { result.add("\n") .add("Being a {@code MembersInjector<$T>} and handling injection\n", type) .add("of annotated fields.\n"); } return result.build(); }
[ "static", "CodeBlock", "bindingTypeDocs", "(", "TypeName", "type", ",", "boolean", "abstrakt", ",", "boolean", "members", ",", "boolean", "dependent", ")", "{", "CodeBlock", ".", "Builder", "result", "=", "CodeBlock", ".", "builder", "(", ")", ".", "add", "(", "\"A {@code Binding<$T>} implementation which satisfies\\n\"", ",", "type", ")", ".", "add", "(", "\"Dagger's infrastructure requirements including:\\n\"", ")", ";", "if", "(", "dependent", ")", "{", "result", ".", "add", "(", "\"\\n\"", ")", ".", "add", "(", "\"Owning the dependency links between {@code $T} and its\\n\"", ",", "type", ")", ".", "add", "(", "\"dependencies.\\n\"", ")", ";", "}", "if", "(", "!", "abstrakt", ")", "{", "result", ".", "add", "(", "\"\\n\"", ")", ".", "add", "(", "\"Being a {@code Provider<$T>} and handling creation and\\n\"", ",", "type", ")", ".", "add", "(", "\"preparation of object instances.\\n\"", ")", ";", "}", "if", "(", "members", ")", "{", "result", ".", "add", "(", "\"\\n\"", ")", ".", "add", "(", "\"Being a {@code MembersInjector<$T>} and handling injection\\n\"", ",", "type", ")", ".", "add", "(", "\"of annotated fields.\\n\"", ")", ";", "}", "return", "result", ".", "build", "(", ")", ";", "}" ]
Creates an appropriate javadoc depending on aspects of the type in question.
[ "Creates", "an", "appropriate", "javadoc", "depending", "on", "aspects", "of", "the", "type", "in", "question", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/compiler/src/main/java/dagger/internal/codegen/AdapterJavadocs.java#L49-L70
27,768
square/dagger
core/src/main/java/dagger/internal/ArrayQueue.java
ArrayQueue.add
@Override public boolean add(E e) { if (e == null) throw new NullPointerException("e == null"); elements[tail] = e; if ((tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); return true; }
java
@Override public boolean add(E e) { if (e == null) throw new NullPointerException("e == null"); elements[tail] = e; if ((tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); return true; }
[ "@", "Override", "public", "boolean", "add", "(", "E", "e", ")", "{", "if", "(", "e", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"e == null\"", ")", ";", "elements", "[", "tail", "]", "=", "e", ";", "if", "(", "(", "tail", "=", "(", "tail", "+", "1", ")", "&", "(", "elements", ".", "length", "-", "1", ")", ")", "==", "head", ")", "doubleCapacity", "(", ")", ";", "return", "true", ";", "}" ]
Inserts the specified element at the end of this queue. <p>This method is equivalent to {@link #offer}. @param e the element to add @return <tt>true</tt> (as specified by {@link Collection#add}) @throws NullPointerException if the specified element is null
[ "Inserts", "the", "specified", "element", "at", "the", "end", "of", "this", "queue", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/ArrayQueue.java#L179-L187
27,769
square/dagger
core/src/main/java/dagger/internal/ArrayQueue.java
ArrayQueue.remove
@Override public E remove() { E x = poll(); if (x == null) throw new NoSuchElementException(); return x; }
java
@Override public E remove() { E x = poll(); if (x == null) throw new NoSuchElementException(); return x; }
[ "@", "Override", "public", "E", "remove", "(", ")", "{", "E", "x", "=", "poll", "(", ")", ";", "if", "(", "x", "==", "null", ")", "throw", "new", "NoSuchElementException", "(", ")", ";", "return", "x", ";", "}" ]
Retrieves and removes the head of the queue represented by this queue. This method differs from {@link #poll poll} only in that it throws an exception if this queue is empty. @return the head of the queue represented by this queue @throws NoSuchElementException {@inheritDoc}
[ "Retrieves", "and", "removes", "the", "head", "of", "the", "queue", "represented", "by", "this", "queue", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/ArrayQueue.java#L210-L216
27,770
square/dagger
core/src/main/java/dagger/internal/ArrayQueue.java
ArrayQueue.delete
private boolean delete(int i) { //checkInvariants(); final Object[] elements = this.elements; final int mask = elements.length - 1; final int h = head; final int t = tail; final int front = (i - h) & mask; final int back = (t - i) & mask; // Invariant: head <= i < tail mod circularity if (front >= ((t - h) & mask)) throw new ConcurrentModificationException(); // Optimize for least element motion if (front < back) { if (h <= i) { System.arraycopy(elements, h, elements, h + 1, front); } else { // Wrap around System.arraycopy(elements, 0, elements, 1, i); elements[0] = elements[mask]; System.arraycopy(elements, h, elements, h + 1, mask - h); } elements[h] = null; head = (h + 1) & mask; return false; } else { if (i < t) { // Copy the null tail as well System.arraycopy(elements, i + 1, elements, i, back); tail = t - 1; } else { // Wrap around System.arraycopy(elements, i + 1, elements, i, mask - i); elements[mask] = elements[0]; System.arraycopy(elements, 1, elements, 0, t); tail = (t - 1) & mask; } return true; } }
java
private boolean delete(int i) { //checkInvariants(); final Object[] elements = this.elements; final int mask = elements.length - 1; final int h = head; final int t = tail; final int front = (i - h) & mask; final int back = (t - i) & mask; // Invariant: head <= i < tail mod circularity if (front >= ((t - h) & mask)) throw new ConcurrentModificationException(); // Optimize for least element motion if (front < back) { if (h <= i) { System.arraycopy(elements, h, elements, h + 1, front); } else { // Wrap around System.arraycopy(elements, 0, elements, 1, i); elements[0] = elements[mask]; System.arraycopy(elements, h, elements, h + 1, mask - h); } elements[h] = null; head = (h + 1) & mask; return false; } else { if (i < t) { // Copy the null tail as well System.arraycopy(elements, i + 1, elements, i, back); tail = t - 1; } else { // Wrap around System.arraycopy(elements, i + 1, elements, i, mask - i); elements[mask] = elements[0]; System.arraycopy(elements, 1, elements, 0, t); tail = (t - 1) & mask; } return true; } }
[ "private", "boolean", "delete", "(", "int", "i", ")", "{", "//checkInvariants();", "final", "Object", "[", "]", "elements", "=", "this", ".", "elements", ";", "final", "int", "mask", "=", "elements", ".", "length", "-", "1", ";", "final", "int", "h", "=", "head", ";", "final", "int", "t", "=", "tail", ";", "final", "int", "front", "=", "(", "i", "-", "h", ")", "&", "mask", ";", "final", "int", "back", "=", "(", "t", "-", "i", ")", "&", "mask", ";", "// Invariant: head <= i < tail mod circularity", "if", "(", "front", ">=", "(", "(", "t", "-", "h", ")", "&", "mask", ")", ")", "throw", "new", "ConcurrentModificationException", "(", ")", ";", "// Optimize for least element motion", "if", "(", "front", "<", "back", ")", "{", "if", "(", "h", "<=", "i", ")", "{", "System", ".", "arraycopy", "(", "elements", ",", "h", ",", "elements", ",", "h", "+", "1", ",", "front", ")", ";", "}", "else", "{", "// Wrap around", "System", ".", "arraycopy", "(", "elements", ",", "0", ",", "elements", ",", "1", ",", "i", ")", ";", "elements", "[", "0", "]", "=", "elements", "[", "mask", "]", ";", "System", ".", "arraycopy", "(", "elements", ",", "h", ",", "elements", ",", "h", "+", "1", ",", "mask", "-", "h", ")", ";", "}", "elements", "[", "h", "]", "=", "null", ";", "head", "=", "(", "h", "+", "1", ")", "&", "mask", ";", "return", "false", ";", "}", "else", "{", "if", "(", "i", "<", "t", ")", "{", "// Copy the null tail as well", "System", ".", "arraycopy", "(", "elements", ",", "i", "+", "1", ",", "elements", ",", "i", ",", "back", ")", ";", "tail", "=", "t", "-", "1", ";", "}", "else", "{", "// Wrap around", "System", ".", "arraycopy", "(", "elements", ",", "i", "+", "1", ",", "elements", ",", "i", ",", "mask", "-", "i", ")", ";", "elements", "[", "mask", "]", "=", "elements", "[", "0", "]", ";", "System", ".", "arraycopy", "(", "elements", ",", "1", ",", "elements", ",", "0", ",", "t", ")", ";", "tail", "=", "(", "t", "-", "1", ")", "&", "mask", ";", "}", "return", "true", ";", "}", "}" ]
Removes the element at the specified position in the elements array, adjusting head and tail as necessary. This can result in motion of elements backwards or forwards in the array. <p>This method is called delete rather than remove to emphasize that its semantics differ from those of {@link List#remove(int)}. @return true if elements moved backwards
[ "Removes", "the", "element", "at", "the", "specified", "position", "in", "the", "elements", "array", "adjusting", "head", "and", "tail", "as", "necessary", ".", "This", "can", "result", "in", "motion", "of", "elements", "backwards", "or", "forwards", "in", "the", "array", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/ArrayQueue.java#L278-L315
27,771
square/dagger
core/src/main/java/dagger/internal/ArrayQueue.java
ArrayQueue.writeObject
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); // Write out size s.writeInt(size()); // Write out elements in order. int mask = elements.length - 1; for (int i = head; i != tail; i = (i + 1) & mask) s.writeObject(elements[i]); }
java
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); // Write out size s.writeInt(size()); // Write out elements in order. int mask = elements.length - 1; for (int i = head; i != tail; i = (i + 1) & mask) s.writeObject(elements[i]); }
[ "private", "void", "writeObject", "(", "java", ".", "io", ".", "ObjectOutputStream", "s", ")", "throws", "java", ".", "io", ".", "IOException", "{", "s", ".", "defaultWriteObject", "(", ")", ";", "// Write out size", "s", ".", "writeInt", "(", "size", "(", ")", ")", ";", "// Write out elements in order.", "int", "mask", "=", "elements", ".", "length", "-", "1", ";", "for", "(", "int", "i", "=", "head", ";", "i", "!=", "tail", ";", "i", "=", "(", "i", "+", "1", ")", "&", "mask", ")", "s", ".", "writeObject", "(", "elements", "[", "i", "]", ")", ";", "}" ]
Serialize this queue. @serialData The current size (<tt>int</tt>) of the queue, followed by all of its elements (each an object reference) in first-to-last order.
[ "Serialize", "this", "queue", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/ArrayQueue.java#L577-L588
27,772
square/dagger
core/src/main/java/dagger/internal/ArrayQueue.java
ArrayQueue.readObject
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in size and allocate array int size = s.readInt(); allocateElements(size); head = 0; tail = size; // Read in all elements in the proper order. for (int i = 0; i < size; i++) elements[i] = s.readObject(); }
java
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in size and allocate array int size = s.readInt(); allocateElements(size); head = 0; tail = size; // Read in all elements in the proper order. for (int i = 0; i < size; i++) elements[i] = s.readObject(); }
[ "private", "void", "readObject", "(", "java", ".", "io", ".", "ObjectInputStream", "s", ")", "throws", "java", ".", "io", ".", "IOException", ",", "ClassNotFoundException", "{", "s", ".", "defaultReadObject", "(", ")", ";", "// Read in size and allocate array", "int", "size", "=", "s", ".", "readInt", "(", ")", ";", "allocateElements", "(", "size", ")", ";", "head", "=", "0", ";", "tail", "=", "size", ";", "// Read in all elements in the proper order.", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "elements", "[", "i", "]", "=", "s", ".", "readObject", "(", ")", ";", "}" ]
Deserialize this queue.
[ "Deserialize", "this", "queue", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/core/src/main/java/dagger/internal/ArrayQueue.java#L593-L606
27,773
square/dagger
compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java
GraphAnalysisLoader.resolveType
private static TypeElement resolveType(Elements elements, String className, StringBuilder sb, final int index) { // We assume '$' should be converted to '.'. So we search for classes with dots first. sb.setCharAt(index, '.'); int nextIndex = nextDollar(className, sb, index + 1); TypeElement type = nextIndex == -1 ? getTypeElement(elements, sb) : resolveType(elements, className, sb, nextIndex); if (type != null) { return type; } // if not found, change back to dollar and search. sb.setCharAt(index, '$'); nextIndex = nextDollar(className, sb, index + 1); return nextIndex == -1 ? getTypeElement(elements, sb) : resolveType(elements, className, sb, nextIndex); }
java
private static TypeElement resolveType(Elements elements, String className, StringBuilder sb, final int index) { // We assume '$' should be converted to '.'. So we search for classes with dots first. sb.setCharAt(index, '.'); int nextIndex = nextDollar(className, sb, index + 1); TypeElement type = nextIndex == -1 ? getTypeElement(elements, sb) : resolveType(elements, className, sb, nextIndex); if (type != null) { return type; } // if not found, change back to dollar and search. sb.setCharAt(index, '$'); nextIndex = nextDollar(className, sb, index + 1); return nextIndex == -1 ? getTypeElement(elements, sb) : resolveType(elements, className, sb, nextIndex); }
[ "private", "static", "TypeElement", "resolveType", "(", "Elements", "elements", ",", "String", "className", ",", "StringBuilder", "sb", ",", "final", "int", "index", ")", "{", "// We assume '$' should be converted to '.'. So we search for classes with dots first.", "sb", ".", "setCharAt", "(", "index", ",", "'", "'", ")", ";", "int", "nextIndex", "=", "nextDollar", "(", "className", ",", "sb", ",", "index", "+", "1", ")", ";", "TypeElement", "type", "=", "nextIndex", "==", "-", "1", "?", "getTypeElement", "(", "elements", ",", "sb", ")", ":", "resolveType", "(", "elements", ",", "className", ",", "sb", ",", "nextIndex", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "return", "type", ";", "}", "// if not found, change back to dollar and search.", "sb", ".", "setCharAt", "(", "index", ",", "'", "'", ")", ";", "nextIndex", "=", "nextDollar", "(", "className", ",", "sb", ",", "index", "+", "1", ")", ";", "return", "nextIndex", "==", "-", "1", "?", "getTypeElement", "(", "elements", ",", "sb", ")", ":", "resolveType", "(", "elements", ",", "className", ",", "sb", ",", "nextIndex", ")", ";", "}" ]
Recursively explores the space of possible canonical names for a given binary class name. @param elements used to resolve a name into a {@link TypeElement} @param className binary class name @param sb the current permutation of canonical name to attempt to resolve @param index the index of a {@code '$'} which may be changed to {@code '.'} in a canonical name
[ "Recursively", "explores", "the", "space", "of", "possible", "canonical", "names", "for", "a", "given", "binary", "class", "name", "." ]
572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java#L83-L102
27,774
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalitySpec.java
CardinalitySpec.parse
public static List<PathElement> parse( String key ) { if ( key.contains(AT) ) { return Arrays.<PathElement>asList( new AtPathElement( key ) ); } else if ( STAR.equals(key) ) { return Arrays.<PathElement>asList( new StarAllPathElement( key ) ); } else if ( key.contains(STAR) ) { if ( StringTools.countMatches(key, STAR) == 1 ) { return Arrays.<PathElement>asList( new StarSinglePathElement( key ) ); } else { return Arrays.<PathElement>asList( new StarRegexPathElement( key ) ); } } else { return Arrays.<PathElement>asList( new LiteralPathElement( key ) ); } }
java
public static List<PathElement> parse( String key ) { if ( key.contains(AT) ) { return Arrays.<PathElement>asList( new AtPathElement( key ) ); } else if ( STAR.equals(key) ) { return Arrays.<PathElement>asList( new StarAllPathElement( key ) ); } else if ( key.contains(STAR) ) { if ( StringTools.countMatches(key, STAR) == 1 ) { return Arrays.<PathElement>asList( new StarSinglePathElement( key ) ); } else { return Arrays.<PathElement>asList( new StarRegexPathElement( key ) ); } } else { return Arrays.<PathElement>asList( new LiteralPathElement( key ) ); } }
[ "public", "static", "List", "<", "PathElement", ">", "parse", "(", "String", "key", ")", "{", "if", "(", "key", ".", "contains", "(", "AT", ")", ")", "{", "return", "Arrays", ".", "<", "PathElement", ">", "asList", "(", "new", "AtPathElement", "(", "key", ")", ")", ";", "}", "else", "if", "(", "STAR", ".", "equals", "(", "key", ")", ")", "{", "return", "Arrays", ".", "<", "PathElement", ">", "asList", "(", "new", "StarAllPathElement", "(", "key", ")", ")", ";", "}", "else", "if", "(", "key", ".", "contains", "(", "STAR", ")", ")", "{", "if", "(", "StringTools", ".", "countMatches", "(", "key", ",", "STAR", ")", "==", "1", ")", "{", "return", "Arrays", ".", "<", "PathElement", ">", "asList", "(", "new", "StarSinglePathElement", "(", "key", ")", ")", ";", "}", "else", "{", "return", "Arrays", ".", "<", "PathElement", ">", "asList", "(", "new", "StarRegexPathElement", "(", "key", ")", ")", ";", "}", "}", "else", "{", "return", "Arrays", ".", "<", "PathElement", ">", "asList", "(", "new", "LiteralPathElement", "(", "key", ")", ")", ";", "}", "}" ]
once all the cardinalitytransform specific logic is extracted.
[ "once", "all", "the", "cardinalitytransform", "specific", "logic", "is", "extracted", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalitySpec.java#L76-L95
27,775
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java
Key.processSpec
private static Set<Key> processSpec( boolean parentIsArray, Map<String, Object> spec ) { // TODO switch to List<Key> and sort before returning Set<Key> result = new HashSet<>(); for ( String key : spec.keySet() ) { Object subSpec = spec.get( key ); if ( parentIsArray ) { result.add( new ArrayKey( key, subSpec ) ); // this will recursively call processSpec if needed } else { result.add( new MapKey( key, subSpec ) ); // this will recursively call processSpec if needed } } return result; }
java
private static Set<Key> processSpec( boolean parentIsArray, Map<String, Object> spec ) { // TODO switch to List<Key> and sort before returning Set<Key> result = new HashSet<>(); for ( String key : spec.keySet() ) { Object subSpec = spec.get( key ); if ( parentIsArray ) { result.add( new ArrayKey( key, subSpec ) ); // this will recursively call processSpec if needed } else { result.add( new MapKey( key, subSpec ) ); // this will recursively call processSpec if needed } } return result; }
[ "private", "static", "Set", "<", "Key", ">", "processSpec", "(", "boolean", "parentIsArray", ",", "Map", "<", "String", ",", "Object", ">", "spec", ")", "{", "// TODO switch to List<Key> and sort before returning", "Set", "<", "Key", ">", "result", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "String", "key", ":", "spec", ".", "keySet", "(", ")", ")", "{", "Object", "subSpec", "=", "spec", ".", "get", "(", "key", ")", ";", "if", "(", "parentIsArray", ")", "{", "result", ".", "add", "(", "new", "ArrayKey", "(", "key", ",", "subSpec", ")", ")", ";", "// this will recursively call processSpec if needed", "}", "else", "{", "result", ".", "add", "(", "new", "MapKey", "(", "key", ",", "subSpec", ")", ")", ";", "// this will recursively call processSpec if needed", "}", "}", "return", "result", ";", "}" ]
Recursively walk the spec input tree. Handle arrays by telling DefaultrKeys if they need to be ArrayKeys, and to find the max default array length.
[ "Recursively", "walk", "the", "spec", "input", "tree", ".", "Handle", "arrays", "by", "telling", "DefaultrKeys", "if", "they", "need", "to", "be", "ArrayKeys", "and", "to", "find", "the", "max", "default", "array", "length", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java#L49-L66
27,776
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java
Key.applyChildren
public void applyChildren( Object defaultee ) { if ( defaultee == null ) { throw new TransformException( "Defaultee should never be null when " + "passed to the applyChildren method." ); } // This has nothing to do with this being an ArrayKey or MapKey, instead this is about // this key being the parent of an Array in the output. if ( isArrayOutput() && defaultee instanceof List) { @SuppressWarnings( "unchecked" ) List<Object> defaultList = (List<Object>) defaultee; // Extend the defaultee list if needed for ( int index = defaultList.size() - 1; index < getOutputArraySize(); index++ ) { defaultList.add( null ); } } // Find and sort the children DefaultrKeys by precedence: literals, |, then * ArrayList<Key> sortedChildren = new ArrayList<>(); sortedChildren.addAll( children ); Collections.sort( sortedChildren, keyComparator ); for ( Key childKey : sortedChildren ) { childKey.applyChild( defaultee ); } }
java
public void applyChildren( Object defaultee ) { if ( defaultee == null ) { throw new TransformException( "Defaultee should never be null when " + "passed to the applyChildren method." ); } // This has nothing to do with this being an ArrayKey or MapKey, instead this is about // this key being the parent of an Array in the output. if ( isArrayOutput() && defaultee instanceof List) { @SuppressWarnings( "unchecked" ) List<Object> defaultList = (List<Object>) defaultee; // Extend the defaultee list if needed for ( int index = defaultList.size() - 1; index < getOutputArraySize(); index++ ) { defaultList.add( null ); } } // Find and sort the children DefaultrKeys by precedence: literals, |, then * ArrayList<Key> sortedChildren = new ArrayList<>(); sortedChildren.addAll( children ); Collections.sort( sortedChildren, keyComparator ); for ( Key childKey : sortedChildren ) { childKey.applyChild( defaultee ); } }
[ "public", "void", "applyChildren", "(", "Object", "defaultee", ")", "{", "if", "(", "defaultee", "==", "null", ")", "{", "throw", "new", "TransformException", "(", "\"Defaultee should never be null when \"", "+", "\"passed to the applyChildren method.\"", ")", ";", "}", "// This has nothing to do with this being an ArrayKey or MapKey, instead this is about", "// this key being the parent of an Array in the output.", "if", "(", "isArrayOutput", "(", ")", "&&", "defaultee", "instanceof", "List", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "Object", ">", "defaultList", "=", "(", "List", "<", "Object", ">", ")", "defaultee", ";", "// Extend the defaultee list if needed", "for", "(", "int", "index", "=", "defaultList", ".", "size", "(", ")", "-", "1", ";", "index", "<", "getOutputArraySize", "(", ")", ";", "index", "++", ")", "{", "defaultList", ".", "add", "(", "null", ")", ";", "}", "}", "// Find and sort the children DefaultrKeys by precedence: literals, |, then *", "ArrayList", "<", "Key", ">", "sortedChildren", "=", "new", "ArrayList", "<>", "(", ")", ";", "sortedChildren", ".", "addAll", "(", "children", ")", ";", "Collections", ".", "sort", "(", "sortedChildren", ",", "keyComparator", ")", ";", "for", "(", "Key", "childKey", ":", "sortedChildren", ")", "{", "childKey", ".", "applyChild", "(", "defaultee", ")", ";", "}", "}" ]
This is the main "recursive" method. The defaultee should never be null, because the defaultee wasn't null, it was null and we created it, OR there was a mismatch between the Defaultr Spec and the input, and we didn't recurse.
[ "This", "is", "the", "main", "recursive", "method", ".", "The", "defaultee", "should", "never", "be", "null", "because", "the", "defaultee", "wasn", "t", "null", "it", "was", "null", "and", "we", "created", "it", "OR", "there", "was", "a", "mismatch", "between", "the", "Defaultr", "Spec", "and", "the", "input", "and", "we", "didn", "t", "recurse", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java#L136-L164
27,777
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/Chainr.java
Chainr.transform
@Override public Object transform( Object input, Map<String, Object> context ) { return doTransform( transformsList, input, context ); }
java
@Override public Object transform( Object input, Map<String, Object> context ) { return doTransform( transformsList, input, context ); }
[ "@", "Override", "public", "Object", "transform", "(", "Object", "input", ",", "Map", "<", "String", ",", "Object", ">", "context", ")", "{", "return", "doTransform", "(", "transformsList", ",", "input", ",", "context", ")", ";", "}" ]
Runs a series of Transforms on the input, piping the inputs and outputs of the Transforms together. Chainr instances are meant to be immutable once they are created so that they can be used many times. The notion of passing "context" to the transforms allows chainr instances to be reused, even in situations were you need to slightly vary. @param input a JSON (Jackson-parsed) maps-of-maps object to transform @param context optional tweaks that the consumer of the transform would like @return an object representing the JSON resulting from the transform @throws com.bazaarvoice.jolt.exception.TransformException if the specification is malformed, an operation is not found, or if one of the specified transforms throws an exception.
[ "Runs", "a", "series", "of", "Transforms", "on", "the", "input", "piping", "the", "inputs", "and", "outputs", "of", "the", "Transforms", "together", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/Chainr.java#L173-L176
27,778
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/Chainr.java
Chainr.transform
public Object transform( int from, int to, Object input, Map<String, Object> context ) { if ( from < 0 || to > transformsList.size() || to <= from ) { throw new TransformException( "JOLT Chainr : invalid from and to parameters : from=" + from + " to=" + to ); } return doTransform( transformsList.subList( from, to ), input, context ); }
java
public Object transform( int from, int to, Object input, Map<String, Object> context ) { if ( from < 0 || to > transformsList.size() || to <= from ) { throw new TransformException( "JOLT Chainr : invalid from and to parameters : from=" + from + " to=" + to ); } return doTransform( transformsList.subList( from, to ), input, context ); }
[ "public", "Object", "transform", "(", "int", "from", ",", "int", "to", ",", "Object", "input", ",", "Map", "<", "String", ",", "Object", ">", "context", ")", "{", "if", "(", "from", "<", "0", "||", "to", ">", "transformsList", ".", "size", "(", ")", "||", "to", "<=", "from", ")", "{", "throw", "new", "TransformException", "(", "\"JOLT Chainr : invalid from and to parameters : from=\"", "+", "from", "+", "\" to=\"", "+", "to", ")", ";", "}", "return", "doTransform", "(", "transformsList", ".", "subList", "(", "from", ",", "to", ")", ",", "input", ",", "context", ")", ";", "}" ]
Have Chainr run a subset of the transforms in it's spec. Useful for testing and debugging. @param input the input data to transform @param from transform from the chainrSpec to start with: 0 based index @param to transform from the chainrSpec to end with: 0 based index exclusive @param context optional tweaks that the consumer of the transform would like
[ "Have", "Chainr", "run", "a", "subset", "of", "the", "transforms", "in", "it", "s", "spec", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/Chainr.java#L227-L234
27,779
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/CardinalityTransform.java
CardinalityTransform.transform
@Override public Object transform( Object input ) { rootSpec.apply( ROOT_KEY, Optional.of( input ), new WalkedPath(), null, null ); return input; }
java
@Override public Object transform( Object input ) { rootSpec.apply( ROOT_KEY, Optional.of( input ), new WalkedPath(), null, null ); return input; }
[ "@", "Override", "public", "Object", "transform", "(", "Object", "input", ")", "{", "rootSpec", ".", "apply", "(", "ROOT_KEY", ",", "Optional", ".", "of", "(", "input", ")", ",", "new", "WalkedPath", "(", ")", ",", "null", ",", "null", ")", ";", "return", "input", ";", "}" ]
Applies the Cardinality transform. @param input the JSON object to transform @return the output object with data shifted to it @throws com.bazaarvoice.jolt.exception.TransformException for a malformed spec or if there are issues during the transform
[ "Applies", "the", "Cardinality", "transform", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/CardinalityTransform.java#L230-L236
27,780
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.toNumber
public static Optional<? extends Number> toNumber(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg )); } else if(arg instanceof String) { try { return Optional.of( (Number) Integer.parseInt( (String) arg ) ); } catch(Exception ignored) {} try { return Optional.of( (Number) Long.parseLong( (String) arg ) ); } catch(Exception ignored) {} try { return Optional.of( (Number) Double.parseDouble( (String) arg ) ); } catch(Exception ignored) {} return Optional.empty(); } else { return Optional.empty(); } }
java
public static Optional<? extends Number> toNumber(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg )); } else if(arg instanceof String) { try { return Optional.of( (Number) Integer.parseInt( (String) arg ) ); } catch(Exception ignored) {} try { return Optional.of( (Number) Long.parseLong( (String) arg ) ); } catch(Exception ignored) {} try { return Optional.of( (Number) Double.parseDouble( (String) arg ) ); } catch(Exception ignored) {} return Optional.empty(); } else { return Optional.empty(); } }
[ "public", "static", "Optional", "<", "?", "extends", "Number", ">", "toNumber", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Number", ")", "{", "return", "Optional", ".", "of", "(", "(", "(", "Number", ")", "arg", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "try", "{", "return", "Optional", ".", "of", "(", "(", "Number", ")", "Integer", ".", "parseInt", "(", "(", "String", ")", "arg", ")", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "try", "{", "return", "Optional", ".", "of", "(", "(", "Number", ")", "Long", ".", "parseLong", "(", "(", "String", ")", "arg", ")", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "try", "{", "return", "Optional", ".", "of", "(", "(", "Number", ")", "Double", ".", "parseDouble", "(", "(", "String", ")", "arg", ")", ")", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Given any object, returns, if possible. its Java number equivalent wrapped in Optional Interprets String as Number toNumber("123") == Optional.of(123) toNumber("-123") == Optional.of(-123) toNumber("12.3") == Optional.of(12.3) toNumber("abc") == Optional.empty() toNumber(null) == Optional.empty() also, see: MathTest#testNitPicks
[ "Given", "any", "object", "returns", "if", "possible", ".", "its", "Java", "number", "equivalent", "wrapped", "in", "Optional", "Interprets", "String", "as", "Number" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L42-L64
27,781
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.toInteger
public static Optional<Integer> toInteger(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).intValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().intValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
java
public static Optional<Integer> toInteger(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).intValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().intValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
[ "public", "static", "Optional", "<", "Integer", ">", "toInteger", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Number", ")", "{", "return", "Optional", ".", "of", "(", "(", "(", "Number", ")", "arg", ")", ".", "intValue", "(", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "Optional", "<", "?", "extends", "Number", ">", "optional", "=", "toNumber", "(", "arg", ")", ";", "if", "(", "optional", ".", "isPresent", "(", ")", ")", "{", "return", "Optional", ".", "of", "(", "optional", ".", "get", "(", ")", ".", "intValue", "(", ")", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Returns int value of argument, if possible, wrapped in Optional Interprets String as Number
[ "Returns", "int", "value", "of", "argument", "if", "possible", "wrapped", "in", "Optional", "Interprets", "String", "as", "Number" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L70-L86
27,782
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.toLong
public static Optional<Long> toLong(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).longValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().longValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
java
public static Optional<Long> toLong(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).longValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().longValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
[ "public", "static", "Optional", "<", "Long", ">", "toLong", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Number", ")", "{", "return", "Optional", ".", "of", "(", "(", "(", "Number", ")", "arg", ")", ".", "longValue", "(", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "Optional", "<", "?", "extends", "Number", ">", "optional", "=", "toNumber", "(", "arg", ")", ";", "if", "(", "optional", ".", "isPresent", "(", ")", ")", "{", "return", "Optional", ".", "of", "(", "optional", ".", "get", "(", ")", ".", "longValue", "(", ")", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Returns long value of argument, if possible, wrapped in Optional Interprets String as Number
[ "Returns", "long", "value", "of", "argument", "if", "possible", "wrapped", "in", "Optional", "Interprets", "String", "as", "Number" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L92-L108
27,783
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.toDouble
public static Optional<Double> toDouble(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).doubleValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().doubleValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
java
public static Optional<Double> toDouble(Object arg) { if ( arg instanceof Number ) { return Optional.of( ( (Number) arg ).doubleValue() ); } else if(arg instanceof String) { Optional<? extends Number> optional = toNumber( arg ); if ( optional.isPresent() ) { return Optional.of( optional.get().doubleValue() ); } else { return Optional.empty(); } } else { return Optional.empty(); } }
[ "public", "static", "Optional", "<", "Double", ">", "toDouble", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Number", ")", "{", "return", "Optional", ".", "of", "(", "(", "(", "Number", ")", "arg", ")", ".", "doubleValue", "(", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "Optional", "<", "?", "extends", "Number", ">", "optional", "=", "toNumber", "(", "arg", ")", ";", "if", "(", "optional", ".", "isPresent", "(", ")", ")", "{", "return", "Optional", ".", "of", "(", "optional", ".", "get", "(", ")", ".", "doubleValue", "(", ")", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Returns double value of argument, if possible, wrapped in Optional Interprets String as Number
[ "Returns", "double", "value", "of", "argument", "if", "possible", "wrapped", "in", "Optional", "Interprets", "String", "as", "Number" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L114-L130
27,784
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.toBoolean
public static Optional<Boolean> toBoolean(Object arg) { if ( arg instanceof Boolean ) { return Optional.of( (Boolean) arg ); } else if(arg instanceof String) { if("true".equalsIgnoreCase( (String)arg )) { return Optional.of( Boolean.TRUE ); } else if("false".equalsIgnoreCase( (String)arg )) { return Optional.of( Boolean.FALSE ); } } return Optional.empty(); }
java
public static Optional<Boolean> toBoolean(Object arg) { if ( arg instanceof Boolean ) { return Optional.of( (Boolean) arg ); } else if(arg instanceof String) { if("true".equalsIgnoreCase( (String)arg )) { return Optional.of( Boolean.TRUE ); } else if("false".equalsIgnoreCase( (String)arg )) { return Optional.of( Boolean.FALSE ); } } return Optional.empty(); }
[ "public", "static", "Optional", "<", "Boolean", ">", "toBoolean", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Boolean", ")", "{", "return", "Optional", ".", "of", "(", "(", "Boolean", ")", "arg", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "if", "(", "\"true\"", ".", "equalsIgnoreCase", "(", "(", "String", ")", "arg", ")", ")", "{", "return", "Optional", ".", "of", "(", "Boolean", ".", "TRUE", ")", ";", "}", "else", "if", "(", "\"false\"", ".", "equalsIgnoreCase", "(", "(", "String", ")", "arg", ")", ")", "{", "return", "Optional", ".", "of", "(", "Boolean", ".", "FALSE", ")", ";", "}", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Returns boolean value of argument, if possible, wrapped in Optional Interprets Strings "true" & "false" as boolean
[ "Returns", "boolean", "value", "of", "argument", "if", "possible", "wrapped", "in", "Optional", "Interprets", "Strings", "true", "&", "false", "as", "boolean" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L136-L149
27,785
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.squashNulls
public static void squashNulls( Object input ) { if ( input instanceof List ) { List inputList = (List) input; inputList.removeIf( java.util.Objects::isNull ); } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; List<String> keysToNuke = new ArrayList<>(); for (Map.Entry<String,Object> entry : inputMap.entrySet()) { if ( entry.getValue() == null ) { keysToNuke.add( entry.getKey() ); } } inputMap.keySet().removeAll( keysToNuke ); } }
java
public static void squashNulls( Object input ) { if ( input instanceof List ) { List inputList = (List) input; inputList.removeIf( java.util.Objects::isNull ); } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; List<String> keysToNuke = new ArrayList<>(); for (Map.Entry<String,Object> entry : inputMap.entrySet()) { if ( entry.getValue() == null ) { keysToNuke.add( entry.getKey() ); } } inputMap.keySet().removeAll( keysToNuke ); } }
[ "public", "static", "void", "squashNulls", "(", "Object", "input", ")", "{", "if", "(", "input", "instanceof", "List", ")", "{", "List", "inputList", "=", "(", "List", ")", "input", ";", "inputList", ".", "removeIf", "(", "java", ".", "util", ".", "Objects", "::", "isNull", ")", ";", "}", "else", "if", "(", "input", "instanceof", "Map", ")", "{", "Map", "<", "String", ",", "Object", ">", "inputMap", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "input", ";", "List", "<", "String", ">", "keysToNuke", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "inputMap", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", "==", "null", ")", "{", "keysToNuke", ".", "add", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "inputMap", ".", "keySet", "(", ")", ".", "removeAll", "(", "keysToNuke", ")", ";", "}", "}" ]
Squashes nulls in a list or map. Modifies the data.
[ "Squashes", "nulls", "in", "a", "list", "or", "map", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L176-L193
27,786
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java
Objects.recursivelySquashNulls
public static void recursivelySquashNulls(Object input) { // Makes two passes thru the data. Objects.squashNulls( input ); if ( input instanceof List ) { List inputList = (List) input; inputList.forEach( i -> recursivelySquashNulls( i ) ); } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; for (Map.Entry<String,Object> entry : inputMap.entrySet()) { recursivelySquashNulls( entry.getValue() ); } } }
java
public static void recursivelySquashNulls(Object input) { // Makes two passes thru the data. Objects.squashNulls( input ); if ( input instanceof List ) { List inputList = (List) input; inputList.forEach( i -> recursivelySquashNulls( i ) ); } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; for (Map.Entry<String,Object> entry : inputMap.entrySet()) { recursivelySquashNulls( entry.getValue() ); } } }
[ "public", "static", "void", "recursivelySquashNulls", "(", "Object", "input", ")", "{", "// Makes two passes thru the data.", "Objects", ".", "squashNulls", "(", "input", ")", ";", "if", "(", "input", "instanceof", "List", ")", "{", "List", "inputList", "=", "(", "List", ")", "input", ";", "inputList", ".", "forEach", "(", "i", "->", "recursivelySquashNulls", "(", "i", ")", ")", ";", "}", "else", "if", "(", "input", "instanceof", "Map", ")", "{", "Map", "<", "String", ",", "Object", ">", "inputMap", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "input", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "inputMap", ".", "entrySet", "(", ")", ")", "{", "recursivelySquashNulls", "(", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Recursively squash nulls in maps and lists. Modifies the data.
[ "Recursively", "squash", "nulls", "in", "maps", "and", "lists", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Objects.java#L200-L216
27,787
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java
Math.max
public static Optional<Number> max( List<Object> args ) { if(args == null || args.size() == 0) { return Optional.empty(); } Integer maxInt = Integer.MIN_VALUE; Double maxDouble = -(Double.MAX_VALUE); Long maxLong = Long.MIN_VALUE; boolean found = false; for(Object arg: args) { if(arg instanceof Integer) { maxInt = java.lang.Math.max( maxInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { maxDouble = java.lang.Math.max( maxDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { maxLong = java.lang.Math.max(maxLong, (Long) arg); found = true; } else if(arg instanceof String) { Optional<?> optional = Objects.toNumber( arg ); if(optional.isPresent()) { arg = optional.get(); if(arg instanceof Integer) { maxInt = java.lang.Math.max( maxInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { maxDouble = java.lang.Math.max( maxDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { maxLong = java.lang.Math.max(maxLong, (Long) arg); found = true; } } } } if(!found) { return Optional.empty(); } // explicit getter method calls to avoid runtime autoboxing // autoBoxing will cause it to return the different type // check MathTest#testAutoBoxingIssue for example if(maxInt.longValue() >= maxDouble.longValue() && maxInt.longValue() >= maxLong) { return Optional.<Number>of(maxInt); } else if(maxLong >= maxDouble.longValue()) { return Optional.<Number>of(maxLong); } else { return Optional.<Number>of(maxDouble); } }
java
public static Optional<Number> max( List<Object> args ) { if(args == null || args.size() == 0) { return Optional.empty(); } Integer maxInt = Integer.MIN_VALUE; Double maxDouble = -(Double.MAX_VALUE); Long maxLong = Long.MIN_VALUE; boolean found = false; for(Object arg: args) { if(arg instanceof Integer) { maxInt = java.lang.Math.max( maxInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { maxDouble = java.lang.Math.max( maxDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { maxLong = java.lang.Math.max(maxLong, (Long) arg); found = true; } else if(arg instanceof String) { Optional<?> optional = Objects.toNumber( arg ); if(optional.isPresent()) { arg = optional.get(); if(arg instanceof Integer) { maxInt = java.lang.Math.max( maxInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { maxDouble = java.lang.Math.max( maxDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { maxLong = java.lang.Math.max(maxLong, (Long) arg); found = true; } } } } if(!found) { return Optional.empty(); } // explicit getter method calls to avoid runtime autoboxing // autoBoxing will cause it to return the different type // check MathTest#testAutoBoxingIssue for example if(maxInt.longValue() >= maxDouble.longValue() && maxInt.longValue() >= maxLong) { return Optional.<Number>of(maxInt); } else if(maxLong >= maxDouble.longValue()) { return Optional.<Number>of(maxLong); } else { return Optional.<Number>of(maxDouble); } }
[ "public", "static", "Optional", "<", "Number", ">", "max", "(", "List", "<", "Object", ">", "args", ")", "{", "if", "(", "args", "==", "null", "||", "args", ".", "size", "(", ")", "==", "0", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "Integer", "maxInt", "=", "Integer", ".", "MIN_VALUE", ";", "Double", "maxDouble", "=", "-", "(", "Double", ".", "MAX_VALUE", ")", ";", "Long", "maxLong", "=", "Long", ".", "MIN_VALUE", ";", "boolean", "found", "=", "false", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "if", "(", "arg", "instanceof", "Integer", ")", "{", "maxInt", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxInt", ",", "(", "Integer", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Double", ")", "{", "maxDouble", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxDouble", ",", "(", "Double", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Long", ")", "{", "maxLong", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxLong", ",", "(", "Long", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "Optional", "<", "?", ">", "optional", "=", "Objects", ".", "toNumber", "(", "arg", ")", ";", "if", "(", "optional", ".", "isPresent", "(", ")", ")", "{", "arg", "=", "optional", ".", "get", "(", ")", ";", "if", "(", "arg", "instanceof", "Integer", ")", "{", "maxInt", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxInt", ",", "(", "Integer", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Double", ")", "{", "maxDouble", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxDouble", ",", "(", "Double", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Long", ")", "{", "maxLong", "=", "java", ".", "lang", ".", "Math", ".", "max", "(", "maxLong", ",", "(", "Long", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "}", "}", "}", "if", "(", "!", "found", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// explicit getter method calls to avoid runtime autoboxing", "// autoBoxing will cause it to return the different type", "// check MathTest#testAutoBoxingIssue for example", "if", "(", "maxInt", ".", "longValue", "(", ")", ">=", "maxDouble", ".", "longValue", "(", ")", "&&", "maxInt", ".", "longValue", "(", ")", ">=", "maxLong", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "maxInt", ")", ";", "}", "else", "if", "(", "maxLong", ">=", "maxDouble", ".", "longValue", "(", ")", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "maxLong", ")", ";", "}", "else", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "maxDouble", ")", ";", "}", "}" ]
Given a list of objects, returns the max value in its appropriate type also, interprets String as Number and returns appropriately max(1,2l,3d) == Optional.of(3d) max(1,2l,"3.0") == Optional.of(3.0) max("a", "b", "c") == Optional.empty() max([]) == Optional.empty()
[ "Given", "a", "list", "of", "objects", "returns", "the", "max", "value", "in", "its", "appropriate", "type", "also", "interprets", "String", "as", "Number", "and", "returns", "appropriately" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java#L37-L95
27,788
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java
Math.min
public static Optional<Number> min( List<Object> args ) { if(args == null || args.size() == 0) { return Optional.empty(); } Integer minInt = Integer.MAX_VALUE; Double minDouble = Double.MAX_VALUE; Long minLong = Long.MAX_VALUE; boolean found = false; for(Object arg: args) { if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { minLong = java.lang.Math.min( minLong, (Long) arg ); found = true; } else if(arg instanceof String) { Optional<?> optional = Objects.toNumber( arg ); if(optional.isPresent()) { arg = optional.get(); if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { minLong = java.lang.Math.min(minLong, (Long) arg); found = true; } } } } if(!found) { return Optional.empty(); } // explicit getter method calls to avoid runtime autoboxing if(minInt.longValue() <= minDouble.longValue() && minInt.longValue() <= minLong) { return Optional.<Number>of(minInt); } else if(minLong <= minDouble.longValue()) { return Optional.<Number>of(minLong); } else { return Optional.<Number>of(minDouble); } }
java
public static Optional<Number> min( List<Object> args ) { if(args == null || args.size() == 0) { return Optional.empty(); } Integer minInt = Integer.MAX_VALUE; Double minDouble = Double.MAX_VALUE; Long minLong = Long.MAX_VALUE; boolean found = false; for(Object arg: args) { if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { minLong = java.lang.Math.min( minLong, (Long) arg ); found = true; } else if(arg instanceof String) { Optional<?> optional = Objects.toNumber( arg ); if(optional.isPresent()) { arg = optional.get(); if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); found = true; } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); found = true; } else if(arg instanceof Long) { minLong = java.lang.Math.min(minLong, (Long) arg); found = true; } } } } if(!found) { return Optional.empty(); } // explicit getter method calls to avoid runtime autoboxing if(minInt.longValue() <= minDouble.longValue() && minInt.longValue() <= minLong) { return Optional.<Number>of(minInt); } else if(minLong <= minDouble.longValue()) { return Optional.<Number>of(minLong); } else { return Optional.<Number>of(minDouble); } }
[ "public", "static", "Optional", "<", "Number", ">", "min", "(", "List", "<", "Object", ">", "args", ")", "{", "if", "(", "args", "==", "null", "||", "args", ".", "size", "(", ")", "==", "0", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "Integer", "minInt", "=", "Integer", ".", "MAX_VALUE", ";", "Double", "minDouble", "=", "Double", ".", "MAX_VALUE", ";", "Long", "minLong", "=", "Long", ".", "MAX_VALUE", ";", "boolean", "found", "=", "false", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "if", "(", "arg", "instanceof", "Integer", ")", "{", "minInt", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minInt", ",", "(", "Integer", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Double", ")", "{", "minDouble", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minDouble", ",", "(", "Double", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Long", ")", "{", "minLong", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minLong", ",", "(", "Long", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "Optional", "<", "?", ">", "optional", "=", "Objects", ".", "toNumber", "(", "arg", ")", ";", "if", "(", "optional", ".", "isPresent", "(", ")", ")", "{", "arg", "=", "optional", ".", "get", "(", ")", ";", "if", "(", "arg", "instanceof", "Integer", ")", "{", "minInt", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minInt", ",", "(", "Integer", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Double", ")", "{", "minDouble", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minDouble", ",", "(", "Double", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "else", "if", "(", "arg", "instanceof", "Long", ")", "{", "minLong", "=", "java", ".", "lang", ".", "Math", ".", "min", "(", "minLong", ",", "(", "Long", ")", "arg", ")", ";", "found", "=", "true", ";", "}", "}", "}", "}", "if", "(", "!", "found", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// explicit getter method calls to avoid runtime autoboxing", "if", "(", "minInt", ".", "longValue", "(", ")", "<=", "minDouble", ".", "longValue", "(", ")", "&&", "minInt", ".", "longValue", "(", ")", "<=", "minLong", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "minInt", ")", ";", "}", "else", "if", "(", "minLong", "<=", "minDouble", ".", "longValue", "(", ")", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "minLong", ")", ";", "}", "else", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "minDouble", ")", ";", "}", "}" ]
Given a list of objects, returns the min value in its appropriate type also, interprets String as Number and returns appropriately min(1d,2l,3) == Optional.of(1d) min("1.0",2l,d) == Optional.of(1.0) min("a", "b", "c") == Optional.empty() min([]) == Optional.empty()
[ "Given", "a", "list", "of", "objects", "returns", "the", "min", "value", "in", "its", "appropriate", "type", "also", "interprets", "String", "as", "Number", "and", "returns", "appropriately" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java#L106-L160
27,789
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java
Math.abs
public static Optional<Number> abs( Object arg ) { if(arg instanceof Integer) { return Optional.<Number>of( java.lang.Math.abs( (Integer) arg )); } else if(arg instanceof Double) { return Optional.<Number>of( java.lang.Math.abs( (Double) arg )); } else if(arg instanceof Long) { return Optional.<Number>of( java.lang.Math.abs( (Long) arg )); } else if(arg instanceof String) { return abs( Objects.toNumber( arg ).get() ); } return Optional.empty(); }
java
public static Optional<Number> abs( Object arg ) { if(arg instanceof Integer) { return Optional.<Number>of( java.lang.Math.abs( (Integer) arg )); } else if(arg instanceof Double) { return Optional.<Number>of( java.lang.Math.abs( (Double) arg )); } else if(arg instanceof Long) { return Optional.<Number>of( java.lang.Math.abs( (Long) arg )); } else if(arg instanceof String) { return abs( Objects.toNumber( arg ).get() ); } return Optional.empty(); }
[ "public", "static", "Optional", "<", "Number", ">", "abs", "(", "Object", "arg", ")", "{", "if", "(", "arg", "instanceof", "Integer", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "java", ".", "lang", ".", "Math", ".", "abs", "(", "(", "Integer", ")", "arg", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "Double", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "java", ".", "lang", ".", "Math", ".", "abs", "(", "(", "Double", ")", "arg", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "Long", ")", "{", "return", "Optional", ".", "<", "Number", ">", "of", "(", "java", ".", "lang", ".", "Math", ".", "abs", "(", "(", "Long", ")", "arg", ")", ")", ";", "}", "else", "if", "(", "arg", "instanceof", "String", ")", "{", "return", "abs", "(", "Objects", ".", "toNumber", "(", "arg", ")", ".", "get", "(", ")", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Given any object, returns, if possible. its absolute value wrapped in Optional Interprets String as Number abs("-123") == Optional.of(123) abs("123") == Optional.of(123) abs("12.3") == Optional.of(12.3) abs("abc") == Optional.empty() abs(null) == Optional.empty()
[ "Given", "any", "object", "returns", "if", "possible", ".", "its", "absolute", "value", "wrapped", "in", "Optional", "Interprets", "String", "as", "Number" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java#L174-L188
27,790
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java
Math.avg
public static Optional<Double> avg (List<Object> args) { double sum = 0d; int count = 0; for(Object arg: args) { Optional<? extends Number> numberOptional = Objects.toNumber( arg ); if(numberOptional.isPresent()) { sum = sum + numberOptional.get().doubleValue(); count = count + 1; } } return count == 0 ? Optional.<Double>empty() : Optional.of( sum / count ); }
java
public static Optional<Double> avg (List<Object> args) { double sum = 0d; int count = 0; for(Object arg: args) { Optional<? extends Number> numberOptional = Objects.toNumber( arg ); if(numberOptional.isPresent()) { sum = sum + numberOptional.get().doubleValue(); count = count + 1; } } return count == 0 ? Optional.<Double>empty() : Optional.of( sum / count ); }
[ "public", "static", "Optional", "<", "Double", ">", "avg", "(", "List", "<", "Object", ">", "args", ")", "{", "double", "sum", "=", "0d", ";", "int", "count", "=", "0", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "Optional", "<", "?", "extends", "Number", ">", "numberOptional", "=", "Objects", ".", "toNumber", "(", "arg", ")", ";", "if", "(", "numberOptional", ".", "isPresent", "(", ")", ")", "{", "sum", "=", "sum", "+", "numberOptional", ".", "get", "(", ")", ".", "doubleValue", "(", ")", ";", "count", "=", "count", "+", "1", ";", "}", "}", "return", "count", "==", "0", "?", "Optional", ".", "<", "Double", ">", "empty", "(", ")", ":", "Optional", ".", "of", "(", "sum", "/", "count", ")", ";", "}" ]
Given a list of numbers, returns their avg as double any value in the list that is not a valid number is ignored avg(2,"2","abc") == Optional.of(2.0)
[ "Given", "a", "list", "of", "numbers", "returns", "their", "avg", "as", "double", "any", "value", "in", "the", "list", "that", "is", "not", "a", "valid", "number", "is", "ignored" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/function/Math.java#L196-L207
27,791
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalityLeafSpec.java
CardinalityLeafSpec.applyCardinality
@Override public boolean applyCardinality( String inputKey, Object input, WalkedPath walkedPath, Object parentContainer ) { MatchedElement thisLevel = getMatch( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } performCardinalityAdjustment( inputKey, input, walkedPath, (Map) parentContainer, thisLevel ); return true; }
java
@Override public boolean applyCardinality( String inputKey, Object input, WalkedPath walkedPath, Object parentContainer ) { MatchedElement thisLevel = getMatch( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } performCardinalityAdjustment( inputKey, input, walkedPath, (Map) parentContainer, thisLevel ); return true; }
[ "@", "Override", "public", "boolean", "applyCardinality", "(", "String", "inputKey", ",", "Object", "input", ",", "WalkedPath", "walkedPath", ",", "Object", "parentContainer", ")", "{", "MatchedElement", "thisLevel", "=", "getMatch", "(", "inputKey", ",", "walkedPath", ")", ";", "if", "(", "thisLevel", "==", "null", ")", "{", "return", "false", ";", "}", "performCardinalityAdjustment", "(", "inputKey", ",", "input", ",", "walkedPath", ",", "(", "Map", ")", "parentContainer", ",", "thisLevel", ")", ";", "return", "true", ";", "}" ]
If this CardinalitySpec matches the inputkey, then do the work of modifying the data and return true. @return true if this this spec "handles" the inputkey such that no sibling specs need to see it
[ "If", "this", "CardinalitySpec", "matches", "the", "inputkey", "then", "do", "the", "work", "of", "modifying", "the", "data", "and", "return", "true", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalityLeafSpec.java#L59-L68
27,792
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrLeafSpec.java
RemovrLeafSpec.applyToMap
@Override public List<String> applyToMap( Map<String, Object> inputMap ) { if ( inputMap == null ) { return null; } List<String> keysToBeRemoved = new LinkedList<>(); if ( pathElement instanceof LiteralPathElement ) { // if we are a literal, check to see if we match if ( inputMap.containsKey( pathElement.getRawKey() ) ) { keysToBeRemoved.add( pathElement.getRawKey() ); } } else if ( pathElement instanceof StarPathElement ) { StarPathElement star = (StarPathElement) pathElement; // if we are a wildcard, check each input key to see if it matches us for( String key : inputMap.keySet() ) { if ( star.stringMatch( key ) ) { keysToBeRemoved.add( key ); } } } return keysToBeRemoved; }
java
@Override public List<String> applyToMap( Map<String, Object> inputMap ) { if ( inputMap == null ) { return null; } List<String> keysToBeRemoved = new LinkedList<>(); if ( pathElement instanceof LiteralPathElement ) { // if we are a literal, check to see if we match if ( inputMap.containsKey( pathElement.getRawKey() ) ) { keysToBeRemoved.add( pathElement.getRawKey() ); } } else if ( pathElement instanceof StarPathElement ) { StarPathElement star = (StarPathElement) pathElement; // if we are a wildcard, check each input key to see if it matches us for( String key : inputMap.keySet() ) { if ( star.stringMatch( key ) ) { keysToBeRemoved.add( key ); } } } return keysToBeRemoved; }
[ "@", "Override", "public", "List", "<", "String", ">", "applyToMap", "(", "Map", "<", "String", ",", "Object", ">", "inputMap", ")", "{", "if", "(", "inputMap", "==", "null", ")", "{", "return", "null", ";", "}", "List", "<", "String", ">", "keysToBeRemoved", "=", "new", "LinkedList", "<>", "(", ")", ";", "if", "(", "pathElement", "instanceof", "LiteralPathElement", ")", "{", "// if we are a literal, check to see if we match", "if", "(", "inputMap", ".", "containsKey", "(", "pathElement", ".", "getRawKey", "(", ")", ")", ")", "{", "keysToBeRemoved", ".", "add", "(", "pathElement", ".", "getRawKey", "(", ")", ")", ";", "}", "}", "else", "if", "(", "pathElement", "instanceof", "StarPathElement", ")", "{", "StarPathElement", "star", "=", "(", "StarPathElement", ")", "pathElement", ";", "// if we are a wildcard, check each input key to see if it matches us", "for", "(", "String", "key", ":", "inputMap", ".", "keySet", "(", ")", ")", "{", "if", "(", "star", ".", "stringMatch", "(", "key", ")", ")", "{", "keysToBeRemoved", ".", "add", "(", "key", ")", ";", "}", "}", "}", "return", "keysToBeRemoved", ";", "}" ]
Build a list of keys to remove from the input map, using the pathElement from the Spec. @param inputMap : Input map from which the spec key needs to be removed.
[ "Build", "a", "list", "of", "keys", "to", "remove", "from", "the", "input", "map", "using", "the", "pathElement", "from", "the", "Spec", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrLeafSpec.java#L43-L72
27,793
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/Defaultr.java
Defaultr.transform
@Override public Object transform( Object input ) { if ( input == null ) { // if null, assume HashMap input = new HashMap(); } // TODO : Make copy of the defaultee or like shiftr create a new output object if ( input instanceof List ) { if ( arrayRoot == null ) { throw new TransformException( "The Spec provided can not handle input that is a top level Json Array." ); } arrayRoot.applyChildren( input ); } else { mapRoot.applyChildren( input ); } return input; }
java
@Override public Object transform( Object input ) { if ( input == null ) { // if null, assume HashMap input = new HashMap(); } // TODO : Make copy of the defaultee or like shiftr create a new output object if ( input instanceof List ) { if ( arrayRoot == null ) { throw new TransformException( "The Spec provided can not handle input that is a top level Json Array." ); } arrayRoot.applyChildren( input ); } else { mapRoot.applyChildren( input ); } return input; }
[ "@", "Override", "public", "Object", "transform", "(", "Object", "input", ")", "{", "if", "(", "input", "==", "null", ")", "{", "// if null, assume HashMap", "input", "=", "new", "HashMap", "(", ")", ";", "}", "// TODO : Make copy of the defaultee or like shiftr create a new output object", "if", "(", "input", "instanceof", "List", ")", "{", "if", "(", "arrayRoot", "==", "null", ")", "{", "throw", "new", "TransformException", "(", "\"The Spec provided can not handle input that is a top level Json Array.\"", ")", ";", "}", "arrayRoot", ".", "applyChildren", "(", "input", ")", ";", "}", "else", "{", "mapRoot", ".", "applyChildren", "(", "input", ")", ";", "}", "return", "input", ";", "}" ]
Top level standalone Defaultr method. @param input JSON object to have defaults applied to. This will be modified. @return the modified input
[ "Top", "level", "standalone", "Defaultr", "method", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/Defaultr.java#L226-L246
27,794
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/shiftr/spec/ShiftrCompositeSpec.java
ShiftrCompositeSpec.apply
@Override public boolean apply( String inputKey, Optional<Object> inputOptional, WalkedPath walkedPath, Map<String,Object> output, Map<String, Object> context ) { MatchedElement thisLevel = pathElement.match( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } // If we are a TransposePathElement, try to swap the "input" with what we lookup from the Transpose if ( pathElement instanceof TransposePathElement ) { TransposePathElement tpe = (TransposePathElement) this.pathElement; // Note the data found may not be a String, thus we have to call the special objectEvaluate // Optional, because the input data could have been a valid null. Optional<Object> optional = tpe.objectEvaluate( walkedPath ); if ( !optional.isPresent() ) { return false; } inputOptional = optional; } // add ourselves to the path, so that our children can reference us walkedPath.add( inputOptional.get(), thisLevel ); // Handle any special / key based children first, but don't have them block anything for( ShiftrSpec subSpec : specialChildren ) { subSpec.apply( inputKey, inputOptional, walkedPath, output, context ); } // Handle the rest of the children executionStrategy.process( this, inputOptional, walkedPath, output, context ); // We are done, so remove ourselves from the walkedPath walkedPath.removeLast(); // we matched so increment the matchCount of our parent walkedPath.lastElement().getMatchedElement().incrementHashCount(); return true; }
java
@Override public boolean apply( String inputKey, Optional<Object> inputOptional, WalkedPath walkedPath, Map<String,Object> output, Map<String, Object> context ) { MatchedElement thisLevel = pathElement.match( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } // If we are a TransposePathElement, try to swap the "input" with what we lookup from the Transpose if ( pathElement instanceof TransposePathElement ) { TransposePathElement tpe = (TransposePathElement) this.pathElement; // Note the data found may not be a String, thus we have to call the special objectEvaluate // Optional, because the input data could have been a valid null. Optional<Object> optional = tpe.objectEvaluate( walkedPath ); if ( !optional.isPresent() ) { return false; } inputOptional = optional; } // add ourselves to the path, so that our children can reference us walkedPath.add( inputOptional.get(), thisLevel ); // Handle any special / key based children first, but don't have them block anything for( ShiftrSpec subSpec : specialChildren ) { subSpec.apply( inputKey, inputOptional, walkedPath, output, context ); } // Handle the rest of the children executionStrategy.process( this, inputOptional, walkedPath, output, context ); // We are done, so remove ourselves from the walkedPath walkedPath.removeLast(); // we matched so increment the matchCount of our parent walkedPath.lastElement().getMatchedElement().incrementHashCount(); return true; }
[ "@", "Override", "public", "boolean", "apply", "(", "String", "inputKey", ",", "Optional", "<", "Object", ">", "inputOptional", ",", "WalkedPath", "walkedPath", ",", "Map", "<", "String", ",", "Object", ">", "output", ",", "Map", "<", "String", ",", "Object", ">", "context", ")", "{", "MatchedElement", "thisLevel", "=", "pathElement", ".", "match", "(", "inputKey", ",", "walkedPath", ")", ";", "if", "(", "thisLevel", "==", "null", ")", "{", "return", "false", ";", "}", "// If we are a TransposePathElement, try to swap the \"input\" with what we lookup from the Transpose", "if", "(", "pathElement", "instanceof", "TransposePathElement", ")", "{", "TransposePathElement", "tpe", "=", "(", "TransposePathElement", ")", "this", ".", "pathElement", ";", "// Note the data found may not be a String, thus we have to call the special objectEvaluate", "// Optional, because the input data could have been a valid null.", "Optional", "<", "Object", ">", "optional", "=", "tpe", ".", "objectEvaluate", "(", "walkedPath", ")", ";", "if", "(", "!", "optional", ".", "isPresent", "(", ")", ")", "{", "return", "false", ";", "}", "inputOptional", "=", "optional", ";", "}", "// add ourselves to the path, so that our children can reference us", "walkedPath", ".", "add", "(", "inputOptional", ".", "get", "(", ")", ",", "thisLevel", ")", ";", "// Handle any special / key based children first, but don't have them block anything", "for", "(", "ShiftrSpec", "subSpec", ":", "specialChildren", ")", "{", "subSpec", ".", "apply", "(", "inputKey", ",", "inputOptional", ",", "walkedPath", ",", "output", ",", "context", ")", ";", "}", "// Handle the rest of the children", "executionStrategy", ".", "process", "(", "this", ",", "inputOptional", ",", "walkedPath", ",", "output", ",", "context", ")", ";", "// We are done, so remove ourselves from the walkedPath", "walkedPath", ".", "removeLast", "(", ")", ";", "// we matched so increment the matchCount of our parent", "walkedPath", ".", "lastElement", "(", ")", ".", "getMatchedElement", "(", ")", ".", "incrementHashCount", "(", ")", ";", "return", "true", ";", "}" ]
If this Spec matches the inputKey, then perform one step in the Shiftr parallel treewalk. Step one level down the input "tree" by carefully handling the List/Map nature the input to get the "one level down" data. Step one level down the Spec tree by carefully and efficiently applying our children to the "one level down" data. @return true if this this spec "handles" the inputKey such that no sibling specs need to see it
[ "If", "this", "Spec", "matches", "the", "inputKey", "then", "perform", "one", "step", "in", "the", "Shiftr", "parallel", "treewalk", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/shiftr/spec/ShiftrCompositeSpec.java#L191-L231
27,795
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/spec/ModifierSpec.java
ModifierSpec.setData
@SuppressWarnings( "unchecked" ) protected static void setData(Object parent, MatchedElement matchedElement, Object value, OpMode opMode) { if(parent instanceof Map) { Map source = (Map) parent; String key = matchedElement.getRawKey(); if(opMode.isApplicable( source, key )) { source.put( key, value ); } } else if (parent instanceof List && matchedElement instanceof ArrayMatchedElement ) { List source = (List) parent; int origSize = ( (ArrayMatchedElement) matchedElement ).getOrigSize(); int reqIndex = ( (ArrayMatchedElement) matchedElement ).getRawIndex(); if(opMode.isApplicable( source, reqIndex, origSize )) { source.set( reqIndex, value ); } } else { throw new RuntimeException( "Should not come here!" ); } }
java
@SuppressWarnings( "unchecked" ) protected static void setData(Object parent, MatchedElement matchedElement, Object value, OpMode opMode) { if(parent instanceof Map) { Map source = (Map) parent; String key = matchedElement.getRawKey(); if(opMode.isApplicable( source, key )) { source.put( key, value ); } } else if (parent instanceof List && matchedElement instanceof ArrayMatchedElement ) { List source = (List) parent; int origSize = ( (ArrayMatchedElement) matchedElement ).getOrigSize(); int reqIndex = ( (ArrayMatchedElement) matchedElement ).getRawIndex(); if(opMode.isApplicable( source, reqIndex, origSize )) { source.set( reqIndex, value ); } } else { throw new RuntimeException( "Should not come here!" ); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "static", "void", "setData", "(", "Object", "parent", ",", "MatchedElement", "matchedElement", ",", "Object", "value", ",", "OpMode", "opMode", ")", "{", "if", "(", "parent", "instanceof", "Map", ")", "{", "Map", "source", "=", "(", "Map", ")", "parent", ";", "String", "key", "=", "matchedElement", ".", "getRawKey", "(", ")", ";", "if", "(", "opMode", ".", "isApplicable", "(", "source", ",", "key", ")", ")", "{", "source", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}", "else", "if", "(", "parent", "instanceof", "List", "&&", "matchedElement", "instanceof", "ArrayMatchedElement", ")", "{", "List", "source", "=", "(", "List", ")", "parent", ";", "int", "origSize", "=", "(", "(", "ArrayMatchedElement", ")", "matchedElement", ")", ".", "getOrigSize", "(", ")", ";", "int", "reqIndex", "=", "(", "(", "ArrayMatchedElement", ")", "matchedElement", ")", ".", "getRawIndex", "(", ")", ";", "if", "(", "opMode", ".", "isApplicable", "(", "source", ",", "reqIndex", ",", "origSize", ")", ")", "{", "source", ".", "set", "(", "reqIndex", ",", "value", ")", ";", "}", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Should not come here!\"", ")", ";", "}", "}" ]
Static utility method for facilitating writes on input object @param parent the source object @param matchedElement the current spec (leaf) element that was matched with input @param value to write @param opMode to determine if write is applicable
[ "Static", "utility", "method", "for", "facilitating", "writes", "on", "input", "object" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/modifier/spec/ModifierSpec.java#L127-L147
27,796
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java
JoltCliUtilities.printJsonObject
public static boolean printJsonObject( Object output, Boolean uglyPrint, boolean suppressOutput ) { try { if ( uglyPrint ) { printToStandardOut( JsonUtils.toJsonString( output ), suppressOutput ); } else { printToStandardOut( JsonUtils.toPrettyJsonString( output ), suppressOutput ); } } catch ( Exception e ) { printToStandardOut( "An error occured while attempting to print the output.", suppressOutput ); return false; } return true; }
java
public static boolean printJsonObject( Object output, Boolean uglyPrint, boolean suppressOutput ) { try { if ( uglyPrint ) { printToStandardOut( JsonUtils.toJsonString( output ), suppressOutput ); } else { printToStandardOut( JsonUtils.toPrettyJsonString( output ), suppressOutput ); } } catch ( Exception e ) { printToStandardOut( "An error occured while attempting to print the output.", suppressOutput ); return false; } return true; }
[ "public", "static", "boolean", "printJsonObject", "(", "Object", "output", ",", "Boolean", "uglyPrint", ",", "boolean", "suppressOutput", ")", "{", "try", "{", "if", "(", "uglyPrint", ")", "{", "printToStandardOut", "(", "JsonUtils", ".", "toJsonString", "(", "output", ")", ",", "suppressOutput", ")", ";", "}", "else", "{", "printToStandardOut", "(", "JsonUtils", ".", "toPrettyJsonString", "(", "output", ")", ",", "suppressOutput", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "printToStandardOut", "(", "\"An error occured while attempting to print the output.\"", ",", "suppressOutput", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Prints the given json object to standard out, accounting for pretty printing and suppressed output. @param output The object to print. This method will fail if this object is not well formed JSON. @param uglyPrint ignore pretty print @param suppressOutput suppress output to standard out @return true if printing operation was successful
[ "Prints", "the", "given", "json", "object", "to", "standard", "out", "accounting", "for", "pretty", "printing", "and", "suppressed", "output", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java#L74-L86
27,797
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java
JoltCliUtilities.readJsonInput
public static Object readJsonInput( File file, boolean suppressOutput ) { Object jsonObject; if ( file == null ) { try { jsonObject = JsonUtils.jsonToMap( System.in ); } catch ( Exception e ) { printToStandardOut( "Failed to process standard input.", suppressOutput ); return null; } } else { jsonObject = createJsonObjectFromFile( file, suppressOutput ); } return jsonObject; }
java
public static Object readJsonInput( File file, boolean suppressOutput ) { Object jsonObject; if ( file == null ) { try { jsonObject = JsonUtils.jsonToMap( System.in ); } catch ( Exception e ) { printToStandardOut( "Failed to process standard input.", suppressOutput ); return null; } } else { jsonObject = createJsonObjectFromFile( file, suppressOutput ); } return jsonObject; }
[ "public", "static", "Object", "readJsonInput", "(", "File", "file", ",", "boolean", "suppressOutput", ")", "{", "Object", "jsonObject", ";", "if", "(", "file", "==", "null", ")", "{", "try", "{", "jsonObject", "=", "JsonUtils", ".", "jsonToMap", "(", "System", ".", "in", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "printToStandardOut", "(", "\"Failed to process standard input.\"", ",", "suppressOutput", ")", ";", "return", "null", ";", "}", "}", "else", "{", "jsonObject", "=", "createJsonObjectFromFile", "(", "file", ",", "suppressOutput", ")", ";", "}", "return", "jsonObject", ";", "}" ]
This method will read in JSON, either from the given file or from standard in if the file is null. An object contain the ingested input is returned. @param file the file to read the input from, or null to use standard in @param suppressOutput suppress output of error messages to standard out @return Object containing input if successful or null if an error occured
[ "This", "method", "will", "read", "in", "JSON", "either", "from", "the", "given", "file", "or", "from", "standard", "in", "if", "the", "file", "is", "null", ".", "An", "object", "contain", "the", "ingested", "input", "is", "returned", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java#L96-L109
27,798
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/traversr/SimpleTraversr.java
SimpleTraversr.handleIntermediateGet
@Override public Optional<DataType> handleIntermediateGet( TraversalStep traversalStep, Object tree, String key, TraversalStep.Operation op ) { Optional<Object> optSub = traversalStep.get( tree, key ); Object sub = optSub.get(); if ( sub == null && op == TraversalStep.Operation.SET ) { // get our child to make the container object, so it will be happy with it sub = traversalStep.getChild().newContainer(); traversalStep.overwriteSet( tree, key, sub ); } return Optional.of( (DataType) sub ); }
java
@Override public Optional<DataType> handleIntermediateGet( TraversalStep traversalStep, Object tree, String key, TraversalStep.Operation op ) { Optional<Object> optSub = traversalStep.get( tree, key ); Object sub = optSub.get(); if ( sub == null && op == TraversalStep.Operation.SET ) { // get our child to make the container object, so it will be happy with it sub = traversalStep.getChild().newContainer(); traversalStep.overwriteSet( tree, key, sub ); } return Optional.of( (DataType) sub ); }
[ "@", "Override", "public", "Optional", "<", "DataType", ">", "handleIntermediateGet", "(", "TraversalStep", "traversalStep", ",", "Object", "tree", ",", "String", "key", ",", "TraversalStep", ".", "Operation", "op", ")", "{", "Optional", "<", "Object", ">", "optSub", "=", "traversalStep", ".", "get", "(", "tree", ",", "key", ")", ";", "Object", "sub", "=", "optSub", ".", "get", "(", ")", ";", "if", "(", "sub", "==", "null", "&&", "op", "==", "TraversalStep", ".", "Operation", ".", "SET", ")", "{", "// get our child to make the container object, so it will be happy with it", "sub", "=", "traversalStep", ".", "getChild", "(", ")", ".", "newContainer", "(", ")", ";", "traversalStep", ".", "overwriteSet", "(", "tree", ",", "key", ",", "sub", ")", ";", "}", "return", "Optional", ".", "of", "(", "(", "DataType", ")", "sub", ")", ";", "}" ]
Only make a new instance of a container object for SET, if there is nothing "there".
[ "Only", "make", "a", "new", "instance", "of", "a", "container", "object", "for", "SET", "if", "there", "is", "nothing", "there", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/traversr/SimpleTraversr.java#L47-L62
27,799
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java
TransposePathElement.parse
public static TransposePathElement parse( String key ) { if ( key == null || key.length() < 2 ) { throw new SpecException( "'Transpose Input' key '@', can not be null or of length 1. Offending key : " + key ); } if ( '@' != key.charAt( 0 ) ) { throw new SpecException( "'Transpose Input' key must start with an '@'. Offending key : " + key ); } // Strip off the leading '@' as we don't need it anymore. String meat = key.substring( 1 ); if ( meat.contains( "@" ) ) { throw new SpecException( "@ pathElement can not contain a nested @. Was: " + meat ); } if ( meat.contains( "*" ) || meat.contains( "[]" ) ) { throw new SpecException( "'Transpose Input' can not contain expansion wildcards (* and []). Offending key : " + key ); } // Check to see if the key is wrapped by parens if ( meat.startsWith( "(" ) ) { if ( meat.endsWith( ")" ) ) { meat = meat.substring( 1, meat.length() - 1 ); } else { throw new SpecException( "@ path element that starts with '(' must have a matching ')'. Offending key : " + key ); } } return innerParse( key, meat ); }
java
public static TransposePathElement parse( String key ) { if ( key == null || key.length() < 2 ) { throw new SpecException( "'Transpose Input' key '@', can not be null or of length 1. Offending key : " + key ); } if ( '@' != key.charAt( 0 ) ) { throw new SpecException( "'Transpose Input' key must start with an '@'. Offending key : " + key ); } // Strip off the leading '@' as we don't need it anymore. String meat = key.substring( 1 ); if ( meat.contains( "@" ) ) { throw new SpecException( "@ pathElement can not contain a nested @. Was: " + meat ); } if ( meat.contains( "*" ) || meat.contains( "[]" ) ) { throw new SpecException( "'Transpose Input' can not contain expansion wildcards (* and []). Offending key : " + key ); } // Check to see if the key is wrapped by parens if ( meat.startsWith( "(" ) ) { if ( meat.endsWith( ")" ) ) { meat = meat.substring( 1, meat.length() - 1 ); } else { throw new SpecException( "@ path element that starts with '(' must have a matching ')'. Offending key : " + key ); } } return innerParse( key, meat ); }
[ "public", "static", "TransposePathElement", "parse", "(", "String", "key", ")", "{", "if", "(", "key", "==", "null", "||", "key", ".", "length", "(", ")", "<", "2", ")", "{", "throw", "new", "SpecException", "(", "\"'Transpose Input' key '@', can not be null or of length 1. Offending key : \"", "+", "key", ")", ";", "}", "if", "(", "'", "'", "!=", "key", ".", "charAt", "(", "0", ")", ")", "{", "throw", "new", "SpecException", "(", "\"'Transpose Input' key must start with an '@'. Offending key : \"", "+", "key", ")", ";", "}", "// Strip off the leading '@' as we don't need it anymore.", "String", "meat", "=", "key", ".", "substring", "(", "1", ")", ";", "if", "(", "meat", ".", "contains", "(", "\"@\"", ")", ")", "{", "throw", "new", "SpecException", "(", "\"@ pathElement can not contain a nested @. Was: \"", "+", "meat", ")", ";", "}", "if", "(", "meat", ".", "contains", "(", "\"*\"", ")", "||", "meat", ".", "contains", "(", "\"[]\"", ")", ")", "{", "throw", "new", "SpecException", "(", "\"'Transpose Input' can not contain expansion wildcards (* and []). Offending key : \"", "+", "key", ")", ";", "}", "// Check to see if the key is wrapped by parens", "if", "(", "meat", ".", "startsWith", "(", "\"(\"", ")", ")", "{", "if", "(", "meat", ".", "endsWith", "(", "\")\"", ")", ")", "{", "meat", "=", "meat", ".", "substring", "(", "1", ",", "meat", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "{", "throw", "new", "SpecException", "(", "\"@ path element that starts with '(' must have a matching ')'. Offending key : \"", "+", "key", ")", ";", "}", "}", "return", "innerParse", "(", "key", ",", "meat", ")", ";", "}" ]
Parse a text value from a Spec, into a TransposePathElement. @param key rawKey from a Jolt Spec file @return a TransposePathElement
[ "Parse", "a", "text", "value", "from", "a", "Spec", "into", "a", "TransposePathElement", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java#L80-L110