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
partition
stringclasses
1 value
qatools/properties
src/main/java/ru/qatools/properties/PropertyLoader.java
PropertyLoader.checkRequired
protected void checkRequired(String key, AnnotatedElement element) { if (isRequired(element)) { throw new PropertyLoaderException(String.format("Required property <%s> doesn't exists", key)); } }
java
protected void checkRequired(String key, AnnotatedElement element) { if (isRequired(element)) { throw new PropertyLoaderException(String.format("Required property <%s> doesn't exists", key)); } }
[ "protected", "void", "checkRequired", "(", "String", "key", ",", "AnnotatedElement", "element", ")", "{", "if", "(", "isRequired", "(", "element", ")", ")", "{", "throw", "new", "PropertyLoaderException", "(", "String", ".", "format", "(", "\"Required property <...
Throws an exception if given element is required. @see #isRequired(AnnotatedElement)
[ "Throws", "an", "exception", "if", "given", "element", "is", "required", "." ]
ae50b460a6bb4fcb21afe888b2e86a7613cd2115
https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/PropertyLoader.java#L220-L224
train
qatools/properties
src/main/java/ru/qatools/properties/PropertyLoader.java
PropertyLoader.concat
protected String concat(String first, String second) { return first == null ? second : String.format("%s.%s", first, second); }
java
protected String concat(String first, String second) { return first == null ? second : String.format("%s.%s", first, second); }
[ "protected", "String", "concat", "(", "String", "first", ",", "String", "second", ")", "{", "return", "first", "==", "null", "?", "second", ":", "String", ".", "format", "(", "\"%s.%s\"", ",", "first", ",", "second", ")", ";", "}" ]
Concat the given prefixes into one.
[ "Concat", "the", "given", "prefixes", "into", "one", "." ]
ae50b460a6bb4fcb21afe888b2e86a7613cd2115
https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/PropertyLoader.java#L256-L258
train
qatools/properties
src/main/java/ru/qatools/properties/PropertyLoader.java
PropertyLoader.register
public <T> PropertyLoader register(Converter<T> converter, Class<T> type) { manager.register(type, converter); return this; }
java
public <T> PropertyLoader register(Converter<T> converter, Class<T> type) { manager.register(type, converter); return this; }
[ "public", "<", "T", ">", "PropertyLoader", "register", "(", "Converter", "<", "T", ">", "converter", ",", "Class", "<", "T", ">", "type", ")", "{", "manager", ".", "register", "(", "type", ",", "converter", ")", ";", "return", "this", ";", "}" ]
Register custom converter for given type.
[ "Register", "custom", "converter", "for", "given", "type", "." ]
ae50b460a6bb4fcb21afe888b2e86a7613cd2115
https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/PropertyLoader.java#L356-L359
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/utils/HexStrings.java
HexStrings.byteArrayAsHex
public final static String byteArrayAsHex(final byte[] buf, final int limit) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < limit; ++i) { if ((i % 16) == 0) { // print offset sb.append(nativeAsHex(i, 32)).append(" "); } else if (((i) % 8) == 0) { // split on qword sb.append(" "); } sb.append(nativeAsHex((buf[i] & 0xFF), 8)).append(" "); // hex byte if (((i % 16) == 15) || (i == (buf.length - 1))) { for (int j = (16 - (i % 16)); j > 1; j--) { // padding non exist bytes sb.append(" "); } sb.append(" |"); // byte columns final int start = ((i / 16) * 16); final int end = ((buf.length < i + 1) ? buf.length : (i + 1)); for (int j = start; j < end; ++j) { if ((buf[j] >= 32) && (buf[j] <= 126)) { sb.append((char) buf[j]); } else { sb.append("."); // non-printable character } } sb.append("|\n"); // end column } } return sb.toString(); }
java
public final static String byteArrayAsHex(final byte[] buf, final int limit) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < limit; ++i) { if ((i % 16) == 0) { // print offset sb.append(nativeAsHex(i, 32)).append(" "); } else if (((i) % 8) == 0) { // split on qword sb.append(" "); } sb.append(nativeAsHex((buf[i] & 0xFF), 8)).append(" "); // hex byte if (((i % 16) == 15) || (i == (buf.length - 1))) { for (int j = (16 - (i % 16)); j > 1; j--) { // padding non exist bytes sb.append(" "); } sb.append(" |"); // byte columns final int start = ((i / 16) * 16); final int end = ((buf.length < i + 1) ? buf.length : (i + 1)); for (int j = start; j < end; ++j) { if ((buf[j] >= 32) && (buf[j] <= 126)) { sb.append((char) buf[j]); } else { sb.append("."); // non-printable character } } sb.append("|\n"); // end column } } return sb.toString(); }
[ "public", "final", "static", "String", "byteArrayAsHex", "(", "final", "byte", "[", "]", "buf", ",", "final", "int", "limit", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", ...
Return hexdump of byte-array @param buf is byte array to dump @param limit size to dump from 0-offset to limit @return String representation of hexdump
[ "Return", "hexdump", "of", "byte", "-", "array" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/utils/HexStrings.java#L93-L120
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java
WeakSet.clear
public void clear(final boolean shrink) { while (queue.poll() != null) { ; } if (elementCount > 0) { elementCount = 0; } if (shrink && (elementData.length > 1024) && (elementData.length > defaultSize)) { elementData = newElementArray(defaultSize); } else { Arrays.fill(elementData, null); } computeMaxSize(); while (queue.poll() != null) { ; } }
java
public void clear(final boolean shrink) { while (queue.poll() != null) { ; } if (elementCount > 0) { elementCount = 0; } if (shrink && (elementData.length > 1024) && (elementData.length > defaultSize)) { elementData = newElementArray(defaultSize); } else { Arrays.fill(elementData, null); } computeMaxSize(); while (queue.poll() != null) { ; } }
[ "public", "void", "clear", "(", "final", "boolean", "shrink", ")", "{", "while", "(", "queue", ".", "poll", "(", ")", "!=", "null", ")", "{", ";", "}", "if", "(", "elementCount", ">", "0", ")", "{", "elementCount", "=", "0", ";", "}", "if", "(", ...
Clear the set @param shrink if true, shrink the set to initial size
[ "Clear", "the", "set" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java#L103-L119
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java
WeakSet.get
public T get(final T value) { expungeStaleEntries(); // final int index = (value.hashCode() & 0x7FFFFFFF) % elementData.length; Entry<T> m = elementData[index]; while (m != null) { if (eq(value, m.get())) { return m.get(); } m = m.nextInSlot; } return null; }
java
public T get(final T value) { expungeStaleEntries(); // final int index = (value.hashCode() & 0x7FFFFFFF) % elementData.length; Entry<T> m = elementData[index]; while (m != null) { if (eq(value, m.get())) { return m.get(); } m = m.nextInSlot; } return null; }
[ "public", "T", "get", "(", "final", "T", "value", ")", "{", "expungeStaleEntries", "(", ")", ";", "//", "final", "int", "index", "=", "(", "value", ".", "hashCode", "(", ")", "&", "0x7FFFFFFF", ")", "%", "elementData", ".", "length", ";", "Entry", "<...
Returns the specified value. @param value the value. @return the value, or {@code null} if not found the specified value
[ "Returns", "the", "specified", "value", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java#L127-L139
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java
WeakSet.put
public T put(final T value) { expungeStaleEntries(); // final int hash = value.hashCode(); int index = (hash & 0x7FFFFFFF) % elementData.length; Entry<T> entry = elementData[index]; while (entry != null && !eq(value, entry.get())) { entry = entry.nextInSlot; } if (entry == null) { if (++elementCount > threshold) { expandElementArray(elementData.length); index = (hash & 0x7FFFFFFF) % elementData.length; } entry = createHashedEntry(value, index); return null; } final T result = entry.get(); return result; }
java
public T put(final T value) { expungeStaleEntries(); // final int hash = value.hashCode(); int index = (hash & 0x7FFFFFFF) % elementData.length; Entry<T> entry = elementData[index]; while (entry != null && !eq(value, entry.get())) { entry = entry.nextInSlot; } if (entry == null) { if (++elementCount > threshold) { expandElementArray(elementData.length); index = (hash & 0x7FFFFFFF) % elementData.length; } entry = createHashedEntry(value, index); return null; } final T result = entry.get(); return result; }
[ "public", "T", "put", "(", "final", "T", "value", ")", "{", "expungeStaleEntries", "(", ")", ";", "//", "final", "int", "hash", "=", "value", ".", "hashCode", "(", ")", ";", "int", "index", "=", "(", "hash", "&", "0x7FFFFFFF", ")", "%", "elementData"...
Puts the specified value in the set. @param value the value. @return the value of any previous put or {@code null} if there was no such value.
[ "Puts", "the", "specified", "value", "in", "the", "set", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java#L158-L179
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java
WeakSet.remove
public T remove(final T value) { expungeStaleEntries(); // final Entry<T> entry = removeEntry(value); if (entry == null) { return null; } final T ret = entry.get(); return ret; }
java
public T remove(final T value) { expungeStaleEntries(); // final Entry<T> entry = removeEntry(value); if (entry == null) { return null; } final T ret = entry.get(); return ret; }
[ "public", "T", "remove", "(", "final", "T", "value", ")", "{", "expungeStaleEntries", "(", ")", ";", "//", "final", "Entry", "<", "T", ">", "entry", "=", "removeEntry", "(", "value", ")", ";", "if", "(", "entry", "==", "null", ")", "{", "return", "...
Removes the specified value from this set. @param value the value to remove. @return the value removed or {@code null} if not found
[ "Removes", "the", "specified", "value", "from", "this", "set", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/WeakSet.java#L253-L262
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/FixedIntHashMap.java
FixedIntHashMap.clear
public void clear(boolean shrink) { if (elementCount > 0) { elementCount = 0; } if (shrink && ((elementKeys.length > 1024) && (elementKeys.length > defaultSize))) { elementKeys = newKeyArray(defaultSize); elementValues = newElementArray(defaultSize); } else { Arrays.fill(elementKeys, Integer.MIN_VALUE); Arrays.fill(elementValues, null); } computeMaxSize(); }
java
public void clear(boolean shrink) { if (elementCount > 0) { elementCount = 0; } if (shrink && ((elementKeys.length > 1024) && (elementKeys.length > defaultSize))) { elementKeys = newKeyArray(defaultSize); elementValues = newElementArray(defaultSize); } else { Arrays.fill(elementKeys, Integer.MIN_VALUE); Arrays.fill(elementValues, null); } computeMaxSize(); }
[ "public", "void", "clear", "(", "boolean", "shrink", ")", "{", "if", "(", "elementCount", ">", "0", ")", "{", "elementCount", "=", "0", ";", "}", "if", "(", "shrink", "&&", "(", "(", "elementKeys", ".", "length", ">", "1024", ")", "&&", "(", "eleme...
Removes all mappings from this hash map, leaving it empty. @see #isEmpty @see #size
[ "Removes", "all", "mappings", "from", "this", "hash", "map", "leaving", "it", "empty", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/FixedIntHashMap.java#L97-L109
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/FixedIntHashMap.java
FixedIntHashMap.computeMaxSize
private void computeMaxSize() { threshold = (int) (elementKeys.length * loadFactor); if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + "::computeMaxSize()=" + threshold + " collisions=" + collisions + " (" + (collisions * 100 / elementKeys.length) + ")"); } collisions = 0; }
java
private void computeMaxSize() { threshold = (int) (elementKeys.length * loadFactor); if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + "::computeMaxSize()=" + threshold + " collisions=" + collisions + " (" + (collisions * 100 / elementKeys.length) + ")"); } collisions = 0; }
[ "private", "void", "computeMaxSize", "(", ")", "{", "threshold", "=", "(", "int", ")", "(", "elementKeys", ".", "length", "*", "loadFactor", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "this", ".",...
Returns a shallow copy of this map. @return a shallow copy of this map.
[ "Returns", "a", "shallow", "copy", "of", "this", "map", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/FixedIntHashMap.java#L124-L131
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.createRootNode
protected void createRootNode() { final Node<K, V> node = createLeafNode(); node.allocId(); rootIdx = node.id; height = 1; elements = 0; putNode(node); }
java
protected void createRootNode() { final Node<K, V> node = createLeafNode(); node.allocId(); rootIdx = node.id; height = 1; elements = 0; putNode(node); }
[ "protected", "void", "createRootNode", "(", ")", "{", "final", "Node", "<", "K", ",", "V", ">", "node", "=", "createLeafNode", "(", ")", ";", "node", ".", "allocId", "(", ")", ";", "rootIdx", "=", "node", ".", "id", ";", "height", "=", "1", ";", ...
Create a Leaf root node and alloc nodeid for this
[ "Create", "a", "Leaf", "root", "node", "and", "alloc", "nodeid", "for", "this" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L295-L302
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.getMaxStructSize
private int getMaxStructSize() { final int leafSize = (createLeafNode().getStructMaxSize()); final int internalSize = (createInternalNode().getStructMaxSize()); return Math.max(leafSize, internalSize); }
java
private int getMaxStructSize() { final int leafSize = (createLeafNode().getStructMaxSize()); final int internalSize = (createInternalNode().getStructMaxSize()); return Math.max(leafSize, internalSize); }
[ "private", "int", "getMaxStructSize", "(", ")", "{", "final", "int", "leafSize", "=", "(", "createLeafNode", "(", ")", ".", "getStructMaxSize", "(", ")", ")", ";", "final", "int", "internalSize", "=", "(", "createInternalNode", "(", ")", ".", "getStructMaxSi...
Get the maximal size for a node @return integer with the max size of a leaf / internal node
[ "Get", "the", "maximal", "size", "for", "a", "node" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L309-L313
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.findOptimalNodeOrder
private void findOptimalNodeOrder(final int block_size) { final Node<K, V> leaf = createLeafNode(); final Node<K, V> internal = createInternalNode(); // Get Maximal Size final int nodeSize = Math.max(leaf.getStructEstimateSize(MIN_B_ORDER), internal.getStructEstimateSize(MIN_B_ORDER)); // Find minimal blockSize blockSize = ((nodeSize > block_size) ? roundBlockSize(nodeSize, block_size) : block_size); // Find b-order for Leaf Nodes b_order_leaf = findOptimalNodeOrder(leaf); // Find b-order for Internal Nodes b_order_internal = findOptimalNodeOrder(internal); }
java
private void findOptimalNodeOrder(final int block_size) { final Node<K, V> leaf = createLeafNode(); final Node<K, V> internal = createInternalNode(); // Get Maximal Size final int nodeSize = Math.max(leaf.getStructEstimateSize(MIN_B_ORDER), internal.getStructEstimateSize(MIN_B_ORDER)); // Find minimal blockSize blockSize = ((nodeSize > block_size) ? roundBlockSize(nodeSize, block_size) : block_size); // Find b-order for Leaf Nodes b_order_leaf = findOptimalNodeOrder(leaf); // Find b-order for Internal Nodes b_order_internal = findOptimalNodeOrder(internal); }
[ "private", "void", "findOptimalNodeOrder", "(", "final", "int", "block_size", ")", "{", "final", "Node", "<", "K", ",", "V", ">", "leaf", "=", "createLeafNode", "(", ")", ";", "final", "Node", "<", "K", ",", "V", ">", "internal", "=", "createInternalNode...
Calculate optimal values for b-order to fit in a block of block_size @param block_size integer with block size (bytes)
[ "Calculate", "optimal", "values", "for", "b", "-", "order", "to", "fit", "in", "a", "block", "of", "block_size" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L320-L332
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.findOptimalNodeOrder
private int findOptimalNodeOrder(final Node<K, V> node) { int low = MIN_B_ORDER; // minimal b-order int high = (blockSize / node.getStructEstimateSize(1)) << 2; // estimate high b-order while (low <= high) { int mid = ((low + high) >>> 1); mid += (1 - (mid % 2)); int nodeSize = node.getStructEstimateSize(mid); if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + "::findOptimalNodeOrder(" + node.getClass().getName() + ") blockSize=" + blockSize + " nodeSize=" + nodeSize + " b_low=" + low + " b_order=" + mid + " b_high=" + high); } if (nodeSize < blockSize) { low = mid + 2; } else if (nodeSize > blockSize) { high = mid - 2; } else { return mid; } } return low - 2; }
java
private int findOptimalNodeOrder(final Node<K, V> node) { int low = MIN_B_ORDER; // minimal b-order int high = (blockSize / node.getStructEstimateSize(1)) << 2; // estimate high b-order while (low <= high) { int mid = ((low + high) >>> 1); mid += (1 - (mid % 2)); int nodeSize = node.getStructEstimateSize(mid); if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + "::findOptimalNodeOrder(" + node.getClass().getName() + ") blockSize=" + blockSize + " nodeSize=" + nodeSize + " b_low=" + low + " b_order=" + mid + " b_high=" + high); } if (nodeSize < blockSize) { low = mid + 2; } else if (nodeSize > blockSize) { high = mid - 2; } else { return mid; } } return low - 2; }
[ "private", "int", "findOptimalNodeOrder", "(", "final", "Node", "<", "K", ",", "V", ">", "node", ")", "{", "int", "low", "=", "MIN_B_ORDER", ";", "// minimal b-order", "int", "high", "=", "(", "blockSize", "/", "node", ".", "getStructEstimateSize", "(", "1...
Find b-order for a blockSize of this tree @param node of type Leaf or Integernal @return integer with b-order
[ "Find", "b", "-", "order", "for", "a", "blockSize", "of", "this", "tree" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L340-L364
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.findLeafNode
private final LeafNode<K, V> findLeafNode(final K key, final boolean tracePath) { Node<K, V> node = getNode(rootIdx); if (tracePath) { stackNodes.clear(); stackSlots.clear(); } while (!node.isLeaf()) { final InternalNode<K, V> nodeInternal = (InternalNode<K, V>) node; int slot = node.findSlotByKey(key); slot = ((slot < 0) ? (-slot) - 1 : slot + 1); if (tracePath) { stackNodes.push(nodeInternal); stackSlots.push(slot); } node = getNode(nodeInternal.childs[slot]); if (node == null) { log.error("ERROR childs[" + slot + "] in node=" + nodeInternal); return null; } } return (node.isLeaf() ? (LeafNode<K, V>) node : null); }
java
private final LeafNode<K, V> findLeafNode(final K key, final boolean tracePath) { Node<K, V> node = getNode(rootIdx); if (tracePath) { stackNodes.clear(); stackSlots.clear(); } while (!node.isLeaf()) { final InternalNode<K, V> nodeInternal = (InternalNode<K, V>) node; int slot = node.findSlotByKey(key); slot = ((slot < 0) ? (-slot) - 1 : slot + 1); if (tracePath) { stackNodes.push(nodeInternal); stackSlots.push(slot); } node = getNode(nodeInternal.childs[slot]); if (node == null) { log.error("ERROR childs[" + slot + "] in node=" + nodeInternal); return null; } } return (node.isLeaf() ? (LeafNode<K, V>) node : null); }
[ "private", "final", "LeafNode", "<", "K", ",", "V", ">", "findLeafNode", "(", "final", "K", "key", ",", "final", "boolean", "tracePath", ")", "{", "Node", "<", "K", ",", "V", ">", "node", "=", "getNode", "(", "rootIdx", ")", ";", "if", "(", "traceP...
Find node that can hold the key @param key @return LeafNode<K, V> containing the key or null if not found
[ "Find", "node", "that", "can", "hold", "the", "key" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L425-L446
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.pollFirstEntry
public synchronized TreeEntry<K, V> pollFirstEntry() { final TreeEntry<K, V> entry = firstEntry(); if (entry != null) { remove(entry.getKey()); } return entry; }
java
public synchronized TreeEntry<K, V> pollFirstEntry() { final TreeEntry<K, V> entry = firstEntry(); if (entry != null) { remove(entry.getKey()); } return entry; }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "pollFirstEntry", "(", ")", "{", "final", "TreeEntry", "<", "K", ",", "V", ">", "entry", "=", "firstEntry", "(", ")", ";", "if", "(", "entry", "!=", "null", ")", "{", "remove", "(", "e...
Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. @return entry
[ "Removes", "and", "returns", "a", "key", "-", "value", "mapping", "associated", "with", "the", "least", "key", "in", "this", "map", "or", "null", "if", "the", "map", "is", "empty", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L538-L544
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.pollLastEntry
public synchronized TreeEntry<K, V> pollLastEntry() { final TreeEntry<K, V> entry = lastEntry(); if (entry != null) { remove(entry.getKey()); } return entry; }
java
public synchronized TreeEntry<K, V> pollLastEntry() { final TreeEntry<K, V> entry = lastEntry(); if (entry != null) { remove(entry.getKey()); } return entry; }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "pollLastEntry", "(", ")", "{", "final", "TreeEntry", "<", "K", ",", "V", ">", "entry", "=", "lastEntry", "(", ")", ";", "if", "(", "entry", "!=", "null", ")", "{", "remove", "(", "ent...
Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. @return entry
[ "Removes", "and", "returns", "a", "key", "-", "value", "mapping", "associated", "with", "the", "greatest", "key", "in", "this", "map", "or", "null", "if", "the", "map", "is", "empty", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L552-L558
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.getRoundKey
private final K getRoundKey(final K key, final boolean upORdown, final boolean acceptEqual) { final TreeEntry<K, V> entry = getRoundEntry(key, upORdown, acceptEqual); if (entry == null) { return null; } return entry.getKey(); }
java
private final K getRoundKey(final K key, final boolean upORdown, final boolean acceptEqual) { final TreeEntry<K, V> entry = getRoundEntry(key, upORdown, acceptEqual); if (entry == null) { return null; } return entry.getKey(); }
[ "private", "final", "K", "getRoundKey", "(", "final", "K", "key", ",", "final", "boolean", "upORdown", ",", "final", "boolean", "acceptEqual", ")", "{", "final", "TreeEntry", "<", "K", ",", "V", ">", "entry", "=", "getRoundEntry", "(", "key", ",", "upORd...
Return ceilingKey, floorKey, higherKey or lowerKey @param key the key @param upORdown true returns ceilingKey, false floorKey @param acceptEqual true returns equal keys, otherwise, only higher or lower @return the key found or null if not found
[ "Return", "ceilingKey", "floorKey", "higherKey", "or", "lowerKey" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L635-L641
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.ceilingEntry
public synchronized TreeEntry<K, V> ceilingEntry(final K key) { // Retorna la clave mas cercana mayor o igual a la clave indicada return getRoundEntry(key, true, true); }
java
public synchronized TreeEntry<K, V> ceilingEntry(final K key) { // Retorna la clave mas cercana mayor o igual a la clave indicada return getRoundEntry(key, true, true); }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "ceilingEntry", "(", "final", "K", "key", ")", "{", "// Retorna la clave mas cercana mayor o igual a la clave indicada", "return", "getRoundEntry", "(", "key", ",", "true", ",", "true", ")", ";", "}" ...
Returns the least key greater than or equal to the given key, or null if there is no such key. @param key the key @return the Entry with least key greater than or equal to key, or null if there is no such key
[ "Returns", "the", "least", "key", "greater", "than", "or", "equal", "to", "the", "given", "key", "or", "null", "if", "there", "is", "no", "such", "key", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L649-L652
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.floorEntry
public synchronized TreeEntry<K, V> floorEntry(final K key) { // Retorna la clave mas cercana menor o igual a la clave indicada return getRoundEntry(key, false, true); }
java
public synchronized TreeEntry<K, V> floorEntry(final K key) { // Retorna la clave mas cercana menor o igual a la clave indicada return getRoundEntry(key, false, true); }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "floorEntry", "(", "final", "K", "key", ")", "{", "// Retorna la clave mas cercana menor o igual a la clave indicada", "return", "getRoundEntry", "(", "key", ",", "false", ",", "true", ")", ";", "}" ]
Returns the greatest key less than or equal to the given key, or null if there is no such key. @param key the key @return the Entry with greatest key less than or equal to key, or null if there is no such key
[ "Returns", "the", "greatest", "key", "less", "than", "or", "equal", "to", "the", "given", "key", "or", "null", "if", "there", "is", "no", "such", "key", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L660-L663
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.higherEntry
public synchronized TreeEntry<K, V> higherEntry(final K key) { // Retorna la clave mas cercana mayor a la clave indicada return getRoundEntry(key, true, false); }
java
public synchronized TreeEntry<K, V> higherEntry(final K key) { // Retorna la clave mas cercana mayor a la clave indicada return getRoundEntry(key, true, false); }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "higherEntry", "(", "final", "K", "key", ")", "{", "// Retorna la clave mas cercana mayor a la clave indicada", "return", "getRoundEntry", "(", "key", ",", "true", ",", "false", ")", ";", "}" ]
Returns the least key strictly greater than the given key, or null if there is no such key. @param key the key @return the Entry with least key strictly greater than the given key, or null if there is no such key.
[ "Returns", "the", "least", "key", "strictly", "greater", "than", "the", "given", "key", "or", "null", "if", "there", "is", "no", "such", "key", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L671-L674
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.lowerEntry
public synchronized TreeEntry<K, V> lowerEntry(final K key) { // Retorna la clave mas cercana menor a la clave indicada return getRoundEntry(key, false, false); }
java
public synchronized TreeEntry<K, V> lowerEntry(final K key) { // Retorna la clave mas cercana menor a la clave indicada return getRoundEntry(key, false, false); }
[ "public", "synchronized", "TreeEntry", "<", "K", ",", "V", ">", "lowerEntry", "(", "final", "K", "key", ")", "{", "// Retorna la clave mas cercana menor a la clave indicada", "return", "getRoundEntry", "(", "key", ",", "false", ",", "false", ")", ";", "}" ]
Returns the greatest key strictly less than the given key, or null if there is no such key. @param key the key @return the Entry with greatest key strictly less than the given key, or null if there is no such key.
[ "Returns", "the", "greatest", "key", "strictly", "less", "than", "the", "given", "key", "or", "null", "if", "there", "is", "no", "such", "key", "." ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L682-L685
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.getRoundEntry
private final TreeEntry<K, V> getRoundEntry(final K key, final boolean upORdown, final boolean acceptEqual) { if (!validState) { throw new InvalidStateException(); } if (_isEmpty()) { return null; } if (key == null) { return null; } try { LeafNode<K, V> node = findLeafNode(key, false); if (node == null) { return null; } int slot = node.findSlotByKey(key); if (upORdown) { // ceiling / higher slot = ((slot < 0) ? (-slot) - 1 : (acceptEqual ? slot : slot + 1)); if (slot >= node.allocated) { node = node.nextNode(); if (node == null) { return null; } slot = 0; } } else { // floor / lower slot = ((slot < 0) ? (-slot) - 2 : (acceptEqual ? slot : slot - 1)); if (slot < 0) { node = node.prevNode(); if (node == null) { return null; } slot = node.allocated - 1; } } return ((node.keys[slot] == null) ? null : new TreeEntry<K, V>(node.keys[slot], node.values[slot])); } finally { releaseNodes(); } }
java
private final TreeEntry<K, V> getRoundEntry(final K key, final boolean upORdown, final boolean acceptEqual) { if (!validState) { throw new InvalidStateException(); } if (_isEmpty()) { return null; } if (key == null) { return null; } try { LeafNode<K, V> node = findLeafNode(key, false); if (node == null) { return null; } int slot = node.findSlotByKey(key); if (upORdown) { // ceiling / higher slot = ((slot < 0) ? (-slot) - 1 : (acceptEqual ? slot : slot + 1)); if (slot >= node.allocated) { node = node.nextNode(); if (node == null) { return null; } slot = 0; } } else { // floor / lower slot = ((slot < 0) ? (-slot) - 2 : (acceptEqual ? slot : slot - 1)); if (slot < 0) { node = node.prevNode(); if (node == null) { return null; } slot = node.allocated - 1; } } return ((node.keys[slot] == null) ? null : new TreeEntry<K, V>(node.keys[slot], node.values[slot])); } finally { releaseNodes(); } }
[ "private", "final", "TreeEntry", "<", "K", ",", "V", ">", "getRoundEntry", "(", "final", "K", "key", ",", "final", "boolean", "upORdown", ",", "final", "boolean", "acceptEqual", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidSt...
Return ceilingEntry, floorEntry, higherEntry or lowerEntry @param key the key @param upORdown true returns ceiling/higher, false floor/lower @param acceptEqual true returns equal keys, otherwise, only higher or lower @return the Entry found or null if not found
[ "Return", "ceilingEntry", "floorEntry", "higherEntry", "or", "lowerEntry" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L695-L737
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.get
public synchronized V get(final K key) { if (!validState) { throw new InvalidStateException(); } if (_isEmpty()) { return null; } if (key == null) { return null; } try { final LeafNode<K, V> node = findLeafNode(key, false); if (node == null) { return null; } int slot = node.findSlotByKey(key); if (slot >= 0) { return node.values[slot]; } return null; } finally { releaseNodes(); } }
java
public synchronized V get(final K key) { if (!validState) { throw new InvalidStateException(); } if (_isEmpty()) { return null; } if (key == null) { return null; } try { final LeafNode<K, V> node = findLeafNode(key, false); if (node == null) { return null; } int slot = node.findSlotByKey(key); if (slot >= 0) { return node.values[slot]; } return null; } finally { releaseNodes(); } }
[ "public", "synchronized", "V", "get", "(", "final", "K", "key", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "if", "(", "_isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "i...
Find a Key in the Tree @param key to find @return Value found or null if not
[ "Find", "a", "Key", "in", "the", "Tree" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L755-L778
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.remove
public synchronized boolean remove(final K key) { if (readOnly) { return false; } if (!validState) { throw new InvalidStateException(); } if (key == null) { return false; } try { if (log.isDebugEnabled()) { log.debug("trying remove key=" + key); } submitRedoRemove(key); if (removeIterative(key)) { // removeRecursive(key, rootIdx) elements--; Node<K, V> nodeRoot = getNode(rootIdx); if (nodeRoot.isEmpty() && (elements > 0)) { // root has only one child // Si sale un ClassCastException es porque hay algun error en la cuenta de elementos rootIdx = ((InternalNode<K, V>) nodeRoot).childs[0]; // Clean old nodeRoot freeNode(nodeRoot); if (log.isDebugEnabled()) { log.debug("DECREASES TREE HEIGHT (ROOT): elements=" + elements + " oldRoot=" + nodeRoot.id + " newRoot=" + rootIdx); } height--; // tree height } else if (nodeRoot.isEmpty() && nodeRoot.isLeaf() && (elements == 0) && (getHighestNodeId() > 4096)) { // Hace un reset del arbol para liberar espacio de modo rapido if (log.isDebugEnabled()) { log.debug("RESET TREE: elements=" + elements + " leaf=" + nodeRoot.isLeaf() + " empty=" + nodeRoot.isEmpty() + " id=" + nodeRoot.id + " lastNodeId=" + getHighestNodeId() + " nodeRoot=" + nodeRoot); } clear(); } else if ((elements == 0) && (!nodeRoot.isLeaf() || !nodeRoot.isEmpty())) { log.error("ERROR in TREE: elements=" + elements + " rootLeaf=" + nodeRoot.isLeaf() + " rootEmpty=" + nodeRoot.isEmpty() + " rootId=" + nodeRoot.id + " nodeRoot=" + nodeRoot); } return true; } return false; } finally { stackNodes.clear(); stackSlots.clear(); releaseNodes(); } }
java
public synchronized boolean remove(final K key) { if (readOnly) { return false; } if (!validState) { throw new InvalidStateException(); } if (key == null) { return false; } try { if (log.isDebugEnabled()) { log.debug("trying remove key=" + key); } submitRedoRemove(key); if (removeIterative(key)) { // removeRecursive(key, rootIdx) elements--; Node<K, V> nodeRoot = getNode(rootIdx); if (nodeRoot.isEmpty() && (elements > 0)) { // root has only one child // Si sale un ClassCastException es porque hay algun error en la cuenta de elementos rootIdx = ((InternalNode<K, V>) nodeRoot).childs[0]; // Clean old nodeRoot freeNode(nodeRoot); if (log.isDebugEnabled()) { log.debug("DECREASES TREE HEIGHT (ROOT): elements=" + elements + " oldRoot=" + nodeRoot.id + " newRoot=" + rootIdx); } height--; // tree height } else if (nodeRoot.isEmpty() && nodeRoot.isLeaf() && (elements == 0) && (getHighestNodeId() > 4096)) { // Hace un reset del arbol para liberar espacio de modo rapido if (log.isDebugEnabled()) { log.debug("RESET TREE: elements=" + elements + " leaf=" + nodeRoot.isLeaf() + " empty=" + nodeRoot.isEmpty() + " id=" + nodeRoot.id + " lastNodeId=" + getHighestNodeId() + " nodeRoot=" + nodeRoot); } clear(); } else if ((elements == 0) && (!nodeRoot.isLeaf() || !nodeRoot.isEmpty())) { log.error("ERROR in TREE: elements=" + elements + " rootLeaf=" + nodeRoot.isLeaf() + " rootEmpty=" + nodeRoot.isEmpty() + " rootId=" + nodeRoot.id + " nodeRoot=" + nodeRoot); } return true; } return false; } finally { stackNodes.clear(); stackSlots.clear(); releaseNodes(); } }
[ "public", "synchronized", "boolean", "remove", "(", "final", "K", "key", ")", "{", "if", "(", "readOnly", ")", "{", "return", "false", ";", "}", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "if", ...
Remove a key from key @param key to delete @return true if key was removed, false if not
[ "Remove", "a", "key", "from", "key" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L786-L836
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.toStringIterative
private String toStringIterative() { final String PADDING = " "; final StringBuilder sb = new StringBuilder(); int elements_debug_local_recounter = 0; Node<K, V> node = null; int nodeid = rootIdx; int depth = 0; stackSlots.clear(); stackSlots.push(rootIdx); // init seed, root node boolean lastIsInternal = !Node.isLeaf(rootIdx); while (!stackSlots.isEmpty()) { nodeid = stackSlots.pop(); node = getNode(nodeid); if (!node.isLeaf()) { for (int i = node.allocated; i >= 0; i--) { stackSlots.push(((InternalNode<K, V>) node).childs[i]); } } else { elements_debug_local_recounter += node.allocated; } // For Indentation if (lastIsInternal || !node.isLeaf()) { // Last or Curret are Internal depth += (lastIsInternal ? +1 : -1); } lastIsInternal = !node.isLeaf(); sb.append(PADDING.substring(0, Math.min(PADDING.length(), Math.max(depth - 1, 0)))); // sb.append(node.toString()).append("\n"); } // Count elements sb.append("height=").append(getHeight()).append(" root=").append(rootIdx).append(" low=") .append(lowIdx).append(" high=").append(highIdx).append(" elements=").append(elements) .append(" recounter=").append(elements_debug_local_recounter); return sb.toString(); }
java
private String toStringIterative() { final String PADDING = " "; final StringBuilder sb = new StringBuilder(); int elements_debug_local_recounter = 0; Node<K, V> node = null; int nodeid = rootIdx; int depth = 0; stackSlots.clear(); stackSlots.push(rootIdx); // init seed, root node boolean lastIsInternal = !Node.isLeaf(rootIdx); while (!stackSlots.isEmpty()) { nodeid = stackSlots.pop(); node = getNode(nodeid); if (!node.isLeaf()) { for (int i = node.allocated; i >= 0; i--) { stackSlots.push(((InternalNode<K, V>) node).childs[i]); } } else { elements_debug_local_recounter += node.allocated; } // For Indentation if (lastIsInternal || !node.isLeaf()) { // Last or Curret are Internal depth += (lastIsInternal ? +1 : -1); } lastIsInternal = !node.isLeaf(); sb.append(PADDING.substring(0, Math.min(PADDING.length(), Math.max(depth - 1, 0)))); // sb.append(node.toString()).append("\n"); } // Count elements sb.append("height=").append(getHeight()).append(" root=").append(rootIdx).append(" low=") .append(lowIdx).append(" high=").append(highIdx).append(" elements=").append(elements) .append(" recounter=").append(elements_debug_local_recounter); return sb.toString(); }
[ "private", "String", "toStringIterative", "(", ")", "{", "final", "String", "PADDING", "=", "\" \"", ";", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "elements_debug_local_recounter", "=", "0", "...
A iterative algorithm for converting this tree into a string @return String representing human readable tree
[ "A", "iterative", "algorithm", "for", "converting", "this", "tree", "into", "a", "string" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L1097-L1133
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.toStringRecursive
@SuppressWarnings("unused") private String toStringRecursive() { final StringBuilder sb = new StringBuilder(); int elements_debug_local_recounter = toString(rootIdx, sb, 0); sb.append("height=").append(getHeight()).append(" root=").append(rootIdx).append(" low=") .append(lowIdx).append(" high=").append(highIdx).append(" elements=").append(elements) .append(" recounter=").append(elements_debug_local_recounter); return sb.toString(); }
java
@SuppressWarnings("unused") private String toStringRecursive() { final StringBuilder sb = new StringBuilder(); int elements_debug_local_recounter = toString(rootIdx, sb, 0); sb.append("height=").append(getHeight()).append(" root=").append(rootIdx).append(" low=") .append(lowIdx).append(" high=").append(highIdx).append(" elements=").append(elements) .append(" recounter=").append(elements_debug_local_recounter); return sb.toString(); }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "private", "String", "toStringRecursive", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "elements_debug_local_recounter", "=", "toString", "(", "rootIdx", ",", "...
A recursive algorithm for converting this tree into a string @return String representing human readable tree
[ "A", "recursive", "algorithm", "for", "converting", "this", "tree", "into", "a", "string" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L1140-L1148
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java
BplusTree.iterator
public Iterator<BplusTree.TreeEntry<K, V>> iterator() { return new TreeIterator<BplusTree.TreeEntry<K, V>>(this); }
java
public Iterator<BplusTree.TreeEntry<K, V>> iterator() { return new TreeIterator<BplusTree.TreeEntry<K, V>>(this); }
[ "public", "Iterator", "<", "BplusTree", ".", "TreeEntry", "<", "K", ",", "V", ">", ">", "iterator", "(", ")", "{", "return", "new", "TreeIterator", "<", "BplusTree", ".", "TreeEntry", "<", "K", ",", "V", ">", ">", "(", "this", ")", ";", "}" ]
Note that the iterator cannot be guaranteed to be thread-safe as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. @returns iterator over values in map
[ "Note", "that", "the", "iterator", "cannot", "be", "guaranteed", "to", "be", "thread", "-", "safe", "as", "it", "is", "generally", "speaking", "impossible", "to", "make", "any", "hard", "guarantees", "in", "the", "presence", "of", "unsynchronized", "concurrent...
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/BplusTree.java#L1197-L1199
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/LeafNode.java
LeafNode.prevNode
public LeafNode<K, V> prevNode() { if (leftid == NULL_ID) { return null; } return (LeafNode<K, V>) tree.getNode(leftid); }
java
public LeafNode<K, V> prevNode() { if (leftid == NULL_ID) { return null; } return (LeafNode<K, V>) tree.getNode(leftid); }
[ "public", "LeafNode", "<", "K", ",", "V", ">", "prevNode", "(", ")", "{", "if", "(", "leftid", "==", "NULL_ID", ")", "{", "return", "null", ";", "}", "return", "(", "LeafNode", "<", "K", ",", "V", ">", ")", "tree", ".", "getNode", "(", "leftid", ...
Return the previous LeafNode in LinkedList @return LeafNode<K, V> previous node
[ "Return", "the", "previous", "LeafNode", "in", "LinkedList" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/LeafNode.java#L175-L180
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/LeafNode.java
LeafNode.nextNode
public LeafNode<K, V> nextNode() { if (rightid == NULL_ID) { return null; } return (LeafNode<K, V>) tree.getNode(rightid); }
java
public LeafNode<K, V> nextNode() { if (rightid == NULL_ID) { return null; } return (LeafNode<K, V>) tree.getNode(rightid); }
[ "public", "LeafNode", "<", "K", ",", "V", ">", "nextNode", "(", ")", "{", "if", "(", "rightid", "==", "NULL_ID", ")", "{", "return", "null", ";", "}", "return", "(", "LeafNode", "<", "K", ",", "V", ">", ")", "tree", ".", "getNode", "(", "rightid"...
Return the next LeafNode in LinkedList @return LeafNode<K, V> next node
[ "Return", "the", "next", "LeafNode", "in", "LinkedList" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/LeafNode.java#L187-L192
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.isValid
public synchronized boolean isValid() { if (!validState) { throw new InvalidStateException(); } final long size = size(); if (size == 0) { return true; } try { final long offset = (size - FOOTER_LEN); if (offset < 0) { return false; } if (offset >= offsetOutputCommited) { if (bufOutput.position() > 0) { log.warn("WARN: autoflush forced"); flushBuffer(); } } bufInput.clear(); bufInput.limit(FOOTER_LEN); final int readed = fcInput.position(offset).read(bufInput); if (readed < FOOTER_LEN) { return false; } bufInput.flip(); final int footer = bufInput.get(); // Footer (byte) if (footer != MAGIC_FOOT) { log.error("MAGIC FOOT fake=" + Integer.toHexString(footer) + " expected=" + Integer.toHexString(MAGIC_FOOT)); return false; } return true; } catch (Exception e) { log.error("Exception in isValid()", e); } return false; }
java
public synchronized boolean isValid() { if (!validState) { throw new InvalidStateException(); } final long size = size(); if (size == 0) { return true; } try { final long offset = (size - FOOTER_LEN); if (offset < 0) { return false; } if (offset >= offsetOutputCommited) { if (bufOutput.position() > 0) { log.warn("WARN: autoflush forced"); flushBuffer(); } } bufInput.clear(); bufInput.limit(FOOTER_LEN); final int readed = fcInput.position(offset).read(bufInput); if (readed < FOOTER_LEN) { return false; } bufInput.flip(); final int footer = bufInput.get(); // Footer (byte) if (footer != MAGIC_FOOT) { log.error("MAGIC FOOT fake=" + Integer.toHexString(footer) + " expected=" + Integer.toHexString(MAGIC_FOOT)); return false; } return true; } catch (Exception e) { log.error("Exception in isValid()", e); } return false; }
[ "public", "synchronized", "boolean", "isValid", "(", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "final", "long", "size", "=", "size", "(", ")", ";", "if", "(", "size", "==", "0", ")"...
Read end of valid and check last magic footer @return true if valid
[ "Read", "end", "of", "valid", "and", "check", "last", "magic", "footer" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L249-L286
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.readFromEnd
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) { if (!validState) { throw new InvalidStateException(); } final long size = size(); final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN); return read(offset, buf); }
java
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) { if (!validState) { throw new InvalidStateException(); } final long size = size(); final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN); return read(offset, buf); }
[ "public", "synchronized", "long", "readFromEnd", "(", "final", "long", "datalen", ",", "final", "ByteBuffer", "buf", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "final", "long", "size", "="...
Read desired block of datalen from end of file @param datalen expected @param ByteBuffer @return new offset (offset+headerlen+datalen+footer)
[ "Read", "desired", "block", "of", "datalen", "from", "end", "of", "file" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L368-L375
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.alignBuffer
private final void alignBuffer(final int diff) throws IOException { if (bufOutput.remaining() < diff) { flushBuffer(); } bufOutput.put(MAGIC_PADDING); // Magic for Padding int i = 1; for (; i + 8 <= diff; i += 8) { bufOutput.putLong(0L); } for (; i + 4 <= diff; i += 4) { bufOutput.putInt(0); } switch (diff - i) { case 3: bufOutput.put((byte) 0); case 2: bufOutput.putShort((short) 0); break; case 1: bufOutput.put((byte) 0); } }
java
private final void alignBuffer(final int diff) throws IOException { if (bufOutput.remaining() < diff) { flushBuffer(); } bufOutput.put(MAGIC_PADDING); // Magic for Padding int i = 1; for (; i + 8 <= diff; i += 8) { bufOutput.putLong(0L); } for (; i + 4 <= diff; i += 4) { bufOutput.putInt(0); } switch (diff - i) { case 3: bufOutput.put((byte) 0); case 2: bufOutput.putShort((short) 0); break; case 1: bufOutput.put((byte) 0); } }
[ "private", "final", "void", "alignBuffer", "(", "final", "int", "diff", ")", "throws", "IOException", "{", "if", "(", "bufOutput", ".", "remaining", "(", ")", "<", "diff", ")", "{", "flushBuffer", "(", ")", ";", "}", "bufOutput", ".", "put", "(", "MAGI...
Pad output buffer with NULL to complete alignment @param diff bytes @throws IOException
[ "Pad", "output", "buffer", "with", "NULL", "to", "complete", "alignment" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L547-L568
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.flush
public synchronized boolean flush() { if (!validState) { throw new InvalidStateException(); } try { flushBuffer(); return true; } catch (Exception e) { log.error("Exception in flush()", e); } return false; }
java
public synchronized boolean flush() { if (!validState) { throw new InvalidStateException(); } try { flushBuffer(); return true; } catch (Exception e) { log.error("Exception in flush()", e); } return false; }
[ "public", "synchronized", "boolean", "flush", "(", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "try", "{", "flushBuffer", "(", ")", ";", "return", "true", ";", "}", "catch", "(", "Excep...
Flush buffer to file @return false if exception occur
[ "Flush", "buffer", "to", "file" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L575-L586
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.flushBuffer
private final void flushBuffer() throws IOException { if (bufOutput.position() > 0) { bufOutput.flip(); fcOutput.write(bufOutput); bufOutput.clear(); // log.debug("offsetOutputUncommited=" + offsetOutputUncommited + " offsetOutputCommited=" + // offsetOutputCommited + " fcOutput.position()=" + fcOutput.position()); offsetOutputUncommited = offsetOutputCommited = fcOutput.position(); if (syncOnFlush) { fcOutput.force(false); if (callback != null) { callback.synched(offsetOutputCommited); } } } }
java
private final void flushBuffer() throws IOException { if (bufOutput.position() > 0) { bufOutput.flip(); fcOutput.write(bufOutput); bufOutput.clear(); // log.debug("offsetOutputUncommited=" + offsetOutputUncommited + " offsetOutputCommited=" + // offsetOutputCommited + " fcOutput.position()=" + fcOutput.position()); offsetOutputUncommited = offsetOutputCommited = fcOutput.position(); if (syncOnFlush) { fcOutput.force(false); if (callback != null) { callback.synched(offsetOutputCommited); } } } }
[ "private", "final", "void", "flushBuffer", "(", ")", "throws", "IOException", "{", "if", "(", "bufOutput", ".", "position", "(", ")", ">", "0", ")", "{", "bufOutput", ".", "flip", "(", ")", ";", "fcOutput", ".", "write", "(", "bufOutput", ")", ";", "...
Write uncommited data to disk @throws IOException
[ "Write", "uncommited", "data", "to", "disk" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L593-L608
train
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/btree/InternalNode.java
InternalNode.checkUnderflowWithRight
private final boolean checkUnderflowWithRight(final int slot) { final Node<K, V> nodeLeft = tree.getNode(childs[slot]); if (nodeLeft.isUnderFlow()) { final Node<K, V> nodeRight = tree.getNode(childs[slot + 1]); if (nodeLeft.canMerge(nodeRight)) { nodeLeft.merge(this, slot, nodeRight); childs[slot] = nodeLeft.id; } else { nodeLeft.shiftRL(this, slot, nodeRight); } // // Update Changed Nodes tree.putNode(this); tree.putNode(nodeRight); tree.putNode(nodeLeft); return true; } return false; }
java
private final boolean checkUnderflowWithRight(final int slot) { final Node<K, V> nodeLeft = tree.getNode(childs[slot]); if (nodeLeft.isUnderFlow()) { final Node<K, V> nodeRight = tree.getNode(childs[slot + 1]); if (nodeLeft.canMerge(nodeRight)) { nodeLeft.merge(this, slot, nodeRight); childs[slot] = nodeLeft.id; } else { nodeLeft.shiftRL(this, slot, nodeRight); } // // Update Changed Nodes tree.putNode(this); tree.putNode(nodeRight); tree.putNode(nodeLeft); return true; } return false; }
[ "private", "final", "boolean", "checkUnderflowWithRight", "(", "final", "int", "slot", ")", "{", "final", "Node", "<", "K", ",", "V", ">", "nodeLeft", "=", "tree", ".", "getNode", "(", "childs", "[", "slot", "]", ")", ";", "if", "(", "nodeLeft", ".", ...
Check if underflow ocurred in child of slot @param nodeParent @param slot the index of a child in nodeParent
[ "Check", "if", "underflow", "ocurred", "in", "child", "of", "slot" ]
c79277f79f4604e0fec8349a98519838e3de38f0
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/btree/InternalNode.java#L302-L320
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java
SsdpDiscovery.getDatagram
public static DatagramPacket getDatagram(String serviceType) { StringBuilder sb = new StringBuilder("M-SEARCH * HTTP/1.1\r\n"); sb.append("HOST: " + SsdpParams.getSsdpMulticastAddress().getHostAddress() + ":" + SsdpParams.getSsdpMulticastPort() + "\r\n"); sb.append("MAN: \"ssdp:discover\"\r\n"); sb.append("MX: 3\r\n"); sb.append("USER-AGENT: Resourcepool SSDP Client\r\n"); sb.append(serviceType == null ? "ST: ssdp:all\r\n" : "ST: " + serviceType + "\r\n\r\n"); byte[] content = sb.toString().getBytes(UTF_8); return new DatagramPacket(content, content.length, SsdpParams.getSsdpMulticastAddress(), SsdpParams.getSsdpMulticastPort()); }
java
public static DatagramPacket getDatagram(String serviceType) { StringBuilder sb = new StringBuilder("M-SEARCH * HTTP/1.1\r\n"); sb.append("HOST: " + SsdpParams.getSsdpMulticastAddress().getHostAddress() + ":" + SsdpParams.getSsdpMulticastPort() + "\r\n"); sb.append("MAN: \"ssdp:discover\"\r\n"); sb.append("MX: 3\r\n"); sb.append("USER-AGENT: Resourcepool SSDP Client\r\n"); sb.append(serviceType == null ? "ST: ssdp:all\r\n" : "ST: " + serviceType + "\r\n\r\n"); byte[] content = sb.toString().getBytes(UTF_8); return new DatagramPacket(content, content.length, SsdpParams.getSsdpMulticastAddress(), SsdpParams.getSsdpMulticastPort()); }
[ "public", "static", "DatagramPacket", "getDatagram", "(", "String", "serviceType", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"M-SEARCH * HTTP/1.1\\r\\n\"", ")", ";", "sb", ".", "append", "(", "\"HOST: \"", "+", "SsdpParams", ".", "getSsd...
Get Datagram from serviceType. @param serviceType the serviceType @return the DatagramPacket matching the search request
[ "Get", "Datagram", "from", "serviceType", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java#L22-L31
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/util/Utils.java
Utils.selectAppropriateInterface
public static void selectAppropriateInterface(MulticastSocket socket) throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if (i.isSiteLocalAddress() && !i.isAnyLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isMulticastAddress()) { socket.setNetworkInterface(NetworkInterface.getByName(n.getName())); } } } }
java
public static void selectAppropriateInterface(MulticastSocket socket) throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if (i.isSiteLocalAddress() && !i.isAnyLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isMulticastAddress()) { socket.setNetworkInterface(NetworkInterface.getByName(n.getName())); } } } }
[ "public", "static", "void", "selectAppropriateInterface", "(", "MulticastSocket", "socket", ")", "throws", "SocketException", "{", "Enumeration", "e", "=", "NetworkInterface", ".", "getNetworkInterfaces", "(", ")", ";", "while", "(", "e", ".", "hasMoreElements", "("...
Selects the appropriate interface to use Multicast. This prevents computers with multiple interfaces to select the wrong one by default. @param socket the socket on which we want to bind the specific interface. @throws SocketException if something bad happens
[ "Selects", "the", "appropriate", "interface", "to", "use", "Multicast", ".", "This", "prevents", "computers", "with", "multiple", "interfaces", "to", "select", "the", "wrong", "one", "by", "default", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/util/Utils.java#L23-L36
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java
ResponseParser.parse
public static SsdpResponse parse(DatagramPacket packet) { Map<String, String> headers = new HashMap<String, String>(); byte[] body = null; SsdpResponse.Type type = null; byte[] data = packet.getData(); // Find position of the last header data int endOfHeaders = findEndOfHeaders(data); if (endOfHeaders == -1) { endOfHeaders = packet.getLength(); } // Retrieve all header lines String[] headerLines = new String(Arrays.copyOfRange(data, 0, endOfHeaders)).split("\r\n"); // Determine type of message if (SEARCH_REQUEST_LINE_PATTERN.matcher(headerLines[0]).matches()) { type = SsdpResponse.Type.DISCOVERY_RESPONSE; } else if (SERVICE_ANNOUNCEMENT_LINE_PATTERN.matcher(headerLines[0]).matches()) { type = SsdpResponse.Type.PRESENCE_ANNOUNCEMENT; } // If type was not found, this is not a valid SSDP message. get out of here if (type == null) { return null; } // Let's parse our headers. for (int i = 1; i < headerLines.length; i++) { String line = headerLines[i]; Matcher matcher = HEADER_PATTERN.matcher(line); if (matcher.matches()) { headers.put(matcher.group(1).toUpperCase().trim(), matcher.group(2).trim()); } } // Determine expiry depending on the presence of cache-control or expires headers. long expiry = parseCacheHeader(headers); // Let's see if we have a body. If we do, let's copy the byte array and put it into the response for the user to get. int endOfBody = packet.getLength(); if (endOfBody > endOfHeaders + 4) { body = Arrays.copyOfRange(data, endOfHeaders + 4, endOfBody); } return new SsdpResponse(type, headers, body, expiry, packet.getAddress()); }
java
public static SsdpResponse parse(DatagramPacket packet) { Map<String, String> headers = new HashMap<String, String>(); byte[] body = null; SsdpResponse.Type type = null; byte[] data = packet.getData(); // Find position of the last header data int endOfHeaders = findEndOfHeaders(data); if (endOfHeaders == -1) { endOfHeaders = packet.getLength(); } // Retrieve all header lines String[] headerLines = new String(Arrays.copyOfRange(data, 0, endOfHeaders)).split("\r\n"); // Determine type of message if (SEARCH_REQUEST_LINE_PATTERN.matcher(headerLines[0]).matches()) { type = SsdpResponse.Type.DISCOVERY_RESPONSE; } else if (SERVICE_ANNOUNCEMENT_LINE_PATTERN.matcher(headerLines[0]).matches()) { type = SsdpResponse.Type.PRESENCE_ANNOUNCEMENT; } // If type was not found, this is not a valid SSDP message. get out of here if (type == null) { return null; } // Let's parse our headers. for (int i = 1; i < headerLines.length; i++) { String line = headerLines[i]; Matcher matcher = HEADER_PATTERN.matcher(line); if (matcher.matches()) { headers.put(matcher.group(1).toUpperCase().trim(), matcher.group(2).trim()); } } // Determine expiry depending on the presence of cache-control or expires headers. long expiry = parseCacheHeader(headers); // Let's see if we have a body. If we do, let's copy the byte array and put it into the response for the user to get. int endOfBody = packet.getLength(); if (endOfBody > endOfHeaders + 4) { body = Arrays.copyOfRange(data, endOfHeaders + 4, endOfBody); } return new SsdpResponse(type, headers, body, expiry, packet.getAddress()); }
[ "public", "static", "SsdpResponse", "parse", "(", "DatagramPacket", "packet", ")", "{", "Map", "<", "String", ",", "String", ">", "headers", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "byte", "[", "]", "body", "=", "null",...
Parse incoming Datagram into SsdpResponse. @param packet the incoming datagram. @return the parsed SsdpResponse if it worked, null otherwise
[ "Parse", "incoming", "Datagram", "into", "SsdpResponse", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java#L39-L84
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java
ResponseParser.parseCacheHeader
private static long parseCacheHeader(Map<String, String> headers) { if (headers.get("CACHE-CONTROL") != null) { String cacheControlHeader = headers.get("CACHE-CONTROL"); Matcher m = CACHE_CONTROL_PATTERN.matcher(cacheControlHeader); if (m.matches()) { return new Date().getTime() + Long.parseLong(m.group(1)) * 1000L; } } if (headers.get("EXPIRES") != null) { try { return DATE_HEADER_FORMAT.parse(headers.get("EXPIRES")).getTime(); } catch (ParseException e) { } } // No result, no expiry strategy return 0; }
java
private static long parseCacheHeader(Map<String, String> headers) { if (headers.get("CACHE-CONTROL") != null) { String cacheControlHeader = headers.get("CACHE-CONTROL"); Matcher m = CACHE_CONTROL_PATTERN.matcher(cacheControlHeader); if (m.matches()) { return new Date().getTime() + Long.parseLong(m.group(1)) * 1000L; } } if (headers.get("EXPIRES") != null) { try { return DATE_HEADER_FORMAT.parse(headers.get("EXPIRES")).getTime(); } catch (ParseException e) { } } // No result, no expiry strategy return 0; }
[ "private", "static", "long", "parseCacheHeader", "(", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "if", "(", "headers", ".", "get", "(", "\"CACHE-CONTROL\"", ")", "!=", "null", ")", "{", "String", "cacheControlHeader", "=", "headers", "....
Parse both Cache-Control and Expires headers to determine if there is any caching strategy requested by service. @param headers the headers. @return 0 if no strategy, or the timestamp matching the future expiration in milliseconds otherwise.
[ "Parse", "both", "Cache", "-", "Control", "and", "Expires", "headers", "to", "determine", "if", "there", "is", "any", "caching", "strategy", "requested", "by", "service", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java#L92-L108
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java
ResponseParser.findEndOfHeaders
private static int findEndOfHeaders(byte[] data) { for (int i = 0; i < data.length - 3; i++) { if (data[i] != CRLF[0] || data[i + 1] != CRLF[1] || data[i + 2] != CRLF[0] || data[i + 3] != CRLF[1]) { continue; } // Headers finish here return i; } return -1; }
java
private static int findEndOfHeaders(byte[] data) { for (int i = 0; i < data.length - 3; i++) { if (data[i] != CRLF[0] || data[i + 1] != CRLF[1] || data[i + 2] != CRLF[0] || data[i + 3] != CRLF[1]) { continue; } // Headers finish here return i; } return -1; }
[ "private", "static", "int", "findEndOfHeaders", "(", "byte", "[", "]", "data", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", "-", "3", ";", "i", "++", ")", "{", "if", "(", "data", "[", "i", "]", "!=", "CRLF...
Find the index matching the end of the header data. @param data the request data @return the index if found, -1 otherwise
[ "Find", "the", "index", "matching", "the", "end", "of", "the", "header", "data", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/parser/ResponseParser.java#L116-L125
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.reset
private void reset(DiscoveryRequest req, DiscoveryListener callback) { this.callback = callback; this.state = State.ACTIVE; this.requests = new ArrayList<DiscoveryRequest>(); if (req != null) { requests.add(req); } // Lazily Remove expired entries for (Map.Entry<String, SsdpService> e : this.cache.entrySet()) { if (e.getValue().isExpired()) { this.cache.remove(e.getKey()); } else { // Notify entry which is non expired callback.onServiceDiscovered(e.getValue()); } } }
java
private void reset(DiscoveryRequest req, DiscoveryListener callback) { this.callback = callback; this.state = State.ACTIVE; this.requests = new ArrayList<DiscoveryRequest>(); if (req != null) { requests.add(req); } // Lazily Remove expired entries for (Map.Entry<String, SsdpService> e : this.cache.entrySet()) { if (e.getValue().isExpired()) { this.cache.remove(e.getKey()); } else { // Notify entry which is non expired callback.onServiceDiscovered(e.getValue()); } } }
[ "private", "void", "reset", "(", "DiscoveryRequest", "req", ",", "DiscoveryListener", "callback", ")", "{", "this", ".", "callback", "=", "callback", ";", "this", ".", "state", "=", "State", ".", "ACTIVE", ";", "this", ".", "requests", "=", "new", "ArrayLi...
Reset all stateful attributes. @param req the new discovery request @param callback the callback
[ "Reset", "all", "stateful", "attributes", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L58-L74
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.handleIncomingPacket
private void handleIncomingPacket(DatagramPacket packet) { SsdpResponse response = new ResponseParser().parse(packet); if (response == null) { // Unknown to protocol return; } if (response.getType().equals(SsdpResponse.Type.DISCOVERY_RESPONSE)) { handleDiscoveryResponse(response); } else if (response.getType().equals(SsdpResponse.Type.PRESENCE_ANNOUNCEMENT)) { handlePresenceAnnouncement(response); } }
java
private void handleIncomingPacket(DatagramPacket packet) { SsdpResponse response = new ResponseParser().parse(packet); if (response == null) { // Unknown to protocol return; } if (response.getType().equals(SsdpResponse.Type.DISCOVERY_RESPONSE)) { handleDiscoveryResponse(response); } else if (response.getType().equals(SsdpResponse.Type.PRESENCE_ANNOUNCEMENT)) { handlePresenceAnnouncement(response); } }
[ "private", "void", "handleIncomingPacket", "(", "DatagramPacket", "packet", ")", "{", "SsdpResponse", "response", "=", "new", "ResponseParser", "(", ")", ".", "parse", "(", "packet", ")", ";", "if", "(", "response", "==", "null", ")", "{", "// Unknown to proto...
Thid handler handles incoming SSDP packets. @param packet the received datagram
[ "Thid", "handler", "handles", "incoming", "SSDP", "packets", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L122-L133
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.sendDiscoveryRequest
private void sendDiscoveryRequest() { try { if (requests.isEmpty()) { // Do nothing if no request has been set return; } for (DiscoveryRequest req : requests) { if (req.getServiceTypes() == null || req.getServiceTypes().isEmpty()) { clientSocket.send(SsdpDiscovery.getDatagram(null)); } else { for (String st : req.getServiceTypes()) { clientSocket.send(SsdpDiscovery.getDatagram(st)); } } } } catch (IOException e) { if (clientSocket.isClosed() && !State.ACTIVE.equals(state)) { // This could happen when closing socket. In that case, this is not an issue. return; } callback.onFailed(e); } }
java
private void sendDiscoveryRequest() { try { if (requests.isEmpty()) { // Do nothing if no request has been set return; } for (DiscoveryRequest req : requests) { if (req.getServiceTypes() == null || req.getServiceTypes().isEmpty()) { clientSocket.send(SsdpDiscovery.getDatagram(null)); } else { for (String st : req.getServiceTypes()) { clientSocket.send(SsdpDiscovery.getDatagram(st)); } } } } catch (IOException e) { if (clientSocket.isClosed() && !State.ACTIVE.equals(state)) { // This could happen when closing socket. In that case, this is not an issue. return; } callback.onFailed(e); } }
[ "private", "void", "sendDiscoveryRequest", "(", ")", "{", "try", "{", "if", "(", "requests", ".", "isEmpty", "(", ")", ")", "{", "// Do nothing if no request has been set", "return", ";", "}", "for", "(", "DiscoveryRequest", "req", ":", "requests", ")", "{", ...
Send discovery Multicast request.
[ "Send", "discovery", "Multicast", "request", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L138-L160
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.openAndBindSocket
private void openAndBindSocket() { try { this.clientSocket = new MulticastSocket(); Utils.selectAppropriateInterface(clientSocket); this.clientSocket.joinGroup(SsdpParams.getSsdpMulticastAddress()); } catch (IOException e) { callback.onFailed(e); } }
java
private void openAndBindSocket() { try { this.clientSocket = new MulticastSocket(); Utils.selectAppropriateInterface(clientSocket); this.clientSocket.joinGroup(SsdpParams.getSsdpMulticastAddress()); } catch (IOException e) { callback.onFailed(e); } }
[ "private", "void", "openAndBindSocket", "(", ")", "{", "try", "{", "this", ".", "clientSocket", "=", "new", "MulticastSocket", "(", ")", ";", "Utils", ".", "selectAppropriateInterface", "(", "clientSocket", ")", ";", "this", ".", "clientSocket", ".", "joinGrou...
Open MulticastSocket and bind to Ssdp port.
[ "Open", "MulticastSocket", "and", "bind", "to", "Ssdp", "port", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L165-L173
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.handlePresenceAnnouncement
private void handlePresenceAnnouncement(SsdpResponse response) { SsdpServiceAnnouncement ssdpServiceAnnouncement = response.toServiceAnnouncement(); if (ssdpServiceAnnouncement.getSerialNumber() == null) { callback.onFailed(new NoSerialNumberException()); return; } if (cache.containsKey(ssdpServiceAnnouncement.getSerialNumber())) { callback.onServiceAnnouncement(ssdpServiceAnnouncement); } else { requests.add(DiscoveryRequest.builder().serviceType(ssdpServiceAnnouncement.getServiceType()).build()); } }
java
private void handlePresenceAnnouncement(SsdpResponse response) { SsdpServiceAnnouncement ssdpServiceAnnouncement = response.toServiceAnnouncement(); if (ssdpServiceAnnouncement.getSerialNumber() == null) { callback.onFailed(new NoSerialNumberException()); return; } if (cache.containsKey(ssdpServiceAnnouncement.getSerialNumber())) { callback.onServiceAnnouncement(ssdpServiceAnnouncement); } else { requests.add(DiscoveryRequest.builder().serviceType(ssdpServiceAnnouncement.getServiceType()).build()); } }
[ "private", "void", "handlePresenceAnnouncement", "(", "SsdpResponse", "response", ")", "{", "SsdpServiceAnnouncement", "ssdpServiceAnnouncement", "=", "response", ".", "toServiceAnnouncement", "(", ")", ";", "if", "(", "ssdpServiceAnnouncement", ".", "getSerialNumber", "(...
Handle presence announcement Datagrams. @param response the incoming announcement
[ "Handle", "presence", "announcement", "Datagrams", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L181-L192
train
resourcepool/ssdp-client
src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java
SsdpClientImpl.handleDiscoveryResponse
private void handleDiscoveryResponse(SsdpResponse response) { SsdpService ssdpService = response.toService(); if (ssdpService.getSerialNumber() == null) { callback.onFailed(new NoSerialNumberException()); return; } if (!cache.containsKey(ssdpService.getSerialNumber())) { callback.onServiceDiscovered(ssdpService); } cache.put(ssdpService.getSerialNumber(), ssdpService); }
java
private void handleDiscoveryResponse(SsdpResponse response) { SsdpService ssdpService = response.toService(); if (ssdpService.getSerialNumber() == null) { callback.onFailed(new NoSerialNumberException()); return; } if (!cache.containsKey(ssdpService.getSerialNumber())) { callback.onServiceDiscovered(ssdpService); } cache.put(ssdpService.getSerialNumber(), ssdpService); }
[ "private", "void", "handleDiscoveryResponse", "(", "SsdpResponse", "response", ")", "{", "SsdpService", "ssdpService", "=", "response", ".", "toService", "(", ")", ";", "if", "(", "ssdpService", ".", "getSerialNumber", "(", ")", "==", "null", ")", "{", "callba...
Handle discovery response Datagrams. @param response the incoming response
[ "Handle", "discovery", "response", "Datagrams", "." ]
5c44131c159189e53dfed712bc10b8b3444776b6
https://github.com/resourcepool/ssdp-client/blob/5c44131c159189e53dfed712bc10b8b3444776b6/src/main/java/io/resourcepool/ssdp/client/impl/SsdpClientImpl.java#L199-L209
train
bramp/unsafe
unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java
UnsafeArrayList.get
public T get(T dest, int index) { checkBounds(index); // We would rather do // UnsafeHelper.copyMemory(null, offset(index), dest, firstFieldOffset, elementSize); // but this is unsupported by the Unsafe class copier.copy(dest, offset(index)); return dest; }
java
public T get(T dest, int index) { checkBounds(index); // We would rather do // UnsafeHelper.copyMemory(null, offset(index), dest, firstFieldOffset, elementSize); // but this is unsupported by the Unsafe class copier.copy(dest, offset(index)); return dest; }
[ "public", "T", "get", "(", "T", "dest", ",", "int", "index", ")", "{", "checkBounds", "(", "index", ")", ";", "// We would rather do", "// UnsafeHelper.copyMemory(null, offset(index), dest, firstFieldOffset, elementSize);", "// but this is unsupported by the Unsafe class", "c...
Copies the element at index into dest @param dest The destination object @param index The index of the object to get @return The fetched object
[ "Copies", "the", "element", "at", "index", "into", "dest" ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java#L122-L129
train
bramp/unsafe
unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java
UnsafeArrayList.swap
public void swap(int i, int j) { checkBounds(i); checkBounds(j); if (i == j) return; copier.copy(tmp, offset(i)); unsafe.copyMemory(null, offset(j), null, offset(i), elementSpacing); unsafe.copyMemory(tmp, firstFieldOffset, null, offset(j), elementSize); }
java
public void swap(int i, int j) { checkBounds(i); checkBounds(j); if (i == j) return; copier.copy(tmp, offset(i)); unsafe.copyMemory(null, offset(j), null, offset(i), elementSpacing); unsafe.copyMemory(tmp, firstFieldOffset, null, offset(j), elementSize); }
[ "public", "void", "swap", "(", "int", "i", ",", "int", "j", ")", "{", "checkBounds", "(", "i", ")", ";", "checkBounds", "(", "j", ")", ";", "if", "(", "i", "==", "j", ")", "return", ";", "copier", ".", "copy", "(", "tmp", ",", "offset", "(", ...
Swaps two elements @param i Index of first element @param j Index of second element
[ "Swaps", "two", "elements" ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java#L153-L163
train
bramp/unsafe
unsafe-unroller/src/main/java/net/bramp/unsafe/UnrolledUnsafeCopierBuilder.java
UnrolledUnsafeCopierBuilder.build
public UnsafeCopier build(Unsafe unsafe) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { checkArgument(offset >= 0, "Offset must be set"); checkArgument(length >= 0, "Length must be set"); checkNotNull(unsafe); Class<?> dynamicType = new ByteBuddy() .subclass(UnsafeCopier.class) .method(named("copy")) .intercept(new CopierImplementation(offset, length)).make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); return (UnsafeCopier) dynamicType.getDeclaredConstructor(Unsafe.class).newInstance(unsafe); }
java
public UnsafeCopier build(Unsafe unsafe) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { checkArgument(offset >= 0, "Offset must be set"); checkArgument(length >= 0, "Length must be set"); checkNotNull(unsafe); Class<?> dynamicType = new ByteBuddy() .subclass(UnsafeCopier.class) .method(named("copy")) .intercept(new CopierImplementation(offset, length)).make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); return (UnsafeCopier) dynamicType.getDeclaredConstructor(Unsafe.class).newInstance(unsafe); }
[ "public", "UnsafeCopier", "build", "(", "Unsafe", "unsafe", ")", "throws", "IllegalAccessException", ",", "InstantiationException", ",", "NoSuchMethodException", ",", "InvocationTargetException", "{", "checkArgument", "(", "offset", ">=", "0", ",", "\"Offset must be set\"...
Constructs a new Copier using the passed in Unsafe instance @param unsafe The sun.misc.Unsafe instance this copier uses @return The new UnsageCopier built with the specific parameters @throws IllegalAccessException @throws InstantiationException @throws NoSuchMethodException @throws InvocationTargetException @throws IllegalArgumentException if any argument is invalid
[ "Constructs", "a", "new", "Copier", "using", "the", "passed", "in", "Unsafe", "instance" ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-unroller/src/main/java/net/bramp/unsafe/UnrolledUnsafeCopierBuilder.java#L76-L92
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/sort/QuickSort.java
QuickSort.recursiveQuickSort
public static <E extends Comparable<E>> void recursiveQuickSort(List<E> array, int startIdx, int endIdx) { int idx = partition(array, startIdx, endIdx); // Recursively call quicksort with left part of the partitioned array if (startIdx < idx - 1) { recursiveQuickSort(array, startIdx, idx - 1); } // Recursively call quick sort with right part of the partitioned array if (endIdx > idx) { recursiveQuickSort(array, idx, endIdx); } }
java
public static <E extends Comparable<E>> void recursiveQuickSort(List<E> array, int startIdx, int endIdx) { int idx = partition(array, startIdx, endIdx); // Recursively call quicksort with left part of the partitioned array if (startIdx < idx - 1) { recursiveQuickSort(array, startIdx, idx - 1); } // Recursively call quick sort with right part of the partitioned array if (endIdx > idx) { recursiveQuickSort(array, idx, endIdx); } }
[ "public", "static", "<", "E", "extends", "Comparable", "<", "E", ">", ">", "void", "recursiveQuickSort", "(", "List", "<", "E", ">", "array", ",", "int", "startIdx", ",", "int", "endIdx", ")", "{", "int", "idx", "=", "partition", "(", "array", ",", "...
Recursive quicksort logic. @param array input array @param startIdx start index of the array @param endIdx end index of the array @param <E> generic type of list
[ "Recursive", "quicksort", "logic", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/sort/QuickSort.java#L40-L54
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java
Main.printMemoryLayout2
public static void printMemoryLayout2() { Object o1 = new Object(); Object o2 = new Object(); Byte b1 = new Byte((byte) 0x12); Byte b2 = new Byte((byte) 0x34); Byte b3 = new Byte((byte) 0x56); Long l = new Long(0x0123456789ABCDEFL); Person p = new Person("Bob", 406425600000L, 'M'); System.out .printf("Object len:%d header:%d\n", UnsafeHelper.sizeOf(o1), UnsafeHelper.headerSize(o1)); UnsafeHelper.hexDump(System.out, o1); UnsafeHelper.hexDump(System.out, o2); System.out .printf("Byte len:%d header:%d\n", UnsafeHelper.sizeOf(b1), UnsafeHelper.headerSize(b1)); UnsafeHelper.hexDump(System.out, b1); UnsafeHelper.hexDump(System.out, b2); UnsafeHelper.hexDump(System.out, b3); Byte[] bArray0 = new Byte[] {}; Byte[] bArray1 = new Byte[] {b1}; Byte[] bArray2 = new Byte[] {b1, b2}; Byte[] bArray3 = new Byte[] {b1, b2, b3}; System.out.printf("Byte[0] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray0), UnsafeHelper.headerSize(bArray0)); UnsafeHelper.hexDump(System.out, bArray0); System.out.printf("Byte[1] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray1), UnsafeHelper.headerSize(bArray1)); UnsafeHelper.hexDump(System.out, bArray1); System.out.printf("Byte[2] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray2), UnsafeHelper.headerSize(bArray2)); UnsafeHelper.hexDump(System.out, bArray2); System.out.printf("Byte[3] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray3), UnsafeHelper.headerSize(bArray3)); UnsafeHelper.hexDump(System.out, bArray3); System.out .printf("Long len:%d header:%d\n", UnsafeHelper.sizeOf(l), UnsafeHelper.headerSize(l)); UnsafeHelper.hexDump(System.out, l); System.out .printf("Person len:%d header:%d\n", UnsafeHelper.sizeOf(p), UnsafeHelper.headerSize(p)); UnsafeHelper.hexDump(System.out, p); }
java
public static void printMemoryLayout2() { Object o1 = new Object(); Object o2 = new Object(); Byte b1 = new Byte((byte) 0x12); Byte b2 = new Byte((byte) 0x34); Byte b3 = new Byte((byte) 0x56); Long l = new Long(0x0123456789ABCDEFL); Person p = new Person("Bob", 406425600000L, 'M'); System.out .printf("Object len:%d header:%d\n", UnsafeHelper.sizeOf(o1), UnsafeHelper.headerSize(o1)); UnsafeHelper.hexDump(System.out, o1); UnsafeHelper.hexDump(System.out, o2); System.out .printf("Byte len:%d header:%d\n", UnsafeHelper.sizeOf(b1), UnsafeHelper.headerSize(b1)); UnsafeHelper.hexDump(System.out, b1); UnsafeHelper.hexDump(System.out, b2); UnsafeHelper.hexDump(System.out, b3); Byte[] bArray0 = new Byte[] {}; Byte[] bArray1 = new Byte[] {b1}; Byte[] bArray2 = new Byte[] {b1, b2}; Byte[] bArray3 = new Byte[] {b1, b2, b3}; System.out.printf("Byte[0] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray0), UnsafeHelper.headerSize(bArray0)); UnsafeHelper.hexDump(System.out, bArray0); System.out.printf("Byte[1] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray1), UnsafeHelper.headerSize(bArray1)); UnsafeHelper.hexDump(System.out, bArray1); System.out.printf("Byte[2] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray2), UnsafeHelper.headerSize(bArray2)); UnsafeHelper.hexDump(System.out, bArray2); System.out.printf("Byte[3] len:%d header:%d\n", UnsafeHelper.sizeOf(bArray3), UnsafeHelper.headerSize(bArray3)); UnsafeHelper.hexDump(System.out, bArray3); System.out .printf("Long len:%d header:%d\n", UnsafeHelper.sizeOf(l), UnsafeHelper.headerSize(l)); UnsafeHelper.hexDump(System.out, l); System.out .printf("Person len:%d header:%d\n", UnsafeHelper.sizeOf(p), UnsafeHelper.headerSize(p)); UnsafeHelper.hexDump(System.out, p); }
[ "public", "static", "void", "printMemoryLayout2", "(", ")", "{", "Object", "o1", "=", "new", "Object", "(", ")", ";", "Object", "o2", "=", "new", "Object", "(", ")", ";", "Byte", "b1", "=", "new", "Byte", "(", "(", "byte", ")", "0x12", ")", ";", ...
Prints the memory layout of various test classes.
[ "Prints", "the", "memory", "layout", "of", "various", "test", "classes", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java#L17-L64
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/ArrayListBenchmark.java
ArrayListBenchmark.setup
@Setup(Level.Trial) public void setup() throws Exception { test = benchmarks.get(list + "-" + type); if (test == null) { throw new RuntimeException("Can't find requested test " + list + " " + type); } test.setSize(size); test.setRandomSeed(size); // TODO Use iteration some how test.setup(); }
java
@Setup(Level.Trial) public void setup() throws Exception { test = benchmarks.get(list + "-" + type); if (test == null) { throw new RuntimeException("Can't find requested test " + list + " " + type); } test.setSize(size); test.setRandomSeed(size); // TODO Use iteration some how test.setup(); }
[ "@", "Setup", "(", "Level", ".", "Trial", ")", "public", "void", "setup", "(", ")", "throws", "Exception", "{", "test", "=", "benchmarks", ".", "get", "(", "list", "+", "\"-\"", "+", "type", ")", ";", "if", "(", "test", "==", "null", ")", "{", "t...
Sets up the benchmark. @throws Exception if the setup fails
[ "Sets", "up", "the", "benchmark", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/ArrayListBenchmark.java#L51-L60
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/ArrayListBenchmark.java
ArrayListBenchmark.main
public static void main(String[] args) throws RunnerException { for (String benchmark : benchmarks.keySet()) { String[] parts = benchmark.split("-"); Options opt = new OptionsBuilder() .include(ArrayListBenchmark.class.getSimpleName()) // Warmup, and then run test iterations .warmupIterations(2).measurementIterations(5) // Each iteration call the test repeatedly for ~60 seconds .mode(Mode.AverageTime) .warmupTime(TimeValue.seconds(10)) .measurementTime(TimeValue.seconds(60)) // The size of the list .param("size", "80000000", "20000000", "5000000") .param("list", parts[0]) .param("type", parts[1]) .forks(1).jvmArgs("-Xmx16g") //.addProfiler(MemoryProfiler.class) //.addProfiler(StackProfiler.class) //.addProfiler(GCProfiler.class) .build(); new Runner(opt).run(); } }
java
public static void main(String[] args) throws RunnerException { for (String benchmark : benchmarks.keySet()) { String[] parts = benchmark.split("-"); Options opt = new OptionsBuilder() .include(ArrayListBenchmark.class.getSimpleName()) // Warmup, and then run test iterations .warmupIterations(2).measurementIterations(5) // Each iteration call the test repeatedly for ~60 seconds .mode(Mode.AverageTime) .warmupTime(TimeValue.seconds(10)) .measurementTime(TimeValue.seconds(60)) // The size of the list .param("size", "80000000", "20000000", "5000000") .param("list", parts[0]) .param("type", parts[1]) .forks(1).jvmArgs("-Xmx16g") //.addProfiler(MemoryProfiler.class) //.addProfiler(StackProfiler.class) //.addProfiler(GCProfiler.class) .build(); new Runner(opt).run(); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "RunnerException", "{", "for", "(", "String", "benchmark", ":", "benchmarks", ".", "keySet", "(", ")", ")", "{", "String", "[", "]", "parts", "=", "benchmark", ".", "sp...
Runs the ArrayListBenchmarks. @param args command line arguments @throws RunnerException if the Benchmark Runner fails
[ "Runs", "the", "ArrayListBenchmarks", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/ArrayListBenchmark.java#L92-L121
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java
MemoryUtils.memoryUsage
public static String memoryUsage() { final Runtime runtime = Runtime.getRuntime(); runtime.gc(); final long max = runtime.maxMemory(); final long total = runtime.totalMemory(); final long free = runtime.freeMemory(); final long used = total - free; return String.format("%d\t%d\t%d\t%d", max, total, free, used); }
java
public static String memoryUsage() { final Runtime runtime = Runtime.getRuntime(); runtime.gc(); final long max = runtime.maxMemory(); final long total = runtime.totalMemory(); final long free = runtime.freeMemory(); final long used = total - free; return String.format("%d\t%d\t%d\t%d", max, total, free, used); }
[ "public", "static", "String", "memoryUsage", "(", ")", "{", "final", "Runtime", "runtime", "=", "Runtime", ".", "getRuntime", "(", ")", ";", "runtime", ".", "gc", "(", ")", ";", "final", "long", "max", "=", "runtime", ".", "maxMemory", "(", ")", ";", ...
Calculates the memory usage according to Runtime. @return max, total, free and used memory (in bytes)
[ "Calculates", "the", "memory", "usage", "according", "to", "Runtime", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java#L24-L35
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java
MemoryUtils.getPid
public static int getPid() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); VMManagement mgmt = (VMManagement) jvm.get(runtime); Method getProcessId = mgmt.getClass().getDeclaredMethod("getProcessId"); getProcessId.setAccessible(true); return (Integer) getProcessId.invoke(mgmt); }
java
public static int getPid() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); VMManagement mgmt = (VMManagement) jvm.get(runtime); Method getProcessId = mgmt.getClass().getDeclaredMethod("getProcessId"); getProcessId.setAccessible(true); return (Integer) getProcessId.invoke(mgmt); }
[ "public", "static", "int", "getPid", "(", ")", "throws", "NoSuchFieldException", ",", "IllegalAccessException", ",", "NoSuchMethodException", ",", "InvocationTargetException", "{", "RuntimeMXBean", "runtime", "=", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ...
Returns the pid of the current process. This fails on systems without process identifiers. @return the processes pid @throws NoSuchFieldException if the JVM does not support the VMManagement class @throws IllegalAccessException if the JVM does not support the VMManagement class @throws NoSuchMethodException if the JVM does not support pids. @throws InvocationTargetException if the JVM does not support pids.
[ "Returns", "the", "pid", "of", "the", "current", "process", ".", "This", "fails", "on", "systems", "without", "process", "identifiers", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java#L63-L75
train
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java
MemoryUtils.pidMemoryUsage
public static String pidMemoryUsage(int pid) throws IOException { Process process = new ProcessBuilder().command("ps", "-o", "pid,rss,vsz", "-p", Long.toString(pid)).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); reader.readLine(); // Skip header String line = reader.readLine(); String[] parts = line.trim().split("\\s+", 3); int readPid = Integer.parseInt(parts[0]); if (pid != readPid) { throw new RuntimeException("`ps` returned something unexpected: '" + line + "'"); } long rss = Long.parseLong(parts[1]) * 1024; long vsz = Long.parseLong(parts[2]); // 0 pid, 1 rss, 2 vsz return String.format("%d\t%d", rss, vsz); }
java
public static String pidMemoryUsage(int pid) throws IOException { Process process = new ProcessBuilder().command("ps", "-o", "pid,rss,vsz", "-p", Long.toString(pid)).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); reader.readLine(); // Skip header String line = reader.readLine(); String[] parts = line.trim().split("\\s+", 3); int readPid = Integer.parseInt(parts[0]); if (pid != readPid) { throw new RuntimeException("`ps` returned something unexpected: '" + line + "'"); } long rss = Long.parseLong(parts[1]) * 1024; long vsz = Long.parseLong(parts[2]); // 0 pid, 1 rss, 2 vsz return String.format("%d\t%d", rss, vsz); }
[ "public", "static", "String", "pidMemoryUsage", "(", "int", "pid", ")", "throws", "IOException", "{", "Process", "process", "=", "new", "ProcessBuilder", "(", ")", ".", "command", "(", "\"ps\"", ",", "\"-o\"", ",", "\"pid,rss,vsz\"", ",", "\"-p\"", ",", "Lon...
Calculates the memory usage according to ps for a given pid. @param pid the pid of the process @return the pid, rss, and vsz for the process @throws IOException if executing ps fails
[ "Calculates", "the", "memory", "usage", "according", "to", "ps", "for", "a", "given", "pid", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-benchmark/src/main/java/net/bramp/unsafe/MemoryUtils.java#L84-L105
train
bramp/unsafe
unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java
UnsafeHelper.toAddress
public static long toAddress(Object obj) { Object[] array = new Object[] {obj}; long baseOffset = unsafe.arrayBaseOffset(Object[].class); return normalize(unsafe.getInt(array, baseOffset)); }
java
public static long toAddress(Object obj) { Object[] array = new Object[] {obj}; long baseOffset = unsafe.arrayBaseOffset(Object[].class); return normalize(unsafe.getInt(array, baseOffset)); }
[ "public", "static", "long", "toAddress", "(", "Object", "obj", ")", "{", "Object", "[", "]", "array", "=", "new", "Object", "[", "]", "{", "obj", "}", ";", "long", "baseOffset", "=", "unsafe", ".", "arrayBaseOffset", "(", "Object", "[", "]", ".", "cl...
Returns the address the object is located at <p>WARNING: This does not return a pointer, so be warned pointer arithmetic will not work. @param obj The object @return the address of the object
[ "Returns", "the", "address", "the", "object", "is", "located", "at" ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L55-L59
train
bramp/unsafe
unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java
UnsafeHelper.copyMemory
public static void copyMemory(final Object src, long srcOffset, final Object dest, final long destOffset, final long len) { // TODO make this work if destOffset is not STRIDE aligned Preconditions.checkNotNull(src); Preconditions.checkArgument(len % COPY_STRIDE != 0, "Length (%d) is not a multiple of stride", len); Preconditions.checkArgument(destOffset % COPY_STRIDE != 0, "Dest offset (%d) is not stride aligned", destOffset); long end = destOffset + len; for (long offset = destOffset; offset < end; ) { unsafe.putLong(dest, offset, unsafe.getLong(srcOffset)); offset += COPY_STRIDE; srcOffset += COPY_STRIDE; } }
java
public static void copyMemory(final Object src, long srcOffset, final Object dest, final long destOffset, final long len) { // TODO make this work if destOffset is not STRIDE aligned Preconditions.checkNotNull(src); Preconditions.checkArgument(len % COPY_STRIDE != 0, "Length (%d) is not a multiple of stride", len); Preconditions.checkArgument(destOffset % COPY_STRIDE != 0, "Dest offset (%d) is not stride aligned", destOffset); long end = destOffset + len; for (long offset = destOffset; offset < end; ) { unsafe.putLong(dest, offset, unsafe.getLong(srcOffset)); offset += COPY_STRIDE; srcOffset += COPY_STRIDE; } }
[ "public", "static", "void", "copyMemory", "(", "final", "Object", "src", ",", "long", "srcOffset", ",", "final", "Object", "dest", ",", "final", "long", "destOffset", ",", "final", "long", "len", ")", "{", "// TODO make this work if destOffset is not STRIDE aligned"...
Copies the memory from srcAddress into dest <p>This is our own implementation because Unsafe.copyMemory(Object src, .. Object dest, ...) only works if <a href="https://goo.gl/pBVlJv">dest in an array</a>, so we wrote our only implementations.
[ "Copies", "the", "memory", "from", "srcAddress", "into", "dest" ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L85-L101
train
bramp/unsafe
unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java
UnsafeHelper.copyMemoryFieldByField
public static void copyMemoryFieldByField(long srcAddress, Object dest) { Class clazz = dest.getClass(); while (clazz != Object.class) { for (Field f : clazz.getDeclaredFields()) { if ((f.getModifiers() & Modifier.STATIC) == 0) { final Class type = f.getType(); // TODO maybe support Wrapper classes Preconditions.checkArgument(type.isPrimitive(), "Only primitives are supported"); final long offset = unsafe.objectFieldOffset(f); final long src = srcAddress + offset; if (type == int.class) { unsafe.putInt(dest, offset, unsafe.getInt(src)); } else if (type == long.class) { unsafe.putLong(dest, offset, unsafe.getLong(src)); } else { throw new IllegalArgumentException("Type not supported yet: " + type); } } } clazz = clazz.getSuperclass(); } }
java
public static void copyMemoryFieldByField(long srcAddress, Object dest) { Class clazz = dest.getClass(); while (clazz != Object.class) { for (Field f : clazz.getDeclaredFields()) { if ((f.getModifiers() & Modifier.STATIC) == 0) { final Class type = f.getType(); // TODO maybe support Wrapper classes Preconditions.checkArgument(type.isPrimitive(), "Only primitives are supported"); final long offset = unsafe.objectFieldOffset(f); final long src = srcAddress + offset; if (type == int.class) { unsafe.putInt(dest, offset, unsafe.getInt(src)); } else if (type == long.class) { unsafe.putLong(dest, offset, unsafe.getLong(src)); } else { throw new IllegalArgumentException("Type not supported yet: " + type); } } } clazz = clazz.getSuperclass(); } }
[ "public", "static", "void", "copyMemoryFieldByField", "(", "long", "srcAddress", ",", "Object", "dest", ")", "{", "Class", "clazz", "=", "dest", ".", "getClass", "(", ")", ";", "while", "(", "clazz", "!=", "Object", ".", "class", ")", "{", "for", "(", ...
Copies from srcAddress to dest one field at a time. @param srcAddress @param dest
[ "Copies", "from", "srcAddress", "to", "dest", "one", "field", "at", "a", "time", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L109-L136
train
bramp/unsafe
unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java
UnsafeHelper.toByteArray
public static byte[] toByteArray(Object obj) { int len = (int) sizeOf(obj); byte[] bytes = new byte[len]; unsafe.copyMemory(obj, 0, bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, bytes.length); return bytes; }
java
public static byte[] toByteArray(Object obj) { int len = (int) sizeOf(obj); byte[] bytes = new byte[len]; unsafe.copyMemory(obj, 0, bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, bytes.length); return bytes; }
[ "public", "static", "byte", "[", "]", "toByteArray", "(", "Object", "obj", ")", "{", "int", "len", "=", "(", "int", ")", "sizeOf", "(", "obj", ")", ";", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "len", "]", ";", "unsafe", ".", "copyMemo...
Returns the object as a byte array, including header, padding and all fields. @param obj @return
[ "Returns", "the", "object", "as", "a", "byte", "array", "including", "header", "padding", "and", "all", "fields", "." ]
805f54e2a8aee905003329556135b6c4059b4418
https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L280-L285
train
sarxos/win-registry
src/main/java/com/github/sarxos/winreg/internal/WindowsPreferencesBuilder.java
WindowsPreferencesBuilder.stringToByteArray
private static byte[] stringToByteArray(String str) { byte[] result = new byte[str.length() + 1]; for (int i = 0; i < str.length(); i++) { result[i] = (byte) str.charAt(i); } result[str.length()] = 0; return result; }
java
private static byte[] stringToByteArray(String str) { byte[] result = new byte[str.length() + 1]; for (int i = 0; i < str.length(); i++) { result[i] = (byte) str.charAt(i); } result[str.length()] = 0; return result; }
[ "private", "static", "byte", "[", "]", "stringToByteArray", "(", "String", "str", ")", "{", "byte", "[", "]", "result", "=", "new", "byte", "[", "str", ".", "length", "(", ")", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<"...
Returns this java string as a null-terminated byte array
[ "Returns", "this", "java", "string", "as", "a", "null", "-", "terminated", "byte", "array" ]
5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437
https://github.com/sarxos/win-registry/blob/5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437/src/main/java/com/github/sarxos/winreg/internal/WindowsPreferencesBuilder.java#L68-L75
train
sarxos/win-registry
src/main/java/com/github/sarxos/winreg/WindowsRegistry.java
WindowsRegistry.createKey
public void createKey(HKey hk, String key) throws RegistryException { int[] ret; try { ret = ReflectedMethods.createKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot create key " + key, e); } if (ret.length == 0) { throw new RegistryException("Cannot create key " + key + ". Zero return length"); } if (ret[1] != RC.SUCCESS) { throw new RegistryException("Cannot create key " + key + ". Return code is " + ret[1]); } }
java
public void createKey(HKey hk, String key) throws RegistryException { int[] ret; try { ret = ReflectedMethods.createKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot create key " + key, e); } if (ret.length == 0) { throw new RegistryException("Cannot create key " + key + ". Zero return length"); } if (ret[1] != RC.SUCCESS) { throw new RegistryException("Cannot create key " + key + ". Return code is " + ret[1]); } }
[ "public", "void", "createKey", "(", "HKey", "hk", ",", "String", "key", ")", "throws", "RegistryException", "{", "int", "[", "]", "ret", ";", "try", "{", "ret", "=", "ReflectedMethods", ".", "createKey", "(", "hk", ".", "root", "(", ")", ",", "hk", "...
Create key in registry. @param hk the HKEY @param key the key @throws RegistryException when something is not right
[ "Create", "key", "in", "registry", "." ]
5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437
https://github.com/sarxos/win-registry/blob/5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437/src/main/java/com/github/sarxos/winreg/WindowsRegistry.java#L132-L145
train
sarxos/win-registry
src/main/java/com/github/sarxos/winreg/WindowsRegistry.java
WindowsRegistry.deleteKey
public void deleteKey(HKey hk, String key) throws RegistryException { int rc = -1; try { rc = ReflectedMethods.deleteKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot delete key " + key, e); } if (rc != RC.SUCCESS) { throw new RegistryException("Cannot delete key " + key + ". Return code is " + rc); } }
java
public void deleteKey(HKey hk, String key) throws RegistryException { int rc = -1; try { rc = ReflectedMethods.deleteKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot delete key " + key, e); } if (rc != RC.SUCCESS) { throw new RegistryException("Cannot delete key " + key + ". Return code is " + rc); } }
[ "public", "void", "deleteKey", "(", "HKey", "hk", ",", "String", "key", ")", "throws", "RegistryException", "{", "int", "rc", "=", "-", "1", ";", "try", "{", "rc", "=", "ReflectedMethods", ".", "deleteKey", "(", "hk", ".", "root", "(", ")", ",", "hk"...
Delete given key from registry. @param hk the HKEY @param key the key to be deleted @throws RegistryException when something is not right
[ "Delete", "given", "key", "from", "registry", "." ]
5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437
https://github.com/sarxos/win-registry/blob/5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437/src/main/java/com/github/sarxos/winreg/WindowsRegistry.java#L171-L181
train
biezhi/webp-io
src/main/java/io/github/biezhi/webp/WebpIO.java
WebpIO.close
public void close() { File tmp = new File(webpTmpDir); if (tmp.exists() && tmp.isDirectory()) { File[] files = tmp.listFiles(); for (File file : Objects.requireNonNull(files)) { file.delete(); } tmp.delete(); } }
java
public void close() { File tmp = new File(webpTmpDir); if (tmp.exists() && tmp.isDirectory()) { File[] files = tmp.listFiles(); for (File file : Objects.requireNonNull(files)) { file.delete(); } tmp.delete(); } }
[ "public", "void", "close", "(", ")", "{", "File", "tmp", "=", "new", "File", "(", "webpTmpDir", ")", ";", "if", "(", "tmp", ".", "exists", "(", ")", "&&", "tmp", ".", "isDirectory", "(", ")", ")", "{", "File", "[", "]", "files", "=", "tmp", "."...
delete temp dir and commands
[ "delete", "temp", "dir", "and", "commands" ]
8eefe535087b3abccacff76de2b6e27bb7301bcc
https://github.com/biezhi/webp-io/blob/8eefe535087b3abccacff76de2b6e27bb7301bcc/src/main/java/io/github/biezhi/webp/WebpIO.java#L147-L156
train
biezhi/webp-io
src/main/java/io/github/biezhi/webp/WebpIO.java
WebpIO.getOsName
private String getOsName() { // windows if (OS_NAME.contains("win")) { boolean is64bit = (System.getenv("ProgramFiles(x86)") != null); return "windows_" + (is64bit ? "x86_64" : "x86"); } else if (OS_NAME.contains("mac")) { // mac osx return "mac_" + OS_ARCH; } else if (OS_NAME.contains("nix") || OS_NAME.contains("nux") || OS_NAME.indexOf("aix") > 0) { // unix return "amd64".equalsIgnoreCase(OS_ARCH) ? "linux_x86_64" : "linux_" + OS_ARCH; } else { throw new WebpIOException("Hi boy, Your OS is not support!!"); } }
java
private String getOsName() { // windows if (OS_NAME.contains("win")) { boolean is64bit = (System.getenv("ProgramFiles(x86)") != null); return "windows_" + (is64bit ? "x86_64" : "x86"); } else if (OS_NAME.contains("mac")) { // mac osx return "mac_" + OS_ARCH; } else if (OS_NAME.contains("nix") || OS_NAME.contains("nux") || OS_NAME.indexOf("aix") > 0) { // unix return "amd64".equalsIgnoreCase(OS_ARCH) ? "linux_x86_64" : "linux_" + OS_ARCH; } else { throw new WebpIOException("Hi boy, Your OS is not support!!"); } }
[ "private", "String", "getOsName", "(", ")", "{", "// windows", "if", "(", "OS_NAME", ".", "contains", "(", "\"win\"", ")", ")", "{", "boolean", "is64bit", "=", "(", "System", ".", "getenv", "(", "\"ProgramFiles(x86)\"", ")", "!=", "null", ")", ";", "retu...
get os name and arch @return
[ "get", "os", "name", "and", "arch" ]
8eefe535087b3abccacff76de2b6e27bb7301bcc
https://github.com/biezhi/webp-io/blob/8eefe535087b3abccacff76de2b6e27bb7301bcc/src/main/java/io/github/biezhi/webp/WebpIO.java#L176-L190
train
biezhi/webp-io
src/main/java/io/github/biezhi/webp/WebpIO.java
WebpIO.getExtensionByOs
private String getExtensionByOs(String os) { if (os == null || os.isEmpty()) return ""; else if (os.contains("win")) return ".exe"; return ""; }
java
private String getExtensionByOs(String os) { if (os == null || os.isEmpty()) return ""; else if (os.contains("win")) return ".exe"; return ""; }
[ "private", "String", "getExtensionByOs", "(", "String", "os", ")", "{", "if", "(", "os", "==", "null", "||", "os", ".", "isEmpty", "(", ")", ")", "return", "\"\"", ";", "else", "if", "(", "os", ".", "contains", "(", "\"win\"", ")", ")", "return", "...
Return the Os specific extension @param os: operating system name
[ "Return", "the", "Os", "specific", "extension" ]
8eefe535087b3abccacff76de2b6e27bb7301bcc
https://github.com/biezhi/webp-io/blob/8eefe535087b3abccacff76de2b6e27bb7301bcc/src/main/java/io/github/biezhi/webp/WebpIO.java#L197-L201
train
meltmedia/jgroups-aws
src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java
TagsUtils.getInstanceTags
public List<Tag> getInstanceTags() { final DescribeInstancesResult response = ec2 .describeInstances(new DescribeInstancesRequest() .withInstanceIds(Collections.singletonList(instanceIdentity.instanceId))); return response.getReservations().stream() .flatMap(reservation -> reservation.getInstances().stream()) .flatMap(instance -> instance.getTags().stream()) .collect(Collectors.toList()); }
java
public List<Tag> getInstanceTags() { final DescribeInstancesResult response = ec2 .describeInstances(new DescribeInstancesRequest() .withInstanceIds(Collections.singletonList(instanceIdentity.instanceId))); return response.getReservations().stream() .flatMap(reservation -> reservation.getInstances().stream()) .flatMap(instance -> instance.getTags().stream()) .collect(Collectors.toList()); }
[ "public", "List", "<", "Tag", ">", "getInstanceTags", "(", ")", "{", "final", "DescribeInstancesResult", "response", "=", "ec2", ".", "describeInstances", "(", "new", "DescribeInstancesRequest", "(", ")", ".", "withInstanceIds", "(", "Collections", ".", "singleton...
Returns all of the tags defined on the EC2 current instance instanceId. @return a list of the Tag objects that were found on the instance.
[ "Returns", "all", "of", "the", "tags", "defined", "on", "the", "EC2", "current", "instance", "instanceId", "." ]
b5e861a6809677e317dc624f981c983ed109fed6
https://github.com/meltmedia/jgroups-aws/blob/b5e861a6809677e317dc624f981c983ed109fed6/src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java#L43-L53
train
meltmedia/jgroups-aws
src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java
TagsUtils.validateTags
public TagsUtils validateTags() { final List<String> instanceTags = getInstanceTags().stream() .map(Tag::getKey) .collect(Collectors.toList()); final List<String> missingTags = getAwsTagNames().map(List::stream).orElse(Stream.empty()) .filter(configuredTag -> !instanceTags.contains(configuredTag)) .collect(Collectors.toList()); if(!missingTags.isEmpty()) { throw new IllegalStateException("expected instance tag(s) missing: " + missingTags.stream().collect(Collectors.joining(", "))); } return this; }
java
public TagsUtils validateTags() { final List<String> instanceTags = getInstanceTags().stream() .map(Tag::getKey) .collect(Collectors.toList()); final List<String> missingTags = getAwsTagNames().map(List::stream).orElse(Stream.empty()) .filter(configuredTag -> !instanceTags.contains(configuredTag)) .collect(Collectors.toList()); if(!missingTags.isEmpty()) { throw new IllegalStateException("expected instance tag(s) missing: " + missingTags.stream().collect(Collectors.joining(", "))); } return this; }
[ "public", "TagsUtils", "validateTags", "(", ")", "{", "final", "List", "<", "String", ">", "instanceTags", "=", "getInstanceTags", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "Tag", "::", "getKey", ")", ".", "collect", "(", "Collectors", ".", "...
Configured tags will be validated against the instance tags. If one or more tags are missing on the instance, an exception will be thrown. @throws IllegalStateException
[ "Configured", "tags", "will", "be", "validated", "against", "the", "instance", "tags", ".", "If", "one", "or", "more", "tags", "are", "missing", "on", "the", "instance", "an", "exception", "will", "be", "thrown", "." ]
b5e861a6809677e317dc624f981c983ed109fed6
https://github.com/meltmedia/jgroups-aws/blob/b5e861a6809677e317dc624f981c983ed109fed6/src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java#L61-L75
train
meltmedia/jgroups-aws
src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java
TagsUtils.parseTagNames
private static List<String> parseTagNames(String tagNames) { return Arrays.stream(tagNames.split("\\s*,\\s*")) .map(String::trim) .collect(Collectors.toList()); }
java
private static List<String> parseTagNames(String tagNames) { return Arrays.stream(tagNames.split("\\s*,\\s*")) .map(String::trim) .collect(Collectors.toList()); }
[ "private", "static", "List", "<", "String", ">", "parseTagNames", "(", "String", "tagNames", ")", "{", "return", "Arrays", ".", "stream", "(", "tagNames", ".", "split", "(", "\"\\\\s*,\\\\s*\"", ")", ")", ".", "map", "(", "String", "::", "trim", ")", "."...
Parses a comma separated list of tag names. @param tagNames a comma separated list of tag names. @return the list of tag names.
[ "Parses", "a", "comma", "separated", "list", "of", "tag", "names", "." ]
b5e861a6809677e317dc624f981c983ed109fed6
https://github.com/meltmedia/jgroups-aws/blob/b5e861a6809677e317dc624f981c983ed109fed6/src/main/java/com/meltmedia/jgroups/aws/TagsUtils.java#L83-L87
train
meltmedia/jgroups-aws
src/main/java/com/meltmedia/jgroups/aws/InstanceIdentity.java
InstanceIdentity.getIdentityDocument
private static String getIdentityDocument(final HttpClient client) throws IOException { try { final HttpGet getInstance = new HttpGet(); getInstance.setURI(INSTANCE_IDENTITY_URI); final HttpResponse response = client.execute(getInstance); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("failed to get instance identity, tried: " + INSTANCE_IDENTITY_URL + ", response: " + response.getStatusLine().getReasonPhrase()); } return EntityUtils.toString(response.getEntity()); } catch (Exception e) { throw new IOException("failed to get instance identity", e); } }
java
private static String getIdentityDocument(final HttpClient client) throws IOException { try { final HttpGet getInstance = new HttpGet(); getInstance.setURI(INSTANCE_IDENTITY_URI); final HttpResponse response = client.execute(getInstance); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("failed to get instance identity, tried: " + INSTANCE_IDENTITY_URL + ", response: " + response.getStatusLine().getReasonPhrase()); } return EntityUtils.toString(response.getEntity()); } catch (Exception e) { throw new IOException("failed to get instance identity", e); } }
[ "private", "static", "String", "getIdentityDocument", "(", "final", "HttpClient", "client", ")", "throws", "IOException", "{", "try", "{", "final", "HttpGet", "getInstance", "=", "new", "HttpGet", "(", ")", ";", "getInstance", ".", "setURI", "(", "INSTANCE_IDENT...
Gets the body of the content returned from a GET request to uri. @param client @return the body of the message returned from the GET request. @throws IOException if there is an error encountered while getting the content.
[ "Gets", "the", "body", "of", "the", "content", "returned", "from", "a", "GET", "request", "to", "uri", "." ]
b5e861a6809677e317dc624f981c983ed109fed6
https://github.com/meltmedia/jgroups-aws/blob/b5e861a6809677e317dc624f981c983ed109fed6/src/main/java/com/meltmedia/jgroups/aws/InstanceIdentity.java#L67-L79
train
meltmedia/jgroups-aws
src/main/java/com/meltmedia/jgroups/aws/EC2Factory.java
EC2Factory.setupAWSExceptionLogging
private static void setupAWSExceptionLogging(AmazonEC2 ec2) { boolean accessible = false; Field exceptionUnmarshallersField = null; try { exceptionUnmarshallersField = AmazonEC2Client.class.getDeclaredField("exceptionUnmarshallers"); accessible = exceptionUnmarshallersField.isAccessible(); exceptionUnmarshallersField.setAccessible(true); @SuppressWarnings("unchecked") final List<Unmarshaller<AmazonServiceException, Node>> exceptionUnmarshallers = (List<Unmarshaller<AmazonServiceException, Node>>) exceptionUnmarshallersField.get(ec2); exceptionUnmarshallers.add(0, new AWSFaultLogger()); ((AmazonEC2Client) ec2).addRequestHandler((RequestHandler) exceptionUnmarshallers.get(0)); } catch (Throwable t) { //I don't care about this. } finally { if (exceptionUnmarshallersField != null) { try { exceptionUnmarshallersField.setAccessible(accessible); } catch (SecurityException se) { //I don't care about this. } } } }
java
private static void setupAWSExceptionLogging(AmazonEC2 ec2) { boolean accessible = false; Field exceptionUnmarshallersField = null; try { exceptionUnmarshallersField = AmazonEC2Client.class.getDeclaredField("exceptionUnmarshallers"); accessible = exceptionUnmarshallersField.isAccessible(); exceptionUnmarshallersField.setAccessible(true); @SuppressWarnings("unchecked") final List<Unmarshaller<AmazonServiceException, Node>> exceptionUnmarshallers = (List<Unmarshaller<AmazonServiceException, Node>>) exceptionUnmarshallersField.get(ec2); exceptionUnmarshallers.add(0, new AWSFaultLogger()); ((AmazonEC2Client) ec2).addRequestHandler((RequestHandler) exceptionUnmarshallers.get(0)); } catch (Throwable t) { //I don't care about this. } finally { if (exceptionUnmarshallersField != null) { try { exceptionUnmarshallersField.setAccessible(accessible); } catch (SecurityException se) { //I don't care about this. } } } }
[ "private", "static", "void", "setupAWSExceptionLogging", "(", "AmazonEC2", "ec2", ")", "{", "boolean", "accessible", "=", "false", ";", "Field", "exceptionUnmarshallersField", "=", "null", ";", "try", "{", "exceptionUnmarshallersField", "=", "AmazonEC2Client", ".", ...
Sets up the AmazonEC2Client to log soap faults from the AWS EC2 api server.
[ "Sets", "up", "the", "AmazonEC2Client", "to", "log", "soap", "faults", "from", "the", "AWS", "EC2", "api", "server", "." ]
b5e861a6809677e317dc624f981c983ed109fed6
https://github.com/meltmedia/jgroups-aws/blob/b5e861a6809677e317dc624f981c983ed109fed6/src/main/java/com/meltmedia/jgroups/aws/EC2Factory.java#L66-L87
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/banking/KidnummerValidator.java
KidnummerValidator.isValid
public static boolean isValid(String kidnummer) { try { KidnummerValidator.getKidnummer(kidnummer); return true; } catch (IllegalArgumentException e) { return false; } }
java
public static boolean isValid(String kidnummer) { try { KidnummerValidator.getKidnummer(kidnummer); return true; } catch (IllegalArgumentException e) { return false; } }
[ "public", "static", "boolean", "isValid", "(", "String", "kidnummer", ")", "{", "try", "{", "KidnummerValidator", ".", "getKidnummer", "(", "kidnummer", ")", ";", "return", "true", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "return", ...
Return true if the provided String is a valid KID-nummmer. @param kidnummer A String containing a Kidnummer @return true or false
[ "Return", "true", "if", "the", "provided", "String", "is", "a", "valid", "KID", "-", "nummmer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/KidnummerValidator.java#L25-L32
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/banking/KidnummerValidator.java
KidnummerValidator.getKidnummer
public static Kidnummer getKidnummer(String kidnummer) throws IllegalArgumentException { validateSyntax(kidnummer); validateChecksum(kidnummer); return new Kidnummer(kidnummer); }
java
public static Kidnummer getKidnummer(String kidnummer) throws IllegalArgumentException { validateSyntax(kidnummer); validateChecksum(kidnummer); return new Kidnummer(kidnummer); }
[ "public", "static", "Kidnummer", "getKidnummer", "(", "String", "kidnummer", ")", "throws", "IllegalArgumentException", "{", "validateSyntax", "(", "kidnummer", ")", ";", "validateChecksum", "(", "kidnummer", ")", ";", "return", "new", "Kidnummer", "(", "kidnummer",...
Returns an object that represents a Kidnummer. @param kidnummer A String containing a Kidnummer @return A Kidnummer instance @throws IllegalArgumentException thrown if String contains an invalid Kidnummer
[ "Returns", "an", "object", "that", "represents", "a", "Kidnummer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/KidnummerValidator.java#L41-L45
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerCalculator.java
OrganisasjonsnummerCalculator.getOrganisasjonsnummerList
public static List<Organisasjonsnummer> getOrganisasjonsnummerList(int length) { List<Organisasjonsnummer> result = new ArrayList<Organisasjonsnummer>(); int numAddedToList = 0; while (numAddedToList < length) { StringBuilder orgnrBuffer = new StringBuilder(LENGTH); for (int i = 0; i < LENGTH; i++) { orgnrBuffer.append((int) (Math.random() * 10)); } Organisasjonsnummer orgNr; try { orgNr = OrganisasjonsnummerValidator.getAndForceValidOrganisasjonsnummer(orgnrBuffer.toString()); } catch (IllegalArgumentException iae) { // this number has no valid checksum continue; } result.add(orgNr); numAddedToList++; } return result; }
java
public static List<Organisasjonsnummer> getOrganisasjonsnummerList(int length) { List<Organisasjonsnummer> result = new ArrayList<Organisasjonsnummer>(); int numAddedToList = 0; while (numAddedToList < length) { StringBuilder orgnrBuffer = new StringBuilder(LENGTH); for (int i = 0; i < LENGTH; i++) { orgnrBuffer.append((int) (Math.random() * 10)); } Organisasjonsnummer orgNr; try { orgNr = OrganisasjonsnummerValidator.getAndForceValidOrganisasjonsnummer(orgnrBuffer.toString()); } catch (IllegalArgumentException iae) { // this number has no valid checksum continue; } result.add(orgNr); numAddedToList++; } return result; }
[ "public", "static", "List", "<", "Organisasjonsnummer", ">", "getOrganisasjonsnummerList", "(", "int", "length", ")", "{", "List", "<", "Organisasjonsnummer", ">", "result", "=", "new", "ArrayList", "<", "Organisasjonsnummer", ">", "(", ")", ";", "int", "numAdde...
Returns a List with completely random but syntactically valid Organisasjonsnummer instances. @param length Specifies the number of Organisasjonsnummer instances to create in the returned List @return A List with random valid Organisasjonsnummer instances
[ "Returns", "a", "List", "with", "completely", "random", "but", "syntactically", "valid", "Organisasjonsnummer", "instances", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerCalculator.java#L27-L46
train
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/WorkflowDemo.java
WorkflowDemo.main
public static void main(String[] args) throws Exception { // Instantiate the CLAVIN GeoParser GeoParser parser = GeoParserFactory.getDefault("./IndexDirectory"); // Unstructured text file about Somalia to be geoparsed File inputFile = new File("src/test/resources/sample-docs/Somalia-doc.txt"); // Grab the contents of the text file as a String String inputString = TextUtils.fileToString(inputFile); // Parse location names in the text into geographic entities List<ResolvedLocation> resolvedLocations = parser.parse(inputString); // Display the ResolvedLocations found for the location names for (ResolvedLocation resolvedLocation : resolvedLocations) System.out.println(resolvedLocation); // And we're done... System.out.println("\n\"That's all folks!\""); }
java
public static void main(String[] args) throws Exception { // Instantiate the CLAVIN GeoParser GeoParser parser = GeoParserFactory.getDefault("./IndexDirectory"); // Unstructured text file about Somalia to be geoparsed File inputFile = new File("src/test/resources/sample-docs/Somalia-doc.txt"); // Grab the contents of the text file as a String String inputString = TextUtils.fileToString(inputFile); // Parse location names in the text into geographic entities List<ResolvedLocation> resolvedLocations = parser.parse(inputString); // Display the ResolvedLocations found for the location names for (ResolvedLocation resolvedLocation : resolvedLocations) System.out.println(resolvedLocation); // And we're done... System.out.println("\n\"That's all folks!\""); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "// Instantiate the CLAVIN GeoParser", "GeoParser", "parser", "=", "GeoParserFactory", ".", "getDefault", "(", "\"./IndexDirectory\"", ")", ";", "// Unstructured text...
Run this after installing & configuring CLAVIN to get a sense of how to use it. @param args not used @throws Exception
[ "Run", "this", "after", "installing", "&", "configuring", "CLAVIN", "to", "get", "a", "sense", "of", "how", "to", "use", "it", "." ]
f73c741f33a01b91aa5b06e71860bc354ef3010d
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/WorkflowDemo.java#L50-L70
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerValidator.java
FodselsnummerValidator.getFodselsnummer
public static no.bekk.bekkopen.person.Fodselsnummer getFodselsnummer(String fodselsnummer) throws IllegalArgumentException { validateSyntax(fodselsnummer); validateIndividnummer(fodselsnummer); validateDate(fodselsnummer); validateChecksums(fodselsnummer); return new no.bekk.bekkopen.person.Fodselsnummer(fodselsnummer); }
java
public static no.bekk.bekkopen.person.Fodselsnummer getFodselsnummer(String fodselsnummer) throws IllegalArgumentException { validateSyntax(fodselsnummer); validateIndividnummer(fodselsnummer); validateDate(fodselsnummer); validateChecksums(fodselsnummer); return new no.bekk.bekkopen.person.Fodselsnummer(fodselsnummer); }
[ "public", "static", "no", ".", "bekk", ".", "bekkopen", ".", "person", ".", "Fodselsnummer", "getFodselsnummer", "(", "String", "fodselsnummer", ")", "throws", "IllegalArgumentException", "{", "validateSyntax", "(", "fodselsnummer", ")", ";", "validateIndividnummer", ...
Returns an object that represents a Fodselsnummer. @param fodselsnummer A String containing a Fodselsnummer @return A Fodselsnummer instance @throws IllegalArgumentException thrown if String contains an invalid Fodselsnummer
[ "Returns", "an", "object", "that", "represents", "a", "Fodselsnummer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerValidator.java#L40-L46
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerValidator.java
FodselsnummerValidator.isValid
public static boolean isValid(String fodselsnummer) { try { FodselsnummerValidator.getFodselsnummer(fodselsnummer); return true; } catch (IllegalArgumentException e) { return false; } }
java
public static boolean isValid(String fodselsnummer) { try { FodselsnummerValidator.getFodselsnummer(fodselsnummer); return true; } catch (IllegalArgumentException e) { return false; } }
[ "public", "static", "boolean", "isValid", "(", "String", "fodselsnummer", ")", "{", "try", "{", "FodselsnummerValidator", ".", "getFodselsnummer", "(", "fodselsnummer", ")", ";", "return", "true", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{"...
Return true if the provided String is a valid Fodselsnummer. @param fodselsnummer A String containing a Fodselsnummer @return true or false
[ "Return", "true", "if", "the", "provided", "String", "is", "a", "valid", "Fodselsnummer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerValidator.java#L55-L62
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java
OrganisasjonsnummerValidator.isValid
public static boolean isValid(String organisasjonsnummer) { try { OrganisasjonsnummerValidator.getOrganisasjonsnummer(organisasjonsnummer); return true; } catch (IllegalArgumentException e) { return false; } }
java
public static boolean isValid(String organisasjonsnummer) { try { OrganisasjonsnummerValidator.getOrganisasjonsnummer(organisasjonsnummer); return true; } catch (IllegalArgumentException e) { return false; } }
[ "public", "static", "boolean", "isValid", "(", "String", "organisasjonsnummer", ")", "{", "try", "{", "OrganisasjonsnummerValidator", ".", "getOrganisasjonsnummer", "(", "organisasjonsnummer", ")", ";", "return", "true", ";", "}", "catch", "(", "IllegalArgumentExcepti...
Return true if the provided String is a valid Organisasjonsnummer. @param organisasjonsnummer A String containing a Organisasjonsnummer @return true or false
[ "Return", "true", "if", "the", "provided", "String", "is", "a", "valid", "Organisasjonsnummer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java#L28-L35
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java
OrganisasjonsnummerValidator.getOrganisasjonsnummer
public static Organisasjonsnummer getOrganisasjonsnummer(String organisasjonsnummer) throws IllegalArgumentException { validateSyntax(organisasjonsnummer); validateChecksum(organisasjonsnummer); return new Organisasjonsnummer(organisasjonsnummer); }
java
public static Organisasjonsnummer getOrganisasjonsnummer(String organisasjonsnummer) throws IllegalArgumentException { validateSyntax(organisasjonsnummer); validateChecksum(organisasjonsnummer); return new Organisasjonsnummer(organisasjonsnummer); }
[ "public", "static", "Organisasjonsnummer", "getOrganisasjonsnummer", "(", "String", "organisasjonsnummer", ")", "throws", "IllegalArgumentException", "{", "validateSyntax", "(", "organisasjonsnummer", ")", ";", "validateChecksum", "(", "organisasjonsnummer", ")", ";", "retu...
Returns an object that represents an Organisasjonsnummer. @param organisasjonsnummer A String containing an Organisasjonsnummer @return An Organisasjonsnummer instance @throws IllegalArgumentException thrown if String contains an invalid Organisasjonsnummer
[ "Returns", "an", "object", "that", "represents", "an", "Organisasjonsnummer", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java#L46-L51
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java
OrganisasjonsnummerValidator.getAndForceValidOrganisasjonsnummer
public static Organisasjonsnummer getAndForceValidOrganisasjonsnummer(String organisasjonsnummer) { validateSyntax(organisasjonsnummer); try { validateChecksum(organisasjonsnummer); } catch (IllegalArgumentException iae) { Organisasjonsnummer onr = new Organisasjonsnummer(organisasjonsnummer); int checksum = calculateMod11CheckSum(getMod11Weights(onr), onr); organisasjonsnummer = organisasjonsnummer.substring(0, LENGTH - 1) + checksum; } return new Organisasjonsnummer(organisasjonsnummer); }
java
public static Organisasjonsnummer getAndForceValidOrganisasjonsnummer(String organisasjonsnummer) { validateSyntax(organisasjonsnummer); try { validateChecksum(organisasjonsnummer); } catch (IllegalArgumentException iae) { Organisasjonsnummer onr = new Organisasjonsnummer(organisasjonsnummer); int checksum = calculateMod11CheckSum(getMod11Weights(onr), onr); organisasjonsnummer = organisasjonsnummer.substring(0, LENGTH - 1) + checksum; } return new Organisasjonsnummer(organisasjonsnummer); }
[ "public", "static", "Organisasjonsnummer", "getAndForceValidOrganisasjonsnummer", "(", "String", "organisasjonsnummer", ")", "{", "validateSyntax", "(", "organisasjonsnummer", ")", ";", "try", "{", "validateChecksum", "(", "organisasjonsnummer", ")", ";", "}", "catch", ...
Returns an object that represents a Organisasjonsnummer. The checksum of the supplied organisasjonsnummer is changed to a valid checksum if the original organisasjonsnummer has an invalid checksum. @param organisasjonsnummer A String containing a Organisasjonsnummer @return A Organisasjonsnummer instance @throws IllegalArgumentException thrown if String contains an invalid Organisasjonsnummer, ie. a number which for one cannot calculate a valid checksum.
[ "Returns", "an", "object", "that", "represents", "a", "Organisasjonsnummer", ".", "The", "checksum", "of", "the", "supplied", "organisasjonsnummer", "is", "changed", "to", "a", "valid", "checksum", "if", "the", "original", "organisasjonsnummer", "has", "an", "inva...
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java#L65-L75
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.getHolidays
public static Date[] getHolidays(int year) { Set<Date> days = getHolidaySet(year); Date[] dates = days.toArray(new Date[days.size()]); Arrays.sort(dates); return dates; }
java
public static Date[] getHolidays(int year) { Set<Date> days = getHolidaySet(year); Date[] dates = days.toArray(new Date[days.size()]); Arrays.sort(dates); return dates; }
[ "public", "static", "Date", "[", "]", "getHolidays", "(", "int", "year", ")", "{", "Set", "<", "Date", ">", "days", "=", "getHolidaySet", "(", "year", ")", ";", "Date", "[", "]", "dates", "=", "days", ".", "toArray", "(", "new", "Date", "[", "days"...
Return a sorted array of holidays for a given year. @param year The year to get holidays for. @return The array of holidays, sorted by date.
[ "Return", "a", "sorted", "array", "of", "holidays", "for", "a", "given", "year", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L82-L87
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.getHolidaySet
private static Set<Date> getHolidaySet(int year) { if (holidays == null) { holidays = new HashMap<Integer, Set<Date>>(); } if (!holidays.containsKey(year)) { Set<Date> yearSet = new HashSet<Date>(); // Add set holidays. yearSet.add(getDate(1, Calendar.JANUARY, year)); yearSet.add(getDate(1, Calendar.MAY, year)); yearSet.add(getDate(17, Calendar.MAY, year)); yearSet.add(getDate(25, Calendar.DECEMBER, year)); yearSet.add(getDate(26, Calendar.DECEMBER, year)); // Add movable holidays - based on easter day. Calendar easterDay = dateToCalendar(getEasterDay(year)); // Sunday before easter. yearSet.add(rollGetDate(easterDay, -7)); // Thurday before easter. yearSet.add(rollGetDate(easterDay, -3)); // Friday before easter. yearSet.add(rollGetDate(easterDay, -2)); // Easter day. yearSet.add(easterDay.getTime()); // Second easter day. yearSet.add(rollGetDate(easterDay, 1)); // "Kristi himmelfart" day. yearSet.add(rollGetDate(easterDay, 39)); // "Pinse" day. yearSet.add(rollGetDate(easterDay, 49)); // Second "Pinse" day. yearSet.add(rollGetDate(easterDay, 50)); holidays.put(year, yearSet); } return holidays.get(year); }
java
private static Set<Date> getHolidaySet(int year) { if (holidays == null) { holidays = new HashMap<Integer, Set<Date>>(); } if (!holidays.containsKey(year)) { Set<Date> yearSet = new HashSet<Date>(); // Add set holidays. yearSet.add(getDate(1, Calendar.JANUARY, year)); yearSet.add(getDate(1, Calendar.MAY, year)); yearSet.add(getDate(17, Calendar.MAY, year)); yearSet.add(getDate(25, Calendar.DECEMBER, year)); yearSet.add(getDate(26, Calendar.DECEMBER, year)); // Add movable holidays - based on easter day. Calendar easterDay = dateToCalendar(getEasterDay(year)); // Sunday before easter. yearSet.add(rollGetDate(easterDay, -7)); // Thurday before easter. yearSet.add(rollGetDate(easterDay, -3)); // Friday before easter. yearSet.add(rollGetDate(easterDay, -2)); // Easter day. yearSet.add(easterDay.getTime()); // Second easter day. yearSet.add(rollGetDate(easterDay, 1)); // "Kristi himmelfart" day. yearSet.add(rollGetDate(easterDay, 39)); // "Pinse" day. yearSet.add(rollGetDate(easterDay, 49)); // Second "Pinse" day. yearSet.add(rollGetDate(easterDay, 50)); holidays.put(year, yearSet); } return holidays.get(year); }
[ "private", "static", "Set", "<", "Date", ">", "getHolidaySet", "(", "int", "year", ")", "{", "if", "(", "holidays", "==", "null", ")", "{", "holidays", "=", "new", "HashMap", "<", "Integer", ",", "Set", "<", "Date", ">", ">", "(", ")", ";", "}", ...
Get a set of holidays for a given year. @param year The year to get holidays for. @return The set of dates.
[ "Get", "a", "set", "of", "holidays", "for", "a", "given", "year", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L96-L140
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.isWorkingDay
private static boolean isWorkingDay(Calendar cal) { return cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && !isHoliday(cal); }
java
private static boolean isWorkingDay(Calendar cal) { return cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && !isHoliday(cal); }
[ "private", "static", "boolean", "isWorkingDay", "(", "Calendar", "cal", ")", "{", "return", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", "!=", "Calendar", ".", "SATURDAY", "&&", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", ...
Will check if the given date is a working day. That is check if the given date is a weekend day or a national holiday. @param cal The Calendar object representing the date. @return true if the given date is a working day, false otherwise.
[ "Will", "check", "if", "the", "given", "date", "is", "a", "working", "day", ".", "That", "is", "check", "if", "the", "given", "date", "is", "a", "weekend", "day", "or", "a", "national", "holiday", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L150-L153
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.isHoliday
private static boolean isHoliday(Calendar cal) { int year = cal.get(Calendar.YEAR); Set<?> yearSet = getHolidaySet(year); for (Object aYearSet : yearSet) { Date date = (Date) aYearSet; if (checkDate(cal, dateToCalendar(date))) { return true; } } return false; }
java
private static boolean isHoliday(Calendar cal) { int year = cal.get(Calendar.YEAR); Set<?> yearSet = getHolidaySet(year); for (Object aYearSet : yearSet) { Date date = (Date) aYearSet; if (checkDate(cal, dateToCalendar(date))) { return true; } } return false; }
[ "private", "static", "boolean", "isHoliday", "(", "Calendar", "cal", ")", "{", "int", "year", "=", "cal", ".", "get", "(", "Calendar", ".", "YEAR", ")", ";", "Set", "<", "?", ">", "yearSet", "=", "getHolidaySet", "(", "year", ")", ";", "for", "(", ...
Check if given Calendar object represents a holiday. @param cal The Calendar to check. @return true if holiday, false otherwise.
[ "Check", "if", "given", "Calendar", "object", "represents", "a", "holiday", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L162-L172
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.checkDate
private static boolean checkDate(Calendar cal, Calendar other) { return checkDate(cal, other.get(Calendar.DATE), other.get(Calendar.MONTH)); }
java
private static boolean checkDate(Calendar cal, Calendar other) { return checkDate(cal, other.get(Calendar.DATE), other.get(Calendar.MONTH)); }
[ "private", "static", "boolean", "checkDate", "(", "Calendar", "cal", ",", "Calendar", "other", ")", "{", "return", "checkDate", "(", "cal", ",", "other", ".", "get", "(", "Calendar", ".", "DATE", ")", ",", "other", ".", "get", "(", "Calendar", ".", "MO...
Check if the given dates match on day and month. @param cal The Calendar representing the first date. @param other The Calendar representing the second date. @return true if they match, false otherwise.
[ "Check", "if", "the", "given", "dates", "match", "on", "day", "and", "month", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L216-L218
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.checkDate
private static boolean checkDate(Calendar cal, int date, int month) { return cal.get(Calendar.DATE) == date && cal.get(Calendar.MONTH) == month; }
java
private static boolean checkDate(Calendar cal, int date, int month) { return cal.get(Calendar.DATE) == date && cal.get(Calendar.MONTH) == month; }
[ "private", "static", "boolean", "checkDate", "(", "Calendar", "cal", ",", "int", "date", ",", "int", "month", ")", "{", "return", "cal", ".", "get", "(", "Calendar", ".", "DATE", ")", "==", "date", "&&", "cal", ".", "get", "(", "Calendar", ".", "MONT...
Check if the given date represents the given date and month. @param cal The Calendar object representing date to check. @param date The date. @param month The month. @return true if they match, false otherwise.
[ "Check", "if", "the", "given", "date", "represents", "the", "given", "date", "and", "month", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L231-L233
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.dateToCalendar
private static Calendar dateToCalendar(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; }
java
private static Calendar dateToCalendar(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; }
[ "private", "static", "Calendar", "dateToCalendar", "(", "Date", "date", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "setTime", "(", "date", ")", ";", "return", "cal", ";", "}" ]
Convert the given Date object to a Calendar instance. @param date The Date object. @return The Calendar instance.
[ "Convert", "the", "given", "Date", "object", "to", "a", "Calendar", "instance", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L242-L246
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.rollGetDate
private static Date rollGetDate(Calendar calendar, int days) { Calendar easterSunday = (Calendar) calendar.clone(); easterSunday.add(Calendar.DATE, days); return easterSunday.getTime(); }
java
private static Date rollGetDate(Calendar calendar, int days) { Calendar easterSunday = (Calendar) calendar.clone(); easterSunday.add(Calendar.DATE, days); return easterSunday.getTime(); }
[ "private", "static", "Date", "rollGetDate", "(", "Calendar", "calendar", ",", "int", "days", ")", "{", "Calendar", "easterSunday", "=", "(", "Calendar", ")", "calendar", ".", "clone", "(", ")", ";", "easterSunday", ".", "add", "(", "Calendar", ".", "DATE",...
Add the given number of days to the calendar and convert to Date. @param calendar The calendar to add to. @param days The number of days to add. @return The date object given by the modified calendar.
[ "Add", "the", "given", "number", "of", "days", "to", "the", "calendar", "and", "convert", "to", "Date", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L257-L261
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.getDate
private static Date getDate(int day, int month, int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DATE, day); return cal.getTime(); }
java
private static Date getDate(int day, int month, int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DATE, day); return cal.getTime(); }
[ "private", "static", "Date", "getDate", "(", "int", "day", ",", "int", "month", ",", "int", "year", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "YEAR", ",", "year", ")", ...
Get the date for the given values. @param day The day. @param month The month. @param year The year. @return The date represented by the given values.
[ "Get", "the", "date", "for", "the", "given", "values", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L274-L280
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/banking/Kontonummer.java
Kontonummer.getGroupedValue
public String getGroupedValue() { StringBuilder sb = new StringBuilder(); sb.append(getRegisternummer()).append(Constants.DOT); sb.append(getAccountType()).append(Constants.DOT); sb.append(getPartAfterAccountType()); return sb.toString(); }
java
public String getGroupedValue() { StringBuilder sb = new StringBuilder(); sb.append(getRegisternummer()).append(Constants.DOT); sb.append(getAccountType()).append(Constants.DOT); sb.append(getPartAfterAccountType()); return sb.toString(); }
[ "public", "String", "getGroupedValue", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "getRegisternummer", "(", ")", ")", ".", "append", "(", "Constants", ".", "DOT", ")", ";", "sb", ".", "ap...
Returns the Kontonummer as a String, formatted with '.''s separating the Registernummer, AccountType and end part. @return The formatted Kontonummer
[ "Returns", "the", "Kontonummer", "as", "a", "String", "formatted", "with", ".", "s", "separating", "the", "Registernummer", "AccountType", "and", "end", "part", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/Kontonummer.java#L52-L58
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java
FodselsnummerCalculator.getFodselsnummerForDateAndGender
public static List<Fodselsnummer> getFodselsnummerForDateAndGender(Date date, KJONN kjonn) { List<Fodselsnummer> result = getManyFodselsnummerForDate(date); splitByGender(kjonn, result); return result; }
java
public static List<Fodselsnummer> getFodselsnummerForDateAndGender(Date date, KJONN kjonn) { List<Fodselsnummer> result = getManyFodselsnummerForDate(date); splitByGender(kjonn, result); return result; }
[ "public", "static", "List", "<", "Fodselsnummer", ">", "getFodselsnummerForDateAndGender", "(", "Date", "date", ",", "KJONN", "kjonn", ")", "{", "List", "<", "Fodselsnummer", ">", "result", "=", "getManyFodselsnummerForDate", "(", "date", ")", ";", "splitByGender"...
Returns a List with valid Fodselsnummer instances for a given Date and gender.
[ "Returns", "a", "List", "with", "valid", "Fodselsnummer", "instances", "for", "a", "given", "Date", "and", "gender", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java#L19-L23
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java
FodselsnummerCalculator.getFodselsnummerForDate
public static Fodselsnummer getFodselsnummerForDate(Date date){ List<Fodselsnummer> fodselsnummerList = getManyFodselsnummerForDate(date); Collections.shuffle(fodselsnummerList); return fodselsnummerList.get(0); }
java
public static Fodselsnummer getFodselsnummerForDate(Date date){ List<Fodselsnummer> fodselsnummerList = getManyFodselsnummerForDate(date); Collections.shuffle(fodselsnummerList); return fodselsnummerList.get(0); }
[ "public", "static", "Fodselsnummer", "getFodselsnummerForDate", "(", "Date", "date", ")", "{", "List", "<", "Fodselsnummer", ">", "fodselsnummerList", "=", "getManyFodselsnummerForDate", "(", "date", ")", ";", "Collections", ".", "shuffle", "(", "fodselsnummerList", ...
Return one random valid fodselsnummer on a given date
[ "Return", "one", "random", "valid", "fodselsnummer", "on", "a", "given", "date" ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java#L28-L32
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java
FodselsnummerCalculator.getManyDNumberFodselsnummerForDate
public static List<Fodselsnummer> getManyDNumberFodselsnummerForDate(Date date) { if (date == null) { throw new IllegalArgumentException(); } DateFormat df = new SimpleDateFormat("ddMMyy"); String centuryString = getCentury(date); String dateString = df.format(date); dateString = new StringBuilder() .append(Character.toChars(dateString.charAt(0) + 4)[0]) .append(dateString.substring(1)) .toString(); return generateFodselsnummerForDate(dateString, centuryString); }
java
public static List<Fodselsnummer> getManyDNumberFodselsnummerForDate(Date date) { if (date == null) { throw new IllegalArgumentException(); } DateFormat df = new SimpleDateFormat("ddMMyy"); String centuryString = getCentury(date); String dateString = df.format(date); dateString = new StringBuilder() .append(Character.toChars(dateString.charAt(0) + 4)[0]) .append(dateString.substring(1)) .toString(); return generateFodselsnummerForDate(dateString, centuryString); }
[ "public", "static", "List", "<", "Fodselsnummer", ">", "getManyDNumberFodselsnummerForDate", "(", "Date", "date", ")", "{", "if", "(", "date", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "DateFormat", "df", "=", "n...
Returns a List with with VALID DNumber Fodselsnummer instances for a given Date. @param date The Date instance @return A List with Fodelsnummer instances
[ "Returns", "a", "List", "with", "with", "VALID", "DNumber", "Fodselsnummer", "instances", "for", "a", "given", "Date", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java#L41-L53
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java
FodselsnummerCalculator.getManyFodselsnummerForDate
public static List<Fodselsnummer> getManyFodselsnummerForDate(Date date) { if (date == null) { throw new IllegalArgumentException(); } DateFormat df = new SimpleDateFormat("ddMMyy"); String centuryString = getCentury(date); String dateString = df.format(date); return generateFodselsnummerForDate(dateString, centuryString); }
java
public static List<Fodselsnummer> getManyFodselsnummerForDate(Date date) { if (date == null) { throw new IllegalArgumentException(); } DateFormat df = new SimpleDateFormat("ddMMyy"); String centuryString = getCentury(date); String dateString = df.format(date); return generateFodselsnummerForDate(dateString, centuryString); }
[ "public", "static", "List", "<", "Fodselsnummer", ">", "getManyFodselsnummerForDate", "(", "Date", "date", ")", "{", "if", "(", "date", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "DateFormat", "df", "=", "new", ...
Returns a List with with VALID Fodselsnummer instances for a given Date. @param date The Date instance @return A List with Fodelsnummer instances
[ "Returns", "a", "List", "with", "with", "VALID", "Fodselsnummer", "instances", "for", "a", "given", "Date", "." ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/person/FodselsnummerCalculator.java#L62-L70
train
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/GeoParserFactory.java
GeoParserFactory.getDefault
public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow) throws ClavinException { return getDefault(pathToLuceneIndex, maxHitDepth, maxContentWindow, false); }
java
public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow) throws ClavinException { return getDefault(pathToLuceneIndex, maxHitDepth, maxContentWindow, false); }
[ "public", "static", "GeoParser", "getDefault", "(", "String", "pathToLuceneIndex", ",", "int", "maxHitDepth", ",", "int", "maxContentWindow", ")", "throws", "ClavinException", "{", "return", "getDefault", "(", "pathToLuceneIndex", ",", "maxHitDepth", ",", "maxContentW...
Get a GeoParser with defined values for maxHitDepth and maxContentWindow. @param pathToLuceneIndex Path to the local Lucene index. @param maxHitDepth Number of candidate matches to consider @param maxContentWindow How much context to consider when resolving @return GeoParser @throws ClavinException If the index cannot be created.
[ "Get", "a", "GeoParser", "with", "defined", "values", "for", "maxHitDepth", "and", "maxContentWindow", "." ]
f73c741f33a01b91aa5b06e71860bc354ef3010d
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParserFactory.java#L79-L81
train
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/GeoParserFactory.java
GeoParserFactory.getDefault
public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow, boolean fuzzy) throws ClavinException { try { // instantiate default LocationExtractor LocationExtractor extractor = new ApacheExtractor(); return getDefault(pathToLuceneIndex, extractor, maxHitDepth, maxContentWindow, fuzzy); } catch (IOException ioe) { throw new ClavinException("Error creating ApacheExtractor", ioe); } }
java
public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow, boolean fuzzy) throws ClavinException { try { // instantiate default LocationExtractor LocationExtractor extractor = new ApacheExtractor(); return getDefault(pathToLuceneIndex, extractor, maxHitDepth, maxContentWindow, fuzzy); } catch (IOException ioe) { throw new ClavinException("Error creating ApacheExtractor", ioe); } }
[ "public", "static", "GeoParser", "getDefault", "(", "String", "pathToLuceneIndex", ",", "int", "maxHitDepth", ",", "int", "maxContentWindow", ",", "boolean", "fuzzy", ")", "throws", "ClavinException", "{", "try", "{", "// instantiate default LocationExtractor", "Locatio...
Get a GeoParser with defined values for maxHitDepth and maxContentWindow, and fuzzy matching explicitly turned on or off. @param pathToLuceneIndex Path to the local Lucene index. @param maxHitDepth Number of candidate matches to consider @param maxContentWindow How much context to consider when resolving @param fuzzy Should fuzzy matching be used? @return GeoParser @throws ClavinException If the index cannot be created.
[ "Get", "a", "GeoParser", "with", "defined", "values", "for", "maxHitDepth", "and", "maxContentWindow", "and", "fuzzy", "matching", "explicitly", "turned", "on", "or", "off", "." ]
f73c741f33a01b91aa5b06e71860bc354ef3010d
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParserFactory.java#L94-L103
train
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/GeoParserFactory.java
GeoParserFactory.getDefault
public static GeoParser getDefault(String pathToLuceneIndex, LocationExtractor extractor, int maxHitDepth, int maxContentWindow, boolean fuzzy) throws ClavinException { // instantiate new LuceneGazetteer Gazetteer gazetteer = new LuceneGazetteer(new File(pathToLuceneIndex)); return new GeoParser(extractor, gazetteer, maxHitDepth, maxContentWindow, fuzzy); }
java
public static GeoParser getDefault(String pathToLuceneIndex, LocationExtractor extractor, int maxHitDepth, int maxContentWindow, boolean fuzzy) throws ClavinException { // instantiate new LuceneGazetteer Gazetteer gazetteer = new LuceneGazetteer(new File(pathToLuceneIndex)); return new GeoParser(extractor, gazetteer, maxHitDepth, maxContentWindow, fuzzy); }
[ "public", "static", "GeoParser", "getDefault", "(", "String", "pathToLuceneIndex", ",", "LocationExtractor", "extractor", ",", "int", "maxHitDepth", ",", "int", "maxContentWindow", ",", "boolean", "fuzzy", ")", "throws", "ClavinException", "{", "// instantiate new Lucen...
Get a GeoParser with defined values for maxHitDepth and maxContentWindow, fuzzy matching explicitly turned on or off, and a specific LocationExtractor to use. @param pathToLuceneIndex Path to the local Lucene index. @param extractor A specific implementation of LocationExtractor to be used @param maxHitDepth Number of candidate matches to consider @param maxContentWindow How much context to consider when resolving @param fuzzy Should fuzzy matching be used? @return GeoParser @throws ClavinException If the index cannot be created.
[ "Get", "a", "GeoParser", "with", "defined", "values", "for", "maxHitDepth", "and", "maxContentWindow", "fuzzy", "matching", "explicitly", "turned", "on", "or", "off", "and", "a", "specific", "LocationExtractor", "to", "use", "." ]
f73c741f33a01b91aa5b06e71860bc354ef3010d
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParserFactory.java#L118-L123
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/banking/Kidnummer.java
Kidnummer.mod10Kid
public static Kidnummer mod10Kid(String baseNumber, int targetLength) { if (baseNumber.length() >= targetLength) throw new IllegalArgumentException("baseNumber too long"); String padded = String.format("%0" + (targetLength-1) + "d", new BigInteger(baseNumber)); Kidnummer k = new Kidnummer(padded + "0"); return KidnummerValidator.getKidnummer(padded + calculateMod10CheckSum(getMod10Weights(k), k)); }
java
public static Kidnummer mod10Kid(String baseNumber, int targetLength) { if (baseNumber.length() >= targetLength) throw new IllegalArgumentException("baseNumber too long"); String padded = String.format("%0" + (targetLength-1) + "d", new BigInteger(baseNumber)); Kidnummer k = new Kidnummer(padded + "0"); return KidnummerValidator.getKidnummer(padded + calculateMod10CheckSum(getMod10Weights(k), k)); }
[ "public", "static", "Kidnummer", "mod10Kid", "(", "String", "baseNumber", ",", "int", "targetLength", ")", "{", "if", "(", "baseNumber", ".", "length", "(", ")", ">=", "targetLength", ")", "throw", "new", "IllegalArgumentException", "(", "\"baseNumber too long\"",...
Create a valid KID numer of the wanted length, using MOD10. Input is padded with leading zeros to reach wanted target length @param baseNumber base number to calculate checksum digit for @param targetLength wanted length, 0-padded. Between 2-25 @return Kidnummer
[ "Create", "a", "valid", "KID", "numer", "of", "the", "wanted", "length", "using", "MOD10", ".", "Input", "is", "padded", "with", "leading", "zeros", "to", "reach", "wanted", "target", "length" ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/Kidnummer.java#L36-L42
train
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/banking/Kidnummer.java
Kidnummer.mod11Kid
public static Kidnummer mod11Kid(String baseNumber, int targetLength) { if (baseNumber.length() >= targetLength) throw new IllegalArgumentException("baseNumber too long"); String padded = String.format("%0" + (targetLength-1) + "d", new BigInteger(baseNumber)); Kidnummer k = new Kidnummer(padded + "0"); return KidnummerValidator.getKidnummer(padded + calculateMod11CheckSum(getMod11Weights(k), k)); }
java
public static Kidnummer mod11Kid(String baseNumber, int targetLength) { if (baseNumber.length() >= targetLength) throw new IllegalArgumentException("baseNumber too long"); String padded = String.format("%0" + (targetLength-1) + "d", new BigInteger(baseNumber)); Kidnummer k = new Kidnummer(padded + "0"); return KidnummerValidator.getKidnummer(padded + calculateMod11CheckSum(getMod11Weights(k), k)); }
[ "public", "static", "Kidnummer", "mod11Kid", "(", "String", "baseNumber", ",", "int", "targetLength", ")", "{", "if", "(", "baseNumber", ".", "length", "(", ")", ">=", "targetLength", ")", "throw", "new", "IllegalArgumentException", "(", "\"baseNumber too long\"",...
Create a valid KID numer of the wanted length, using MOD11. Input is padded with leading zeros to reach wanted target length @param baseNumber base number to calculate checksum digit for @param targetLength wanted length, 0-padded. Between 2-25 @return Kidnummer
[ "Create", "a", "valid", "KID", "numer", "of", "the", "wanted", "length", "using", "MOD11", ".", "Input", "is", "padded", "with", "leading", "zeros", "to", "reach", "wanted", "target", "length" ]
5a576696390cecaac111fa97fde581e0c1afb9b8
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/banking/Kidnummer.java#L60-L66
train