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
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/UnsafeUtil.java
UnsafeUtil.newDirectByteBuffer
public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) { dbbCC.setAccessible(true); Object b = null; try { b = dbbCC.newInstance(new Long(addr), new Integer(size), att); return ByteBuffer.class.cast(b); } catch(Exception e) { throw new IllegalStateException(String.format("Failed to create DirectByteBuffer: %s", e.getMessage())); } }
java
public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) { dbbCC.setAccessible(true); Object b = null; try { b = dbbCC.newInstance(new Long(addr), new Integer(size), att); return ByteBuffer.class.cast(b); } catch(Exception e) { throw new IllegalStateException(String.format("Failed to create DirectByteBuffer: %s", e.getMessage())); } }
[ "public", "static", "ByteBuffer", "newDirectByteBuffer", "(", "long", "addr", ",", "int", "size", ",", "Object", "att", ")", "{", "dbbCC", ".", "setAccessible", "(", "true", ")", ";", "Object", "b", "=", "null", ";", "try", "{", "b", "=", "dbbCC", ".",...
Create a new DirectByteBuffer from a given address and size. The returned DirectByteBuffer does not release the memory by itself. @param addr @param size @param att object holding the underlying memory to attach to the buffer. This will prevent the garbage collection of the memory area that's associated with the new <code>DirectByteBuffer</code> @return
[ "Create", "a", "new", "DirectByteBuffer", "from", "a", "given", "address", "and", "size", ".", "The", "returned", "DirectByteBuffer", "does", "not", "release", "the", "memory", "by", "itself", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/UnsafeUtil.java#L57-L67
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/DefaultMemoryAllocator.java
DefaultMemoryAllocator.releaseAll
public void releaseAll() { synchronized(this) { Object[] refSet = allocatedMemoryReferences.values().toArray(); if(refSet.length != 0) { logger.finer("Releasing allocated memory regions"); } for(Object ref : refSet) { release((MemoryReference) ref); } } }
java
public void releaseAll() { synchronized(this) { Object[] refSet = allocatedMemoryReferences.values().toArray(); if(refSet.length != 0) { logger.finer("Releasing allocated memory regions"); } for(Object ref : refSet) { release((MemoryReference) ref); } } }
[ "public", "void", "releaseAll", "(", ")", "{", "synchronized", "(", "this", ")", "{", "Object", "[", "]", "refSet", "=", "allocatedMemoryReferences", ".", "values", "(", ")", ".", "toArray", "(", ")", ";", "if", "(", "refSet", ".", "length", "!=", "0",...
Release all memory addresses taken by this allocator. Be careful in using this method, since all of the memory addresses become invalid.
[ "Release", "all", "memory", "addresses", "taken", "by", "this", "allocator", ".", "Be", "careful", "in", "using", "this", "method", "since", "all", "of", "the", "memory", "addresses", "become", "invalid", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/DefaultMemoryAllocator.java#L88-L98
train
xerial/larray
larray-mmap/src/main/java/xerial/larray/impl/LArrayLoader.java
LArrayLoader.md5sum
public static String md5sum(InputStream input) throws IOException { InputStream in = new BufferedInputStream(input); try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); DigestInputStream digestInputStream = new DigestInputStream(in, digest); while(digestInputStream.read() >= 0) { } OutputStream md5out = new ByteArrayOutputStream(); md5out.write(digest.digest()); return md5out.toString(); } catch(NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm is not available: " + e.getMessage()); } finally { in.close(); } }
java
public static String md5sum(InputStream input) throws IOException { InputStream in = new BufferedInputStream(input); try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); DigestInputStream digestInputStream = new DigestInputStream(in, digest); while(digestInputStream.read() >= 0) { } OutputStream md5out = new ByteArrayOutputStream(); md5out.write(digest.digest()); return md5out.toString(); } catch(NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm is not available: " + e.getMessage()); } finally { in.close(); } }
[ "public", "static", "String", "md5sum", "(", "InputStream", "input", ")", "throws", "IOException", "{", "InputStream", "in", "=", "new", "BufferedInputStream", "(", "input", ")", ";", "try", "{", "MessageDigest", "digest", "=", "java", ".", "security", ".", ...
Computes the MD5 value of the input stream @param input @return @throws IOException @throws IllegalStateException
[ "Computes", "the", "MD5", "value", "of", "the", "input", "stream" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-mmap/src/main/java/xerial/larray/impl/LArrayLoader.java#L103-L120
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.fill
public void fill(long offset, long length, byte value) { unsafe.setMemory(address() + offset, length, value); }
java
public void fill(long offset, long length, byte value) { unsafe.setMemory(address() + offset, length, value); }
[ "public", "void", "fill", "(", "long", "offset", ",", "long", "length", ",", "byte", "value", ")", "{", "unsafe", ".", "setMemory", "(", "address", "(", ")", "+", "offset", ",", "length", ",", "value", ")", ";", "}" ]
Fill the buffer of the specified range with a given value @param offset @param length @param value
[ "Fill", "the", "buffer", "of", "the", "specified", "range", "with", "a", "given", "value" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L113-L115
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.copyTo
public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) { int cursor = destOffset; for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) { int bbSize = bb.remaining(); if ((cursor + bbSize) > destArray.length) throw new ArrayIndexOutOfBoundsException(String.format("cursor + bbSize = %,d", cursor + bbSize)); bb.get(destArray, cursor, bbSize); cursor += bbSize; } }
java
public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) { int cursor = destOffset; for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) { int bbSize = bb.remaining(); if ((cursor + bbSize) > destArray.length) throw new ArrayIndexOutOfBoundsException(String.format("cursor + bbSize = %,d", cursor + bbSize)); bb.get(destArray, cursor, bbSize); cursor += bbSize; } }
[ "public", "void", "copyTo", "(", "int", "srcOffset", ",", "byte", "[", "]", "destArray", ",", "int", "destOffset", ",", "int", "size", ")", "{", "int", "cursor", "=", "destOffset", ";", "for", "(", "ByteBuffer", "bb", ":", "toDirectByteBuffers", "(", "sr...
Copy the contents of this buffer begginning from the srcOffset to a destination byte array @param srcOffset @param destArray @param destOffset @param size
[ "Copy", "the", "contents", "of", "this", "buffer", "begginning", "from", "the", "srcOffset", "to", "a", "destination", "byte", "array" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L237-L246
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.copyTo
public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) { unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size); }
java
public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) { unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size); }
[ "public", "void", "copyTo", "(", "long", "srcOffset", ",", "LBufferAPI", "dest", ",", "long", "destOffset", ",", "long", "size", ")", "{", "unsafe", ".", "copyMemory", "(", "address", "(", ")", "+", "srcOffset", ",", "dest", ".", "address", "(", ")", "...
Copy the contents of this buffer to the destination LBuffer @param srcOffset @param dest @param destOffset @param size
[ "Copy", "the", "contents", "of", "this", "buffer", "to", "the", "destination", "LBuffer" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L255-L257
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.slice
public LBuffer slice(long from, long to) { if(from > to) throw new IllegalArgumentException(String.format("invalid range %,d to %,d", from, to)); long size = to - from; LBuffer b = new LBuffer(size); copyTo(from, b, 0, size); return b; }
java
public LBuffer slice(long from, long to) { if(from > to) throw new IllegalArgumentException(String.format("invalid range %,d to %,d", from, to)); long size = to - from; LBuffer b = new LBuffer(size); copyTo(from, b, 0, size); return b; }
[ "public", "LBuffer", "slice", "(", "long", "from", ",", "long", "to", ")", "{", "if", "(", "from", ">", "to", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"invalid range %,d to %,d\"", ",", "from", ",", "to", ")", ...
Extract a slice [from, to) of this buffer. This methods creates a copy of the specified region. @param from @param to @return
[ "Extract", "a", "slice", "[", "from", "to", ")", "of", "this", "buffer", ".", "This", "methods", "creates", "a", "copy", "of", "the", "specified", "region", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L265-L273
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.toArray
public byte[] toArray() { if (size() > Integer.MAX_VALUE) throw new IllegalStateException("Cannot create byte array of more than 2GB"); int len = (int) size(); ByteBuffer bb = toDirectByteBuffer(0L, len); byte[] b = new byte[len]; // Copy data to the array bb.get(b, 0, len); return b; }
java
public byte[] toArray() { if (size() > Integer.MAX_VALUE) throw new IllegalStateException("Cannot create byte array of more than 2GB"); int len = (int) size(); ByteBuffer bb = toDirectByteBuffer(0L, len); byte[] b = new byte[len]; // Copy data to the array bb.get(b, 0, len); return b; }
[ "public", "byte", "[", "]", "toArray", "(", ")", "{", "if", "(", "size", "(", ")", ">", "Integer", ".", "MAX_VALUE", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot create byte array of more than 2GB\"", ")", ";", "int", "len", "=", "(", "int", ...
Convert this buffer to a java array. @return
[ "Convert", "this", "buffer", "to", "a", "java", "array", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L293-L303
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.writeTo
public void writeTo(WritableByteChannel channel) throws IOException { for (ByteBuffer buffer : toDirectByteBuffers()) { channel.write(buffer); } }
java
public void writeTo(WritableByteChannel channel) throws IOException { for (ByteBuffer buffer : toDirectByteBuffers()) { channel.write(buffer); } }
[ "public", "void", "writeTo", "(", "WritableByteChannel", "channel", ")", "throws", "IOException", "{", "for", "(", "ByteBuffer", "buffer", ":", "toDirectByteBuffers", "(", ")", ")", "{", "channel", ".", "write", "(", "buffer", ")", ";", "}", "}" ]
Writes the buffer contents to the given byte channel. @param channel @throws IOException
[ "Writes", "the", "buffer", "contents", "to", "the", "given", "byte", "channel", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L331-L335
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.writeTo
public void writeTo(File file) throws IOException { FileChannel channel = new FileOutputStream(file).getChannel(); try { writeTo(channel); } finally { channel.close(); } }
java
public void writeTo(File file) throws IOException { FileChannel channel = new FileOutputStream(file).getChannel(); try { writeTo(channel); } finally { channel.close(); } }
[ "public", "void", "writeTo", "(", "File", "file", ")", "throws", "IOException", "{", "FileChannel", "channel", "=", "new", "FileOutputStream", "(", "file", ")", ".", "getChannel", "(", ")", ";", "try", "{", "writeTo", "(", "channel", ")", ";", "}", "fina...
Dump the buffer contents to a file @param file @throws IOException
[ "Dump", "the", "buffer", "contents", "to", "a", "file" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L342-L349
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.readFrom
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length)); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src, srcOffset, readLen); return readLen; }
java
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length)); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src, srcOffset, readLen); return readLen; }
[ "public", "int", "readFrom", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ",", "long", "destOffset", ",", "int", "length", ")", "{", "int", "readLen", "=", "(", "int", ")", "Math", ".", "min", "(", "src", ".", "length", "-", "srcOffset", ...
Read the given source byte array, then overwrite this buffer's contents @param src source byte array @param srcOffset offset in source byte array to read from @param destOffset offset in this buffer to read to @param length max number of bytes to read @return the number of bytes read
[ "Read", "the", "given", "source", "byte", "array", "then", "overwrite", "this", "buffer", "s", "contents" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L371-L377
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.readFrom
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
java
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
[ "public", "int", "readFrom", "(", "ByteBuffer", "src", ",", "long", "destOffset", ")", "{", "if", "(", "src", ".", "remaining", "(", ")", "+", "destOffset", ">=", "size", "(", ")", ")", "throw", "new", "BufferOverflowException", "(", ")", ";", "int", "...
Reads the given source byte buffer into this buffer at the given offset @param src source byte buffer @param destOffset offset in this buffer to read to @return the number of bytes read
[ "Reads", "the", "given", "source", "byte", "buffer", "into", "this", "buffer", "at", "the", "given", "offset" ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L385-L393
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.loadFrom
public static LBuffer loadFrom(File file) throws IOException { FileChannel fin = new FileInputStream(file).getChannel(); long fileSize = fin.size(); if (fileSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Cannot load from file more than 2GB: " + file); LBuffer b = new LBuffer((int) fileSize); long pos = 0L; WritableChannelWrap ch = new WritableChannelWrap(b); while (pos < fileSize) { pos += fin.transferTo(0, fileSize, ch); } return b; }
java
public static LBuffer loadFrom(File file) throws IOException { FileChannel fin = new FileInputStream(file).getChannel(); long fileSize = fin.size(); if (fileSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Cannot load from file more than 2GB: " + file); LBuffer b = new LBuffer((int) fileSize); long pos = 0L; WritableChannelWrap ch = new WritableChannelWrap(b); while (pos < fileSize) { pos += fin.transferTo(0, fileSize, ch); } return b; }
[ "public", "static", "LBuffer", "loadFrom", "(", "File", "file", ")", "throws", "IOException", "{", "FileChannel", "fin", "=", "new", "FileInputStream", "(", "file", ")", ".", "getChannel", "(", ")", ";", "long", "fileSize", "=", "fin", ".", "size", "(", ...
Create an LBuffer from a given file. @param file @return @throws IOException
[ "Create", "an", "LBuffer", "from", "a", "given", "file", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L401-L413
train
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.toDirectByteBuffers
public ByteBuffer[] toDirectByteBuffers(long offset, long size) { long pos = offset; long blockSize = Integer.MAX_VALUE; long limit = offset + size; int numBuffers = (int) ((size + (blockSize - 1)) / blockSize); ByteBuffer[] result = new ByteBuffer[numBuffers]; int index = 0; while (pos < limit) { long blockLength = Math.min(limit - pos, blockSize); result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this) .order(ByteOrder.nativeOrder()); pos += blockLength; } return result; }
java
public ByteBuffer[] toDirectByteBuffers(long offset, long size) { long pos = offset; long blockSize = Integer.MAX_VALUE; long limit = offset + size; int numBuffers = (int) ((size + (blockSize - 1)) / blockSize); ByteBuffer[] result = new ByteBuffer[numBuffers]; int index = 0; while (pos < limit) { long blockLength = Math.min(limit - pos, blockSize); result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this) .order(ByteOrder.nativeOrder()); pos += blockLength; } return result; }
[ "public", "ByteBuffer", "[", "]", "toDirectByteBuffers", "(", "long", "offset", ",", "long", "size", ")", "{", "long", "pos", "=", "offset", ";", "long", "blockSize", "=", "Integer", ".", "MAX_VALUE", ";", "long", "limit", "=", "offset", "+", "size", ";"...
Gives an sequence of ByteBuffers of a specified range. Writing to these ByteBuffers modifies the contents of this LBuffer. @param offset @param size @return
[ "Gives", "an", "sequence", "of", "ByteBuffers", "of", "a", "specified", "range", ".", "Writing", "to", "these", "ByteBuffers", "modifies", "the", "contents", "of", "this", "LBuffer", "." ]
9a1462623c0e56ca67c5341ea29832963c29479f
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L430-L445
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/hint/WrappingHint.java
WrappingHint.getWrappingHint
public String getWrappingHint(String fieldName) { if (isEmpty()) { return ""; } return String.format(" You can use this expression: %s(%s(%s))", formatMethod(wrappingMethodOwnerName, wrappingMethodName, ""), formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName), fieldName); }
java
public String getWrappingHint(String fieldName) { if (isEmpty()) { return ""; } return String.format(" You can use this expression: %s(%s(%s))", formatMethod(wrappingMethodOwnerName, wrappingMethodName, ""), formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName), fieldName); }
[ "public", "String", "getWrappingHint", "(", "String", "fieldName", ")", "{", "if", "(", "isEmpty", "(", ")", ")", "{", "return", "\"\"", ";", "}", "return", "String", ".", "format", "(", "\" You can use this expression: %s(%s(%s))\"", ",", "formatMethod", "(", ...
For given field name get the actual hint message
[ "For", "given", "field", "name", "get", "the", "actual", "hint", "message" ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/hint/WrappingHint.java#L64-L73
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/settermethod/EffectiveAssignmentInsnFinder.java
EffectiveAssignmentInsnFinder.newInstance
public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable, final Collection<ControlFlowBlock> controlFlowBlocks) { return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks)); }
java
public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable, final Collection<ControlFlowBlock> controlFlowBlocks) { return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks)); }
[ "public", "static", "EffectiveAssignmentInsnFinder", "newInstance", "(", "final", "FieldNode", "targetVariable", ",", "final", "Collection", "<", "ControlFlowBlock", ">", "controlFlowBlocks", ")", "{", "return", "new", "EffectiveAssignmentInsnFinder", "(", "checkNotNull", ...
Static factory method. @param targetVariable the variable to find the effective {@code putfield} or {@code putstatic} instruction for. @param controlFlowBlocks all control flow blocks of an initialising constructor or method. @return a new instance of this class.
[ "Static", "factory", "method", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/settermethod/EffectiveAssignmentInsnFinder.java#L69-L72
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/settermethod/CandidatesInitialisersMapping.java
CandidatesInitialisersMapping.removeAndGetCandidatesWithoutInitialisingMethod
public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() { final List<FieldNode> result = new ArrayList<FieldNode>(); for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) { final Initialisers setters = entry.getValue(); final List<MethodNode> initialisingMethods = setters.getMethods(); if (initialisingMethods.isEmpty()) { result.add(entry.getKey()); } } for (final FieldNode unassociatedVariable : result) { candidatesAndInitialisers.remove(unassociatedVariable); } return result; }
java
public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() { final List<FieldNode> result = new ArrayList<FieldNode>(); for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) { final Initialisers setters = entry.getValue(); final List<MethodNode> initialisingMethods = setters.getMethods(); if (initialisingMethods.isEmpty()) { result.add(entry.getKey()); } } for (final FieldNode unassociatedVariable : result) { candidatesAndInitialisers.remove(unassociatedVariable); } return result; }
[ "public", "Collection", "<", "FieldNode", ">", "removeAndGetCandidatesWithoutInitialisingMethod", "(", ")", "{", "final", "List", "<", "FieldNode", ">", "result", "=", "new", "ArrayList", "<", "FieldNode", ">", "(", ")", ";", "for", "(", "final", "Map", ".", ...
Removes all candidates from this collection which are not associated with an initialising method. @return a {@code Collection} containing the removed unassociated candidates. This list is empty if none were removed, i. e. the result is never {@code null}.
[ "Removes", "all", "candidates", "from", "this", "collection", "which", "are", "not", "associated", "with", "an", "initialising", "method", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/settermethod/CandidatesInitialisersMapping.java#L413-L426
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/settermethod/AbstractSetterMethodChecker.java
AbstractSetterMethodChecker.verify
protected final void verify() { collectInitialisers(); verifyCandidates(); verifyInitialisers(); collectPossibleInitialValues(); verifyPossibleInitialValues(); collectEffectiveAssignmentInstructions(); verifyEffectiveAssignmentInstructions(); collectAssignmentGuards(); verifyAssignmentGuards(); end(); }
java
protected final void verify() { collectInitialisers(); verifyCandidates(); verifyInitialisers(); collectPossibleInitialValues(); verifyPossibleInitialValues(); collectEffectiveAssignmentInstructions(); verifyEffectiveAssignmentInstructions(); collectAssignmentGuards(); verifyAssignmentGuards(); end(); }
[ "protected", "final", "void", "verify", "(", ")", "{", "collectInitialisers", "(", ")", ";", "verifyCandidates", "(", ")", ";", "verifyInitialisers", "(", ")", ";", "collectPossibleInitialValues", "(", ")", ";", "verifyPossibleInitialValues", "(", ")", ";", "col...
Template method for verification of lazy initialisation.
[ "Template", "method", "for", "verification", "of", "lazy", "initialisation", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/settermethod/AbstractSetterMethodChecker.java#L132-L143
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/ConfigurationBuilder.java
ConfigurationBuilder.mergeHardcodedResultsFrom
protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) { Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream() .collect(Collectors.toMap(r -> r.className, r -> r)); resultsMap.putAll(otherConfiguration.hardcodedResults()); hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values()); }
java
protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) { Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream() .collect(Collectors.toMap(r -> r.className, r -> r)); resultsMap.putAll(otherConfiguration.hardcodedResults()); hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values()); }
[ "protected", "void", "mergeHardcodedResultsFrom", "(", "Configuration", "otherConfiguration", ")", "{", "Map", "<", "Dotted", ",", "AnalysisResult", ">", "resultsMap", "=", "hardcodedResults", ".", "build", "(", ")", ".", "stream", "(", ")", ".", "collect", "(",...
Merges the hardcoded results of this Configuration with the given Configuration. The resultant hardcoded results will be the union of the two sets of hardcoded results. Where the AnalysisResult for a class is found in both Configurations, the result from otherConfiguration will replace the existing result in this Configuration. This replacement behaviour will occur for subsequent calls to {@link #mergeHardcodedResultsFrom(Configuration)}. @param otherConfiguration - Configuration to merge hardcoded results with.
[ "Merges", "the", "hardcoded", "results", "of", "this", "Configuration", "with", "the", "given", "Configuration", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/ConfigurationBuilder.java#L355-L360
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/ConfigurationBuilder.java
ConfigurationBuilder.mergeImmutableContainerTypesFrom
protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) { Set<Dotted> union = Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses()); hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(union); }
java
protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) { Set<Dotted> union = Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses()); hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(union); }
[ "protected", "void", "mergeImmutableContainerTypesFrom", "(", "Configuration", "otherConfiguration", ")", "{", "Set", "<", "Dotted", ">", "union", "=", "Sets", ".", "union", "(", "hardcodedImmutableContainerClasses", ".", "build", "(", ")", ",", "otherConfiguration", ...
Merges the immutable container types of this Configuration with the given Configuration. The resultant immutable container types results will be the union of the two sets of immutable container types. Where the type is found in both Configurations, the result from otherConfiguration will replace the existing result in this Configuration. This replacement behaviour will occur for subsequent calls to {@link #mergeImmutableContainerTypesFrom(Configuration)} . @param otherConfiguration - Configuration to merge immutable container types with.
[ "Merges", "the", "immutable", "container", "types", "of", "this", "Configuration", "with", "the", "given", "Configuration", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/ConfigurationBuilder.java#L375-L380
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/ConfigurationBuilder.java
ConfigurationBuilder.hardcodeValidCopyMethod
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(".")); String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(".")+1); String desc = null; try { if (MethodIs.aConstructor(methodName)) { Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType); desc = Type.getConstructorDescriptor(ctor); } else { Method method = Class.forName(className).getMethod(methodName, argType); desc = Type.getMethodDescriptor(method); } } catch (NoSuchMethodException e) { rethrow("No such method", e); } catch (SecurityException e) { rethrow("Security error", e); } catch (ClassNotFoundException e) { rethrow("Class not found", e); } CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc); hardcodeValidCopyMethod(fieldType, copyMethod); }
java
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(".")); String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(".")+1); String desc = null; try { if (MethodIs.aConstructor(methodName)) { Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType); desc = Type.getConstructorDescriptor(ctor); } else { Method method = Class.forName(className).getMethod(methodName, argType); desc = Type.getMethodDescriptor(method); } } catch (NoSuchMethodException e) { rethrow("No such method", e); } catch (SecurityException e) { rethrow("Security error", e); } catch (ClassNotFoundException e) { rethrow("Class not found", e); } CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc); hardcodeValidCopyMethod(fieldType, copyMethod); }
[ "protected", "final", "void", "hardcodeValidCopyMethod", "(", "Class", "<", "?", ">", "fieldType", ",", "String", "fullyQualifiedMethodName", ",", "Class", "<", "?", ">", "argType", ")", "{", "if", "(", "argType", "==", "null", "||", "fieldType", "==", "null...
Hardcode a copy method as being valid. This should be used to tell Mutability Detector about a method which copies a collection, and when the copy can be wrapped in an immutable wrapper we can consider the assignment immutable. Useful for allowing Mutability Detector to correctly work with other collections frameworks such as Google Guava. Reflection is used to obtain the method's descriptor and to verify the method's existence. @param fieldType - the type of the field to which the result of the copy is assigned @param fullyQualifiedMethodName - the fully qualified method name @param argType - the type of the argument passed to the copy method @throws MutabilityAnalysisException - if the specified class or method does not exist @throws IllegalArgumentException - if any of the arguments are null
[ "Hardcode", "a", "copy", "method", "as", "being", "valid", ".", "This", "should", "be", "used", "to", "tell", "Mutability", "Detector", "about", "a", "method", "which", "copies", "a", "collection", "and", "when", "the", "copy", "can", "be", "wrapped", "in"...
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/ConfigurationBuilder.java#L430-L456
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/settermethod/AliasFinder.java
AliasFinder.newInstance
public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) { checkArgument(!variableName.isEmpty()); return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine)); }
java
public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) { checkArgument(!variableName.isEmpty()); return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine)); }
[ "public", "static", "AliasFinder", "newInstance", "(", "final", "String", "variableName", ",", "final", "ControlFlowBlock", "controlFlowBlockToExamine", ")", "{", "checkArgument", "(", "!", "variableName", ".", "isEmpty", "(", ")", ")", ";", "return", "new", "Alia...
Creates a new instance of this class. @param variableName name of the instance variable to search aliases for. Must neither be {@code null} nor empty. @param controlFlowBlockToExamine a {@link ControlFlowBlock} which possibly contains the setup of an alias for a lazy variable. This method thereby examines predecessors of {@code block}, too. This parameter must not be {@code null}. @return a new instance of this class.
[ "Creates", "a", "new", "instance", "of", "this", "class", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/settermethod/AliasFinder.java#L74-L77
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/hint/WrappingHintGenerator.java
WrappingHintGenerator.generateCopyingPart
private void generateCopyingPart(WrappingHint.Builder builder) { ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder() .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS) .putAll(userDefinedCopyMethods) .build() .get(typeAssignedToField); if (copyMethods.isEmpty()) { throw new WrappingHintGenerationException(); } CopyMethod firstSuitable = copyMethods.iterator().next(); builder.setCopyMethodOwnerName(firstSuitable.owner.toString()) .setCopyMethodName(firstSuitable.name); if (firstSuitable.isGeneric && typeSignature != null) { CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature) .transformGenericTree(GenericType::withoutWildcard); builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString())); } }
java
private void generateCopyingPart(WrappingHint.Builder builder) { ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder() .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS) .putAll(userDefinedCopyMethods) .build() .get(typeAssignedToField); if (copyMethods.isEmpty()) { throw new WrappingHintGenerationException(); } CopyMethod firstSuitable = copyMethods.iterator().next(); builder.setCopyMethodOwnerName(firstSuitable.owner.toString()) .setCopyMethodName(firstSuitable.name); if (firstSuitable.isGeneric && typeSignature != null) { CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature) .transformGenericTree(GenericType::withoutWildcard); builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString())); } }
[ "private", "void", "generateCopyingPart", "(", "WrappingHint", ".", "Builder", "builder", ")", "{", "ImmutableCollection", "<", "CopyMethod", ">", "copyMethods", "=", "ImmutableMultimap", ".", "<", "String", ",", "CopyMethod", ">", "builder", "(", ")", ".", "put...
Pick arbitrary copying method from available configuration and don't forget to set generic method type if required. @param builder
[ "Pick", "arbitrary", "copying", "method", "from", "available", "configuration", "and", "don", "t", "forget", "to", "set", "generic", "method", "type", "if", "required", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/hint/WrappingHintGenerator.java#L71-L91
train
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/checkers/hint/WrappingHintGenerator.java
WrappingHintGenerator.generateWrappingPart
private void generateWrappingPart(WrappingHint.Builder builder) { builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER) .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField)); }
java
private void generateWrappingPart(WrappingHint.Builder builder) { builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER) .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField)); }
[ "private", "void", "generateWrappingPart", "(", "WrappingHint", ".", "Builder", "builder", ")", "{", "builder", ".", "setWrappingMethodOwnerName", "(", "configuration", ".", "UNMODIFIABLE_METHOD_OWNER", ")", ".", "setWrappingMethodName", "(", "configuration", ".", "FIEL...
Pick arbitrary wrapping method. No generics should be set. @param builder
[ "Pick", "arbitrary", "wrapping", "method", ".", "No", "generics", "should", "be", "set", "." ]
36014d2f9e45cf0cc6d67b81395942cd39c4f6ae
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/hint/WrappingHintGenerator.java#L97-L100
train
Pkmmte/CircularImageView
circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java
CircularImageView.setBorderWidth
public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; if(paintBorder != null) paintBorder.setStrokeWidth(borderWidth); requestLayout(); invalidate(); }
java
public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; if(paintBorder != null) paintBorder.setStrokeWidth(borderWidth); requestLayout(); invalidate(); }
[ "public", "void", "setBorderWidth", "(", "int", "borderWidth", ")", "{", "this", ".", "borderWidth", "=", "borderWidth", ";", "if", "(", "paintBorder", "!=", "null", ")", "paintBorder", ".", "setStrokeWidth", "(", "borderWidth", ")", ";", "requestLayout", "(",...
Sets the CircularImageView's border width in pixels. @param borderWidth Width in pixels for the border.
[ "Sets", "the", "CircularImageView", "s", "border", "width", "in", "pixels", "." ]
aca59f32d9267c943eb6c930bdaed59c417a4d16
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java#L143-L149
train
Pkmmte/CircularImageView
circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java
CircularImageView.setShadow
public void setShadow(float radius, float dx, float dy, int color) { shadowRadius = radius; shadowDx = dx; shadowDy = dy; shadowColor = color; updateShadow(); }
java
public void setShadow(float radius, float dx, float dy, int color) { shadowRadius = radius; shadowDx = dx; shadowDy = dy; shadowColor = color; updateShadow(); }
[ "public", "void", "setShadow", "(", "float", "radius", ",", "float", "dx", ",", "float", "dy", ",", "int", "color", ")", "{", "shadowRadius", "=", "radius", ";", "shadowDx", "=", "dx", ";", "shadowDy", "=", "dy", ";", "shadowColor", "=", "color", ";", ...
Enables a dark shadow for this CircularImageView. If the radius is set to 0, the shadow is removed. @param radius Radius for the shadow to extend to. @param dx Horizontal shadow offset. @param dy Vertical shadow offset. @param color The color of the shadow to apply.
[ "Enables", "a", "dark", "shadow", "for", "this", "CircularImageView", ".", "If", "the", "radius", "is", "set", "to", "0", "the", "shadow", "is", "removed", "." ]
aca59f32d9267c943eb6c930bdaed59c417a4d16
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java#L210-L216
train
Pkmmte/CircularImageView
circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java
CircularImageView.drawableToBitmap
public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) // Don't do anything without a proper drawable return null; else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable Log.i(TAG, "Bitmap drawable!"); return ((BitmapDrawable) drawable).getBitmap(); } int intrinsicWidth = drawable.getIntrinsicWidth(); int intrinsicHeight = drawable.getIntrinsicHeight(); if (!(intrinsicWidth > 0 && intrinsicHeight > 0)) return null; try { // Create Bitmap object out of the drawable Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { // Simply return null of failed bitmap creations Log.e(TAG, "Encountered OutOfMemoryError while generating bitmap!"); return null; } }
java
public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) // Don't do anything without a proper drawable return null; else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable Log.i(TAG, "Bitmap drawable!"); return ((BitmapDrawable) drawable).getBitmap(); } int intrinsicWidth = drawable.getIntrinsicWidth(); int intrinsicHeight = drawable.getIntrinsicHeight(); if (!(intrinsicWidth > 0 && intrinsicHeight > 0)) return null; try { // Create Bitmap object out of the drawable Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { // Simply return null of failed bitmap creations Log.e(TAG, "Encountered OutOfMemoryError while generating bitmap!"); return null; } }
[ "public", "Bitmap", "drawableToBitmap", "(", "Drawable", "drawable", ")", "{", "if", "(", "drawable", "==", "null", ")", "// Don't do anything without a proper drawable", "return", "null", ";", "else", "if", "(", "drawable", "instanceof", "BitmapDrawable", ")", "{",...
Convert a drawable object into a Bitmap. @param drawable Drawable to extract a Bitmap from. @return A Bitmap created from the drawable parameter.
[ "Convert", "a", "drawable", "object", "into", "a", "Bitmap", "." ]
aca59f32d9267c943eb6c930bdaed59c417a4d16
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java#L393-L419
train
Pkmmte/CircularImageView
circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java
CircularImageView.updateBitmapShader
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); } }
java
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); } }
[ "public", "void", "updateBitmapShader", "(", ")", "{", "if", "(", "image", "==", "null", ")", "return", ";", "shader", "=", "new", "BitmapShader", "(", "image", ",", "Shader", ".", "TileMode", ".", "CLAMP", ",", "Shader", ".", "TileMode", ".", "CLAMP", ...
Re-initializes the shader texture used to fill in the Circle upon drawing.
[ "Re", "-", "initializes", "the", "shader", "texture", "used", "to", "fill", "in", "the", "Circle", "upon", "drawing", "." ]
aca59f32d9267c943eb6c930bdaed59c417a4d16
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java#L428-L440
train
Pkmmte/CircularImageView
circularimageview-eclipse/CircularImageView/src/com/pkmmte/circularimageview/CircularImageView.java
CircularImageView.refreshBitmapShader
public void refreshBitmapShader() { shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); }
java
public void refreshBitmapShader() { shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); }
[ "public", "void", "refreshBitmapShader", "(", ")", "{", "shader", "=", "new", "BitmapShader", "(", "Bitmap", ".", "createScaledBitmap", "(", "image", ",", "canvasSize", ",", "canvasSize", ",", "false", ")", ",", "Shader", ".", "TileMode", ".", "CLAMP", ",", ...
Reinitializes the shader texture used to fill in the Circle upon drawing.
[ "Reinitializes", "the", "shader", "texture", "used", "to", "fill", "in", "the", "Circle", "upon", "drawing", "." ]
aca59f32d9267c943eb6c930bdaed59c417a4d16
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview-eclipse/CircularImageView/src/com/pkmmte/circularimageview/CircularImageView.java#L354-L357
train
Cleveroad/LoopBar
LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/OrientationStateHorizontalBottom.java
OrientationStateHorizontalBottom.calcItemWidth
private int calcItemWidth(RecyclerView rvCategories) { if (itemWidth == null || itemWidth == 0) { for (int i = 0; i < rvCategories.getChildCount(); i++) { itemWidth = rvCategories.getChildAt(i).getWidth(); if (itemWidth != 0) { break; } } } // in case of call before view was created if (itemWidth == null) { itemWidth = 0; } return itemWidth; }
java
private int calcItemWidth(RecyclerView rvCategories) { if (itemWidth == null || itemWidth == 0) { for (int i = 0; i < rvCategories.getChildCount(); i++) { itemWidth = rvCategories.getChildAt(i).getWidth(); if (itemWidth != 0) { break; } } } // in case of call before view was created if (itemWidth == null) { itemWidth = 0; } return itemWidth; }
[ "private", "int", "calcItemWidth", "(", "RecyclerView", "rvCategories", ")", "{", "if", "(", "itemWidth", "==", "null", "||", "itemWidth", "==", "0", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rvCategories", ".", "getChildCount", "(", ...
very big duct tape
[ "very", "big", "duct", "tape" ]
6ff5e0b35e637202202f9b4ca141195bdcfd5697
https://github.com/Cleveroad/LoopBar/blob/6ff5e0b35e637202202f9b4ca141195bdcfd5697/LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/OrientationStateHorizontalBottom.java#L87-L101
train
Cleveroad/LoopBar
LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java
LoopBarView.setOrientation
public final void setOrientation(int orientation) { mOrientation = orientation; mOrientationState = getOrientationStateFromParam(mOrientation); invalidate(); if (mOuterAdapter != null) { mOuterAdapter.setOrientation(mOrientation); } }
java
public final void setOrientation(int orientation) { mOrientation = orientation; mOrientationState = getOrientationStateFromParam(mOrientation); invalidate(); if (mOuterAdapter != null) { mOuterAdapter.setOrientation(mOrientation); } }
[ "public", "final", "void", "setOrientation", "(", "int", "orientation", ")", "{", "mOrientation", "=", "orientation", ";", "mOrientationState", "=", "getOrientationStateFromParam", "(", "mOrientation", ")", ";", "invalidate", "(", ")", ";", "if", "(", "mOuterAdapt...
Sets orientation of loopbar @param orientation int value of orientation. Must be one of {@link Orientation}
[ "Sets", "orientation", "of", "loopbar" ]
6ff5e0b35e637202202f9b4ca141195bdcfd5697
https://github.com/Cleveroad/LoopBar/blob/6ff5e0b35e637202202f9b4ca141195bdcfd5697/LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java#L256-L264
train
Cleveroad/LoopBar
LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java
LoopBarView.selectItem
@SuppressWarnings("unused") public void selectItem(int position, boolean invokeListeners) { IOperationItem item = mOuterAdapter.getItem(position); IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition); int realPosition = mOuterAdapter.normalizePosition(position); //do nothing if position not changed if (realPosition == mCurrentItemPosition) { return; } int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition; item.setVisible(false); startSelectedViewOutAnimation(position); mOuterAdapter.notifyRealItemChanged(position); mRealHidedPosition = realPosition; oldHidedItem.setVisible(true); mFlContainerSelected.requestLayout(); mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition); mCurrentItemPosition = realPosition; if (invokeListeners) { notifyItemClickListeners(realPosition); } if (BuildConfig.DEBUG) { Log.i(TAG, "clicked on position =" + position); } }
java
@SuppressWarnings("unused") public void selectItem(int position, boolean invokeListeners) { IOperationItem item = mOuterAdapter.getItem(position); IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition); int realPosition = mOuterAdapter.normalizePosition(position); //do nothing if position not changed if (realPosition == mCurrentItemPosition) { return; } int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition; item.setVisible(false); startSelectedViewOutAnimation(position); mOuterAdapter.notifyRealItemChanged(position); mRealHidedPosition = realPosition; oldHidedItem.setVisible(true); mFlContainerSelected.requestLayout(); mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition); mCurrentItemPosition = realPosition; if (invokeListeners) { notifyItemClickListeners(realPosition); } if (BuildConfig.DEBUG) { Log.i(TAG, "clicked on position =" + position); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "void", "selectItem", "(", "int", "position", ",", "boolean", "invokeListeners", ")", "{", "IOperationItem", "item", "=", "mOuterAdapter", ".", "getItem", "(", "position", ")", ";", "IOperationItem", "ol...
Select item by it's position @param position int value of item position to select @param invokeListeners boolean value for invoking listeners
[ "Select", "item", "by", "it", "s", "position" ]
6ff5e0b35e637202202f9b4ca141195bdcfd5697
https://github.com/Cleveroad/LoopBar/blob/6ff5e0b35e637202202f9b4ca141195bdcfd5697/LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java#L778-L810
train
Cleveroad/LoopBar
LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java
LoopBarView.getOrientationStateFromParam
public IOrientationState getOrientationStateFromParam(int orientation) { switch (orientation) { case Orientation.ORIENTATION_HORIZONTAL_BOTTOM: return new OrientationStateHorizontalBottom(); case Orientation.ORIENTATION_HORIZONTAL_TOP: return new OrientationStateHorizontalTop(); case Orientation.ORIENTATION_VERTICAL_LEFT: return new OrientationStateVerticalLeft(); case Orientation.ORIENTATION_VERTICAL_RIGHT: return new OrientationStateVerticalRight(); default: return new OrientationStateHorizontalBottom(); } }
java
public IOrientationState getOrientationStateFromParam(int orientation) { switch (orientation) { case Orientation.ORIENTATION_HORIZONTAL_BOTTOM: return new OrientationStateHorizontalBottom(); case Orientation.ORIENTATION_HORIZONTAL_TOP: return new OrientationStateHorizontalTop(); case Orientation.ORIENTATION_VERTICAL_LEFT: return new OrientationStateVerticalLeft(); case Orientation.ORIENTATION_VERTICAL_RIGHT: return new OrientationStateVerticalRight(); default: return new OrientationStateHorizontalBottom(); } }
[ "public", "IOrientationState", "getOrientationStateFromParam", "(", "int", "orientation", ")", "{", "switch", "(", "orientation", ")", "{", "case", "Orientation", ".", "ORIENTATION_HORIZONTAL_BOTTOM", ":", "return", "new", "OrientationStateHorizontalBottom", "(", ")", "...
orientation state factory method
[ "orientation", "state", "factory", "method" ]
6ff5e0b35e637202202f9b4ca141195bdcfd5697
https://github.com/Cleveroad/LoopBar/blob/6ff5e0b35e637202202f9b4ca141195bdcfd5697/LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/LoopBarView.java#L823-L836
train
Cleveroad/LoopBar
LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/AbstractOrientationState.java
AbstractOrientationState.setSelectionMargin
@Override public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) { return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams); }
java
@Override public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) { return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams); }
[ "@", "Override", "public", "<", "T", "extends", "ViewGroup", ".", "MarginLayoutParams", ">", "T", "setSelectionMargin", "(", "int", "marginPx", ",", "T", "layoutParams", ")", "{", "return", "mSelectionGravityState", ".", "setSelectionMargin", "(", "marginPx", ",",...
dispatch to gravity state
[ "dispatch", "to", "gravity", "state" ]
6ff5e0b35e637202202f9b4ca141195bdcfd5697
https://github.com/Cleveroad/LoopBar/blob/6ff5e0b35e637202202f9b4ca141195bdcfd5697/LoopBar-widget/src/main/java/com/cleveroad/loopbar/widget/AbstractOrientationState.java#L31-L34
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/consumer/RepeatingDataConsumer.java
RepeatingDataConsumer.consume
public int consume(Map<String, String> initialVars) { int result = 0; for (int i = 0; i < repeatNumber; i++) { result += super.consume(initialVars); } return result; }
java
public int consume(Map<String, String> initialVars) { int result = 0; for (int i = 0; i < repeatNumber; i++) { result += super.consume(initialVars); } return result; }
[ "public", "int", "consume", "(", "Map", "<", "String", ",", "String", ">", "initialVars", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "repeatNumber", ";", "i", "++", ")", "{", "result", "+=", "super"...
Overridden 'consume' method. Corresponding parent method will be called necessary number of times @param initialVars - a map containing the initial variables assignments @return the number of lines written
[ "Overridden", "consume", "method", ".", "Corresponding", "parent", "method", "will", "be", "called", "necessary", "number", "of", "times" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/consumer/RepeatingDataConsumer.java#L41-L49
train
FINRAOS/DataGenerator
dg-simple-csv/src/main/java/org/finra/datagenerator/simplecsv/CmdLine.java
CmdLine.main
public static void main(String[] args) { String modelFile = ""; String outputFile = ""; int numberOfRows = 0; try { modelFile = args[0]; outputFile = args[1]; numberOfRows = Integer.valueOf(args[2]); } catch (IndexOutOfBoundsException | NumberFormatException e) { System.out.println("ERROR! Invalid command line arguments, expecting: <scxml model file> " + "<desired csv output file> <desired number of output rows>"); return; } FileInputStream model = null; try { model = new FileInputStream(modelFile); } catch (FileNotFoundException e) { System.out.println("ERROR! Model file not found"); return; } SCXMLEngine engine = new SCXMLEngine(); engine.setModelByInputFileStream(model); engine.setBootstrapMin(5); DataConsumer consumer = new DataConsumer(); CSVFileWriter writer; try { writer = new CSVFileWriter(outputFile); } catch (IOException e) { System.out.println("ERROR! Can not write to output csv file"); return; } consumer.addDataWriter(writer); DefaultDistributor dist = new DefaultDistributor(); dist.setThreadCount(5); dist.setMaxNumberOfLines(numberOfRows); dist.setDataConsumer(consumer); engine.process(dist); writer.closeCSVFile(); System.out.println("COMPLETE!"); }
java
public static void main(String[] args) { String modelFile = ""; String outputFile = ""; int numberOfRows = 0; try { modelFile = args[0]; outputFile = args[1]; numberOfRows = Integer.valueOf(args[2]); } catch (IndexOutOfBoundsException | NumberFormatException e) { System.out.println("ERROR! Invalid command line arguments, expecting: <scxml model file> " + "<desired csv output file> <desired number of output rows>"); return; } FileInputStream model = null; try { model = new FileInputStream(modelFile); } catch (FileNotFoundException e) { System.out.println("ERROR! Model file not found"); return; } SCXMLEngine engine = new SCXMLEngine(); engine.setModelByInputFileStream(model); engine.setBootstrapMin(5); DataConsumer consumer = new DataConsumer(); CSVFileWriter writer; try { writer = new CSVFileWriter(outputFile); } catch (IOException e) { System.out.println("ERROR! Can not write to output csv file"); return; } consumer.addDataWriter(writer); DefaultDistributor dist = new DefaultDistributor(); dist.setThreadCount(5); dist.setMaxNumberOfLines(numberOfRows); dist.setDataConsumer(consumer); engine.process(dist); writer.closeCSVFile(); System.out.println("COMPLETE!"); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "String", "modelFile", "=", "\"\"", ";", "String", "outputFile", "=", "\"\"", ";", "int", "numberOfRows", "=", "0", ";", "try", "{", "modelFile", "=", "args", "[", "0", "]...
Main method, handles all the setup tasks for DataGenerator a user would normally do themselves @param args command line arguments
[ "Main", "method", "handles", "all", "the", "setup", "tasks", "for", "DataGenerator", "a", "user", "would", "normally", "do", "themselves" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-simple-csv/src/main/java/org/finra/datagenerator/simplecsv/CmdLine.java#L42-L87
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java
SocialNetworkUtilities.getRandomGeographicalLocation
public static Tuple2<Double, Double> getRandomGeographicalLocation() { return new Tuple2<>( (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100, (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100); }
java
public static Tuple2<Double, Double> getRandomGeographicalLocation() { return new Tuple2<>( (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100, (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100); }
[ "public", "static", "Tuple2", "<", "Double", ",", "Double", ">", "getRandomGeographicalLocation", "(", ")", "{", "return", "new", "Tuple2", "<>", "(", "(", "double", ")", "(", "RandomHelper", ".", "randWithConfiguredSeed", "(", ")", ".", "nextInt", "(", "999...
Get random geographical location @return 2-Tuple of ints (latitude, longitude)
[ "Get", "random", "geographical", "location" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L48-L52
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java
SocialNetworkUtilities.getDistanceBetweenCoordinates
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); }
java
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); }
[ "public", "static", "Double", "getDistanceBetweenCoordinates", "(", "Tuple2", "<", "Double", ",", "Double", ">", "point1", ",", "Tuple2", "<", "Double", ",", "Double", ">", "point2", ")", "{", "// sqrt( (x2-x1)^2 + (y2-y2)^2 )\r", "Double", "xDiff", "=", "point1",...
Get distance between geographical coordinates @param point1 Point1 @param point2 Point2 @return Distance (double)
[ "Get", "distance", "between", "geographical", "coordinates" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L60-L65
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java
SocialNetworkUtilities.getDistanceWithinThresholdOfCoordinates
public static Double getDistanceWithinThresholdOfCoordinates( Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { throw new NotImplementedError(); }
java
public static Double getDistanceWithinThresholdOfCoordinates( Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { throw new NotImplementedError(); }
[ "public", "static", "Double", "getDistanceWithinThresholdOfCoordinates", "(", "Tuple2", "<", "Double", ",", "Double", ">", "point1", ",", "Tuple2", "<", "Double", ",", "Double", ">", "point2", ")", "{", "throw", "new", "NotImplementedError", "(", ")", ";", "}"...
Not implemented. @param point1 Point1 @param point2 Point2 @return Throws an exception.
[ "Not", "implemented", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L73-L76
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java
SocialNetworkUtilities.areCoordinatesWithinThreshold
public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD; }
java
public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD; }
[ "public", "static", "Boolean", "areCoordinatesWithinThreshold", "(", "Tuple2", "<", "Double", ",", "Double", ">", "point1", ",", "Tuple2", "<", "Double", ",", "Double", ">", "point2", ")", "{", "return", "getDistanceBetweenCoordinates", "(", "point1", ",", "poin...
Whether or not points are within some threshold. @param point1 Point 1 @param point2 Point 2 @return True or false
[ "Whether", "or", "not", "points", "are", "within", "some", "threshold", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L94-L96
train
FINRAOS/DataGenerator
dg-example-default/src/main/java/org/finra/datagenerator/samples/CmdLine.java
CmdLine.main
public static void main(String[] args) { //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal--> //MODEL USAGE EXAMPLE: <assign name="var_out_V1_2" expr="%ssn"/> <dg:transform name="EQ"/> Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>(); transformers.put("EQ", new EquivalenceClassTransformer()); Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>(); cte.add(new InLineTransformerExtension(transformers)); Engine engine = new SCXMLEngine(cte); //will default to samplemachine, but you could specify a different file if you choose to InputStream is = CmdLine.class.getResourceAsStream("/" + (args.length == 0 ? "samplemachine" : args[0]) + ".xml"); engine.setModelByInputFileStream(is); // Usually, this should be more than the number of threads you intend to run engine.setBootstrapMin(1); //Prepare the consumer with the proper writer and transformer DataConsumer consumer = new DataConsumer(); consumer.addDataTransformer(new SampleMachineTransformer()); //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation. //MODEL USAGE EXAMPLE: <dg:assign name="var_out_V2" set="%regex([0-9]{3}[A-Z0-9]{5})"/> consumer.addDataTransformer(new EquivalenceClassTransformer()); consumer.addDataWriter(new DefaultWriter(System.out, new String[]{"var_1_1", "var_1_2", "var_1_3", "var_1_4", "var_1_5", "var_1_6", "var_1_7", "var_2_1", "var_2_2", "var_2_3", "var_2_4", "var_2_5", "var_2_6", "var_2_7", "var_2_8"})); //Prepare the distributor DefaultDistributor defaultDistributor = new DefaultDistributor(); defaultDistributor.setThreadCount(1); defaultDistributor.setDataConsumer(consumer); Logger.getLogger("org.apache").setLevel(Level.WARN); engine.process(defaultDistributor); }
java
public static void main(String[] args) { //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal--> //MODEL USAGE EXAMPLE: <assign name="var_out_V1_2" expr="%ssn"/> <dg:transform name="EQ"/> Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>(); transformers.put("EQ", new EquivalenceClassTransformer()); Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>(); cte.add(new InLineTransformerExtension(transformers)); Engine engine = new SCXMLEngine(cte); //will default to samplemachine, but you could specify a different file if you choose to InputStream is = CmdLine.class.getResourceAsStream("/" + (args.length == 0 ? "samplemachine" : args[0]) + ".xml"); engine.setModelByInputFileStream(is); // Usually, this should be more than the number of threads you intend to run engine.setBootstrapMin(1); //Prepare the consumer with the proper writer and transformer DataConsumer consumer = new DataConsumer(); consumer.addDataTransformer(new SampleMachineTransformer()); //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation. //MODEL USAGE EXAMPLE: <dg:assign name="var_out_V2" set="%regex([0-9]{3}[A-Z0-9]{5})"/> consumer.addDataTransformer(new EquivalenceClassTransformer()); consumer.addDataWriter(new DefaultWriter(System.out, new String[]{"var_1_1", "var_1_2", "var_1_3", "var_1_4", "var_1_5", "var_1_6", "var_1_7", "var_2_1", "var_2_2", "var_2_3", "var_2_4", "var_2_5", "var_2_6", "var_2_7", "var_2_8"})); //Prepare the distributor DefaultDistributor defaultDistributor = new DefaultDistributor(); defaultDistributor.setThreadCount(1); defaultDistributor.setDataConsumer(consumer); Logger.getLogger("org.apache").setLevel(Level.WARN); engine.process(defaultDistributor); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "//Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r", "//MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/...
Entry point for the example. @param args Command-line arguments for the example. To use samplemachine.xml from resources, send no arguments. To use other file, send a filename without xml extension).
[ "Entry", "point", "for", "the", "example", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-default/src/main/java/org/finra/datagenerator/samples/CmdLine.java#L54-L90
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/UserStub.java
UserStub.getStubWithRandomParams
public static UserStub getStubWithRandomParams(UserTypeVal userType) { // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles! // Oh the joys of type erasure. Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation(); return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()), SocialNetworkUtilities.getRandomIsSecret()); }
java
public static UserStub getStubWithRandomParams(UserTypeVal userType) { // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles! // Oh the joys of type erasure. Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation(); return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()), SocialNetworkUtilities.getRandomIsSecret()); }
[ "public", "static", "UserStub", "getStubWithRandomParams", "(", "UserTypeVal", "userType", ")", "{", "// Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!\r", "// Oh the joys of type erasure.\r", "Tuple2", "<", "Double", ",", "Double", "...
Get random stub matching this user type @param userType User type @return Random stub
[ "Get", "random", "stub", "matching", "this", "user", "type" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/UserStub.java#L116-L122
train
FINRAOS/DataGenerator
dg-simple-csv/src/main/java/org/finra/datagenerator/simplecsv/writer/CSVFileWriter.java
CSVFileWriter.writeOutput
public void writeOutput(DataPipe cr) { String[] nextLine = new String[cr.getDataMap().entrySet().size()]; int count = 0; for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { nextLine[count] = entry.getValue(); count++; } csvFile.writeNext(nextLine); }
java
public void writeOutput(DataPipe cr) { String[] nextLine = new String[cr.getDataMap().entrySet().size()]; int count = 0; for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { nextLine[count] = entry.getValue(); count++; } csvFile.writeNext(nextLine); }
[ "public", "void", "writeOutput", "(", "DataPipe", "cr", ")", "{", "String", "[", "]", "nextLine", "=", "new", "String", "[", "cr", ".", "getDataMap", "(", ")", ".", "entrySet", "(", ")", ".", "size", "(", ")", "]", ";", "int", "count", "=", "0", ...
Prints one line to the csv file @param cr data pipe with search results
[ "Prints", "one", "line", "to", "the", "csv", "file" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-simple-csv/src/main/java/org/finra/datagenerator/simplecsv/writer/CSVFileWriter.java#L49-L59
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.isHoliday
public boolean isHoliday(String dateString) { boolean isHoliday = false; for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) { if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) { isHoliday = true; } } return isHoliday; }
java
public boolean isHoliday(String dateString) { boolean isHoliday = false; for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) { if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) { isHoliday = true; } } return isHoliday; }
[ "public", "boolean", "isHoliday", "(", "String", "dateString", ")", "{", "boolean", "isHoliday", "=", "false", ";", "for", "(", "Holiday", "date", ":", "EquivalenceClassTransformer", ".", "HOLIDAYS", ")", "{", "if", "(", "convertToReadableDate", "(", "date", "...
Checks if the date is a holiday @param dateString the date @return true if it is a holiday, false otherwise
[ "Checks", "if", "the", "date", "is", "a", "holiday" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L81-L89
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.getNextDay
public String getNextDay(String dateString, boolean onlyBusinessDays) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(dateString).plusDays(1); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); if (onlyBusinessDays) { if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7 || isHoliday(date.toString().substring(0, 10))) { return getNextDay(date.toString().substring(0, 10), true); } else { return parser.print(date); } } else { return parser.print(date); } }
java
public String getNextDay(String dateString, boolean onlyBusinessDays) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(dateString).plusDays(1); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); if (onlyBusinessDays) { if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7 || isHoliday(date.toString().substring(0, 10))) { return getNextDay(date.toString().substring(0, 10), true); } else { return parser.print(date); } } else { return parser.print(date); } }
[ "public", "String", "getNextDay", "(", "String", "dateString", ",", "boolean", "onlyBusinessDays", ")", "{", "DateTimeFormatter", "parser", "=", "ISODateTimeFormat", ".", "date", "(", ")", ";", "DateTime", "date", "=", "parser", ".", "parseDateTime", "(", "dateS...
Takes a date, and retrieves the next business day @param dateString the date @param onlyBusinessDays only business days @return a string containing the next business day
[ "Takes", "a", "date", "and", "retrieves", "the", "next", "business", "day" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L98-L114
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.toDate
public Date toDate(String dateString) { Date date = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { date = df.parse(dateString); } catch (ParseException ex) { System.out.println(ex.fillInStackTrace()); } return date; }
java
public Date toDate(String dateString) { Date date = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { date = df.parse(dateString); } catch (ParseException ex) { System.out.println(ex.fillInStackTrace()); } return date; }
[ "public", "Date", "toDate", "(", "String", "dateString", ")", "{", "Date", "date", "=", "null", ";", "DateFormat", "df", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd\"", ")", ";", "try", "{", "date", "=", "df", ".", "parse", "(", "dateString", ")",...
Takes a String and converts it to a Date @param dateString the date @return Date denoted by dateString
[ "Takes", "a", "String", "and", "converts", "it", "to", "a", "Date" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L212-L221
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.getRandomHoliday
public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new LinkedList<>(); int min = Integer.parseInt(earlyDate.toString().substring(0, 4)); int max = Integer.parseInt(lateDate.toString().substring(0, 4)); int range = max - min + 1; int randomYear = (int) (Math.random() * range) + min; for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) { holidays.add(s); } Collections.shuffle(holidays); for (Holiday holiday : holidays) { dateString = convertToReadableDate(holiday.forYear(randomYear)); if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) { break; } } return dateString; }
java
public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new LinkedList<>(); int min = Integer.parseInt(earlyDate.toString().substring(0, 4)); int max = Integer.parseInt(lateDate.toString().substring(0, 4)); int range = max - min + 1; int randomYear = (int) (Math.random() * range) + min; for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) { holidays.add(s); } Collections.shuffle(holidays); for (Holiday holiday : holidays) { dateString = convertToReadableDate(holiday.forYear(randomYear)); if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) { break; } } return dateString; }
[ "public", "String", "getRandomHoliday", "(", "String", "earliest", ",", "String", "latest", ")", "{", "String", "dateString", "=", "\"\"", ";", "DateTimeFormatter", "parser", "=", "ISODateTimeFormat", ".", "date", "(", ")", ";", "DateTime", "earlyDate", "=", "...
Grab random holiday from the equivalence class that falls between the two dates @param earliest the earliest date parameter as defined in the model @param latest the latest date parameter as defined in the model @return a holiday that falls between the dates
[ "Grab", "random", "holiday", "from", "the", "equivalence", "class", "that", "falls", "between", "the", "two", "dates" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L230-L254
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.numOccurrences
public int numOccurrences(int year, int month, int day) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01"); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); GregorianChronology calendar = GregorianChronology.getInstance(); DateTimeField field = calendar.dayOfMonth(); int days = 0; int count = 0; int num = field.getMaximumValue(new LocalDate(year, month, day, calendar)); while (days < num) { if (cal.get(Calendar.DAY_OF_WEEK) == day) { count++; } date = date.plusDays(1); cal.setTime(date.toDate()); days++; } return count; }
java
public int numOccurrences(int year, int month, int day) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01"); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); GregorianChronology calendar = GregorianChronology.getInstance(); DateTimeField field = calendar.dayOfMonth(); int days = 0; int count = 0; int num = field.getMaximumValue(new LocalDate(year, month, day, calendar)); while (days < num) { if (cal.get(Calendar.DAY_OF_WEEK) == day) { count++; } date = date.plusDays(1); cal.setTime(date.toDate()); days++; } return count; }
[ "public", "int", "numOccurrences", "(", "int", "year", ",", "int", "month", ",", "int", "day", ")", "{", "DateTimeFormatter", "parser", "=", "ISODateTimeFormat", ".", "date", "(", ")", ";", "DateTime", "date", "=", "parser", ".", "parseDateTime", "(", "yea...
Given a year, month, and day, find the number of occurrences of that day in the month @param year the year @param month the month @param day the day @return the number of occurrences of the day in the month
[ "Given", "a", "year", "month", "and", "day", "find", "the", "number", "of", "occurrences", "of", "that", "day", "in", "the", "month" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L264-L285
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
BoundaryDate.convertToReadableDate
public String convertToReadableDate(Holiday holiday) { DateTimeFormatter parser = ISODateTimeFormat.date(); if (holiday.isInDateForm()) { String month = Integer.toString(holiday.getMonth()).length() < 2 ? "0" + holiday.getMonth() : Integer.toString(holiday.getMonth()); String day = Integer.toString(holiday.getDayOfMonth()).length() < 2 ? "0" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth()); return holiday.getYear() + "-" + month + "-" + day; } else { /* * 5 denotes the final occurrence of the day in the month. Need to find actual * number of occurrences */ if (holiday.getOccurrence() == 5) { holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(), holiday.getDayOfWeek())); } DateTime date = parser.parseDateTime(holiday.getYear() + "-" + holiday.getMonth() + "-" + "01"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date.toDate()); int count = 0; while (count < holiday.getOccurrence()) { if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) { count++; if (count == holiday.getOccurrence()) { break; } } date = date.plusDays(1); calendar.setTime(date.toDate()); } return date.toString().substring(0, 10); } }
java
public String convertToReadableDate(Holiday holiday) { DateTimeFormatter parser = ISODateTimeFormat.date(); if (holiday.isInDateForm()) { String month = Integer.toString(holiday.getMonth()).length() < 2 ? "0" + holiday.getMonth() : Integer.toString(holiday.getMonth()); String day = Integer.toString(holiday.getDayOfMonth()).length() < 2 ? "0" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth()); return holiday.getYear() + "-" + month + "-" + day; } else { /* * 5 denotes the final occurrence of the day in the month. Need to find actual * number of occurrences */ if (holiday.getOccurrence() == 5) { holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(), holiday.getDayOfWeek())); } DateTime date = parser.parseDateTime(holiday.getYear() + "-" + holiday.getMonth() + "-" + "01"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date.toDate()); int count = 0; while (count < holiday.getOccurrence()) { if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) { count++; if (count == holiday.getOccurrence()) { break; } } date = date.plusDays(1); calendar.setTime(date.toDate()); } return date.toString().substring(0, 10); } }
[ "public", "String", "convertToReadableDate", "(", "Holiday", "holiday", ")", "{", "DateTimeFormatter", "parser", "=", "ISODateTimeFormat", ".", "date", "(", ")", ";", "if", "(", "holiday", ".", "isInDateForm", "(", ")", ")", "{", "String", "month", "=", "Int...
Convert the holiday format from EquivalenceClassTransformer into a date format @param holiday the date @return a date String in the format yyyy-MM-dd
[ "Convert", "the", "holiday", "format", "from", "EquivalenceClassTransformer", "into", "a", "date", "format" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L293-L330
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java
JettyManager.requestBlock
public synchronized String requestBlock(String name) { if (blocks.isEmpty()) { return "exit"; } remainingBlocks.decrementAndGet(); return blocks.poll().createResponse(); }
java
public synchronized String requestBlock(String name) { if (blocks.isEmpty()) { return "exit"; } remainingBlocks.decrementAndGet(); return blocks.poll().createResponse(); }
[ "public", "synchronized", "String", "requestBlock", "(", "String", "name", ")", "{", "if", "(", "blocks", ".", "isEmpty", "(", ")", ")", "{", "return", "\"exit\"", ";", "}", "remainingBlocks", ".", "decrementAndGet", "(", ")", ";", "return", "blocks", ".",...
Returns a description a block of work, or "exit" if no more blocks exist @param name the assigned name of the consumer requesting a block of work @return a description a block of work, or "exit" if no more blocks exist
[ "Returns", "a", "description", "a", "block", "of", "work", "or", "exit", "if", "no", "more", "blocks", "exist" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java#L76-L83
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java
JettyManager.makeReport
public String makeReport(String name, String report) { long increment = Long.valueOf(report); long currentLineCount = globalLineCounter.addAndGet(increment); if (currentLineCount >= maxScenarios) { return "exit"; } else { return "ok"; } }
java
public String makeReport(String name, String report) { long increment = Long.valueOf(report); long currentLineCount = globalLineCounter.addAndGet(increment); if (currentLineCount >= maxScenarios) { return "exit"; } else { return "ok"; } }
[ "public", "String", "makeReport", "(", "String", "name", ",", "String", "report", ")", "{", "long", "increment", "=", "Long", ".", "valueOf", "(", "report", ")", ";", "long", "currentLineCount", "=", "globalLineCounter", ".", "addAndGet", "(", "increment", "...
Handles reports by consumers @param name the name of the reporting consumer @param report the number of lines the consumer has written since last report @return "exit" if maxScenarios has been reached, "ok" otherwise
[ "Handles", "reports", "by", "consumers" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java#L101-L110
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java
JettyManager.prepareStatus
public void prepareStatus() { globalLineCounter = new AtomicLong(0); time = new AtomicLong(System.currentTimeMillis()); startTime = System.currentTimeMillis(); lastCount = 0; // Status thread regularly reports on what is happening Thread statusThread = new Thread() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Status thread interrupted"); } long thisTime = System.currentTimeMillis(); long currentCount = globalLineCounter.get(); if (thisTime - time.get() > 1000) { long oldTime = time.get(); time.set(thisTime); double avgRate = 1000.0 * currentCount / (thisTime - startTime); double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime); lastCount = currentCount; System.out.println(currentCount + " AvgRage:" + ((int) avgRate) + " lines/sec instRate:" + ((int) instRate) + " lines/sec Unassigned Work: " + remainingBlocks.get() + " blocks"); } } } }; statusThread.start(); }
java
public void prepareStatus() { globalLineCounter = new AtomicLong(0); time = new AtomicLong(System.currentTimeMillis()); startTime = System.currentTimeMillis(); lastCount = 0; // Status thread regularly reports on what is happening Thread statusThread = new Thread() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Status thread interrupted"); } long thisTime = System.currentTimeMillis(); long currentCount = globalLineCounter.get(); if (thisTime - time.get() > 1000) { long oldTime = time.get(); time.set(thisTime); double avgRate = 1000.0 * currentCount / (thisTime - startTime); double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime); lastCount = currentCount; System.out.println(currentCount + " AvgRage:" + ((int) avgRate) + " lines/sec instRate:" + ((int) instRate) + " lines/sec Unassigned Work: " + remainingBlocks.get() + " blocks"); } } } }; statusThread.start(); }
[ "public", "void", "prepareStatus", "(", ")", "{", "globalLineCounter", "=", "new", "AtomicLong", "(", "0", ")", ";", "time", "=", "new", "AtomicLong", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "startTime", "=", "System", ".", "currentTim...
Establishes a thread that on one second intervals reports the number of remaining WorkBlocks enqueued and the total number of lines written and reported by consumers
[ "Establishes", "a", "thread", "that", "on", "one", "second", "intervals", "reports", "the", "number", "of", "remaining", "WorkBlocks", "enqueued", "and", "the", "total", "number", "of", "lines", "written", "and", "reported", "by", "consumers" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java#L126-L159
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java
JettyManager.prepareServer
public void prepareServer() { try { server = new Server(0); jettyHandler = new AbstractHandler() { public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); String[] operands = request.getRequestURI().split("/"); String name = ""; String command = ""; String value = ""; //operands[0] = "", request starts with a "/" if (operands.length >= 2) { name = operands[1]; } if (operands.length >= 3) { command = operands[2]; } if (operands.length >= 4) { value = operands[3]; } if (command.equals("report")) { //report a number of lines written response.getWriter().write(makeReport(name, value)); } else if (command.equals("request") && value.equals("block")) { //request a new block of work response.getWriter().write(requestBlock(name)); } else if (command.equals("request") && value.equals("name")) { //request a new name to report with response.getWriter().write(requestName()); } else { //non recognized response response.getWriter().write("exit"); } ((Request) request).setHandled(true); } }; server.setHandler(jettyHandler); // Select any available port server.start(); Connector[] connectors = server.getConnectors(); NetworkConnector nc = (NetworkConnector) connectors[0]; listeningPort = nc.getLocalPort(); hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { e.printStackTrace(); } }
java
public void prepareServer() { try { server = new Server(0); jettyHandler = new AbstractHandler() { public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); String[] operands = request.getRequestURI().split("/"); String name = ""; String command = ""; String value = ""; //operands[0] = "", request starts with a "/" if (operands.length >= 2) { name = operands[1]; } if (operands.length >= 3) { command = operands[2]; } if (operands.length >= 4) { value = operands[3]; } if (command.equals("report")) { //report a number of lines written response.getWriter().write(makeReport(name, value)); } else if (command.equals("request") && value.equals("block")) { //request a new block of work response.getWriter().write(requestBlock(name)); } else if (command.equals("request") && value.equals("name")) { //request a new name to report with response.getWriter().write(requestName()); } else { //non recognized response response.getWriter().write("exit"); } ((Request) request).setHandled(true); } }; server.setHandler(jettyHandler); // Select any available port server.start(); Connector[] connectors = server.getConnectors(); NetworkConnector nc = (NetworkConnector) connectors[0]; listeningPort = nc.getLocalPort(); hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { e.printStackTrace(); } }
[ "public", "void", "prepareServer", "(", ")", "{", "try", "{", "server", "=", "new", "Server", "(", "0", ")", ";", "jettyHandler", "=", "new", "AbstractHandler", "(", ")", "{", "public", "void", "handle", "(", "String", "target", ",", "Request", "req", ...
Prepares a Jetty server for communicating with consumers.
[ "Prepares", "a", "Jetty", "server", "for", "communicating", "with", "consumers", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java#L164-L217
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java
XmlWriter.getXmlFormatted
public String getXmlFormatted(Map<String, String> dataMap) { StringBuilder sb = new StringBuilder(); for (String var : outTemplate) { sb.append(appendXmlStartTag(var)); sb.append(dataMap.get(var)); sb.append(appendXmlEndingTag(var)); } return sb.toString(); }
java
public String getXmlFormatted(Map<String, String> dataMap) { StringBuilder sb = new StringBuilder(); for (String var : outTemplate) { sb.append(appendXmlStartTag(var)); sb.append(dataMap.get(var)); sb.append(appendXmlEndingTag(var)); } return sb.toString(); }
[ "public", "String", "getXmlFormatted", "(", "Map", "<", "String", ",", "String", ">", "dataMap", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "var", ":", "outTemplate", ")", "{", "sb", ".", "append", ...
Given an array of variable names, returns an Xml String of values. @param dataMap an map containing variable names and their corresponding values names. @param dataMap @return values in Xml format
[ "Given", "an", "array", "of", "variable", "names", "returns", "an", "Xml", "String", "of", "values", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java#L91-L99
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java
XmlWriter.appendXmlStartTag
private String appendXmlStartTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("<").append(value).append(">"); return sb.toString(); }
java
private String appendXmlStartTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("<").append(value).append(">"); return sb.toString(); }
[ "private", "String", "appendXmlStartTag", "(", "String", "value", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"<\"", ")", ".", "append", "(", "value", ")", ".", "append", "(", "\">\"", ")", "...
Helper xml start tag writer @param value the output stream to use in writing
[ "Helper", "xml", "start", "tag", "writer" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java#L106-L111
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java
XmlWriter.appendXmlEndingTag
private String appendXmlEndingTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("</").append(value).append(">"); return sb.toString(); }
java
private String appendXmlEndingTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("</").append(value).append(">"); return sb.toString(); }
[ "private", "String", "appendXmlEndingTag", "(", "String", "value", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"</\"", ")", ".", "append", "(", "value", ")", ".", "append", "(", "\">\"", ")", ...
Helper xml end tag writer @param value the output stream to use in writing
[ "Helper", "xml", "end", "tag", "writer" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/writer/XmlWriter.java#L118-L123
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java
SCXMLEngine.fillInitialVariables
private Map<String, String> fillInitialVariables() { Map<String, TransitionTarget> targets = model.getChildren(); Set<String> variables = new HashSet<>(); for (TransitionTarget target : targets.values()) { OnEntry entry = target.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { if (action instanceof Assign) { String variable = ((Assign) action).getName(); variables.add(variable); } else if (action instanceof SetAssignExtension.SetAssignTag) { String variable = ((SetAssignExtension.SetAssignTag) action).getName(); variables.add(variable); } } } Map<String, String> result = new HashMap<>(); for (String variable : variables) { result.put(variable, ""); } return result; }
java
private Map<String, String> fillInitialVariables() { Map<String, TransitionTarget> targets = model.getChildren(); Set<String> variables = new HashSet<>(); for (TransitionTarget target : targets.values()) { OnEntry entry = target.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { if (action instanceof Assign) { String variable = ((Assign) action).getName(); variables.add(variable); } else if (action instanceof SetAssignExtension.SetAssignTag) { String variable = ((SetAssignExtension.SetAssignTag) action).getName(); variables.add(variable); } } } Map<String, String> result = new HashMap<>(); for (String variable : variables) { result.put(variable, ""); } return result; }
[ "private", "Map", "<", "String", ",", "String", ">", "fillInitialVariables", "(", ")", "{", "Map", "<", "String", ",", "TransitionTarget", ">", "targets", "=", "model", ".", "getChildren", "(", ")", ";", "Set", "<", "String", ">", "variables", "=", "new"...
Searches the model for all variable assignments and makes a default map of those variables, setting them to "" @return the default variable assignment map
[ "Searches", "the", "model", "for", "all", "variable", "assignments", "and", "makes", "a", "default", "map", "of", "those", "variables", "setting", "them", "to" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java#L102-L126
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java
SCXMLEngine.bfs
public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); } } } } return bootStrap; }
java
public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); } } } } return bootStrap; }
[ "public", "List", "<", "PossibleState", ">", "bfs", "(", "int", "min", ")", "throws", "ModelException", "{", "List", "<", "PossibleState", ">", "bootStrap", "=", "new", "LinkedList", "<>", "(", ")", ";", "TransitionTarget", "initial", "=", "model", ".", "g...
Performs a partial BFS on model until the search frontier reaches the desired bootstrap size @param min the desired bootstrap size @return a list of found PossibleState @throws ModelException if the desired bootstrap can not be reached
[ "Performs", "a", "partial", "BFS", "on", "model", "until", "the", "search", "frontier", "reaches", "the", "desired", "bootstrap", "size" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java#L135-L205
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java
SCXMLEngine.process
public void process(SearchDistributor distributor) { List<PossibleState> bootStrap; try { bootStrap = bfs(bootStrapMin); } catch (ModelException e) { bootStrap = new LinkedList<>(); } List<Frontier> frontiers = new LinkedList<>(); for (PossibleState p : bootStrap) { SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList); frontiers.add(dge); } distributor.distribute(frontiers); }
java
public void process(SearchDistributor distributor) { List<PossibleState> bootStrap; try { bootStrap = bfs(bootStrapMin); } catch (ModelException e) { bootStrap = new LinkedList<>(); } List<Frontier> frontiers = new LinkedList<>(); for (PossibleState p : bootStrap) { SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList); frontiers.add(dge); } distributor.distribute(frontiers); }
[ "public", "void", "process", "(", "SearchDistributor", "distributor", ")", "{", "List", "<", "PossibleState", ">", "bootStrap", ";", "try", "{", "bootStrap", "=", "bfs", "(", "bootStrapMin", ")", ";", "}", "catch", "(", "ModelException", "e", ")", "{", "bo...
Performs the BFS and gives the results to a distributor to distribute @param distributor the distributor
[ "Performs", "the", "BFS", "and", "gives", "the", "results", "to", "a", "distributor", "to", "distribute" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java#L212-L227
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java
SCXMLEngine.setModelByInputFileStream
public void setModelByInputFileStream(InputStream inputFileStream) { try { this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
java
public void setModelByInputFileStream(InputStream inputFileStream) { try { this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
[ "public", "void", "setModelByInputFileStream", "(", "InputStream", "inputFileStream", ")", "{", "try", "{", "this", ".", "model", "=", "SCXMLParser", ".", "parse", "(", "new", "InputSource", "(", "inputFileStream", ")", ",", "null", ",", "customActionsFromTagExten...
Sets the SCXML model with an InputStream @param inputFileStream the model input stream
[ "Sets", "the", "SCXML", "model", "with", "an", "InputStream" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java#L248-L255
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java
SCXMLEngine.setModelByText
public void setModelByText(String model) { try { InputStream is = new ByteArrayInputStream(model.getBytes()); this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
java
public void setModelByText(String model) { try { InputStream is = new ByteArrayInputStream(model.getBytes()); this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
[ "public", "void", "setModelByText", "(", "String", "model", ")", "{", "try", "{", "InputStream", "is", "=", "new", "ByteArrayInputStream", "(", "model", ".", "getBytes", "(", ")", ")", ";", "this", ".", "model", "=", "SCXMLParser", ".", "parse", "(", "ne...
Sets the SCXML model with a string @param model the model text
[ "Sets", "the", "SCXML", "model", "with", "a", "string" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLEngine.java#L262-L270
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java
NWiseExtension.makeNWiseTuples
public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) { List<Set<String>> completeTuples = new ArrayList<>(); makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise); return completeTuples; }
java
public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) { List<Set<String>> completeTuples = new ArrayList<>(); makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise); return completeTuples; }
[ "public", "List", "<", "Set", "<", "String", ">", ">", "makeNWiseTuples", "(", "String", "[", "]", "variables", ",", "int", "nWise", ")", "{", "List", "<", "Set", "<", "String", ">>", "completeTuples", "=", "new", "ArrayList", "<>", "(", ")", ";", "m...
Produces all tuples of size n chosen from a list of variable names @param variables the list of variable names to make tuples of @param nWise the size of the desired tuples @return all tuples of size nWise
[ "Produces", "all", "tuples", "of", "size", "n", "chosen", "from", "a", "list", "of", "variable", "names" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java#L73-L78
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java
NWiseExtension.produceNWise
public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) { List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise); List<Map<String, String>> testCases = new ArrayList<>(); for (Set<String> tuple : tuples) { testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains)); } return testCases; }
java
public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) { List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise); List<Map<String, String>> testCases = new ArrayList<>(); for (Set<String> tuple : tuples) { testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains)); } return testCases; }
[ "public", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "produceNWise", "(", "int", "nWise", ",", "String", "[", "]", "coVariables", ",", "Map", "<", "String", ",", "String", "[", "]", ">", "variableDomains", ")", "{", "List", "<", "Set...
Finds all nWise combinations of a set of variables, each with a given domain of values @param nWise the number of variables in each combination @param coVariables the varisbles @param variableDomains the domains @return all nWise combinations of the set of variables
[ "Finds", "all", "nWise", "combinations", "of", "a", "set", "of", "variables", "each", "with", "a", "given", "domain", "of", "values" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java#L119-L128
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java
NWiseExtension.pipelinePossibleStates
public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) { String[] coVariables = action.getCoVariables().split(","); int n = Integer.valueOf(action.getN()); List<Map<String, String>> newPossibleStateList = new ArrayList<>(); for (Map<String, String> possibleState : possibleStateList) { Map<String, String[]> variableDomains = new HashMap<>(); Map<String, String> defaultVariableValues = new HashMap<>(); for (String variable : coVariables) { String variableMetaInfo = possibleState.get(variable); String[] variableDomain = variableMetaInfo.split(","); variableDomains.put(variable, variableDomain); defaultVariableValues.put(variable, variableDomain[0]); } List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains); for (Map<String, String> nWiseCombination : nWiseCombinations) { Map<String, String> newPossibleState = new HashMap<>(possibleState); newPossibleState.putAll(defaultVariableValues); newPossibleState.putAll(nWiseCombination); newPossibleStateList.add(newPossibleState); } } return newPossibleStateList; }
java
public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) { String[] coVariables = action.getCoVariables().split(","); int n = Integer.valueOf(action.getN()); List<Map<String, String>> newPossibleStateList = new ArrayList<>(); for (Map<String, String> possibleState : possibleStateList) { Map<String, String[]> variableDomains = new HashMap<>(); Map<String, String> defaultVariableValues = new HashMap<>(); for (String variable : coVariables) { String variableMetaInfo = possibleState.get(variable); String[] variableDomain = variableMetaInfo.split(","); variableDomains.put(variable, variableDomain); defaultVariableValues.put(variable, variableDomain[0]); } List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains); for (Map<String, String> nWiseCombination : nWiseCombinations) { Map<String, String> newPossibleState = new HashMap<>(possibleState); newPossibleState.putAll(defaultVariableValues); newPossibleState.putAll(nWiseCombination); newPossibleStateList.add(newPossibleState); } } return newPossibleStateList; }
[ "public", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "pipelinePossibleStates", "(", "NWiseAction", "action", ",", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "possibleStateList", ")", "{", "String", "[", "]", "coVariables",...
Uses current variable assignments and info in an NWiseActionTag to expand on an n wise combinatorial set @param action an NWiseAction Action @param possibleStateList a current list of possible states produced so far from expanding a model state @return every input possible state expanded on an n wise combinatorial set defined by that input possible state
[ "Uses", "current", "variable", "assignments", "and", "info", "in", "an", "NWiseActionTag", "to", "expand", "on", "an", "n", "wise", "combinatorial", "set" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/NWiseExtension.java#L137-L163
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/transformer/SampleMachineTransformer.java
SampleMachineTransformer.transform
public void transform(DataPipe cr) { Map<String, String> map = cr.getDataMap(); for (String key : map.keySet()) { String value = map.get(key); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); map.put(key, String.valueOf(ran)); } else if (value.equals("#{divideBy2}")) { String i = map.get("var_out_V3"); String result = String.valueOf(Integer.valueOf(i) / 2); map.put(key, result); } } }
java
public void transform(DataPipe cr) { Map<String, String> map = cr.getDataMap(); for (String key : map.keySet()) { String value = map.get(key); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); map.put(key, String.valueOf(ran)); } else if (value.equals("#{divideBy2}")) { String i = map.get("var_out_V3"); String result = String.valueOf(Integer.valueOf(i) / 2); map.put(key, result); } } }
[ "public", "void", "transform", "(", "DataPipe", "cr", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "cr", ".", "getDataMap", "(", ")", ";", "for", "(", "String", "key", ":", "map", ".", "keySet", "(", ")", ")", "{", "String", "v...
Replace known tags in the current data values with actual values as appropriate @param cr a reference to DataPipe from which to read the current map
[ "Replace", "known", "tags", "in", "the", "current", "data", "values", "with", "actual", "values", "as", "appropriate" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/transformer/SampleMachineTransformer.java#L38-L54
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/distributor/multithreaded/QueueResultsProcessing.java
QueueResultsProcessing.processOutput
@Override public void processOutput(Map<String, String> resultsMap) { queue.add(resultsMap); if (queue.size() > 10000) { log.info("Queue size " + queue.size() + ", waiting"); try { Thread.sleep(500); } catch (InterruptedException ex) { log.info("Interrupted ", ex); } } }
java
@Override public void processOutput(Map<String, String> resultsMap) { queue.add(resultsMap); if (queue.size() > 10000) { log.info("Queue size " + queue.size() + ", waiting"); try { Thread.sleep(500); } catch (InterruptedException ex) { log.info("Interrupted ", ex); } } }
[ "@", "Override", "public", "void", "processOutput", "(", "Map", "<", "String", ",", "String", ">", "resultsMap", ")", "{", "queue", ".", "add", "(", "resultsMap", ")", ";", "if", "(", "queue", ".", "size", "(", ")", ">", "10000", ")", "{", "log", "...
Stores the output from a Frontier into the queue, pausing and waiting if the given queue is too large @param resultsMap map of String and String representing the output of a Frontier's DFS
[ "Stores", "the", "output", "from", "a", "Frontier", "into", "the", "queue", "pausing", "and", "waiting", "if", "the", "given", "queue", "is", "too", "large" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/distributor/multithreaded/QueueResultsProcessing.java#L49-L61
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/consumer/ContextWriter.java
ContextWriter.writeOutput
public void writeOutput(DataPipe cr) { try { context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate))); } catch (Exception e) { throw new RuntimeException("Exception occurred while writing to Context", e); } }
java
public void writeOutput(DataPipe cr) { try { context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate))); } catch (Exception e) { throw new RuntimeException("Exception occurred while writing to Context", e); } }
[ "public", "void", "writeOutput", "(", "DataPipe", "cr", ")", "{", "try", "{", "context", ".", "write", "(", "NullWritable", ".", "get", "(", ")", ",", "new", "Text", "(", "cr", ".", "getPipeDelimited", "(", "outTemplate", ")", ")", ")", ";", "}", "ca...
Write to a context. Uses NullWritable for key so that only value of output string is ultimately written @param cr the DataPipe to write to
[ "Write", "to", "a", "context", ".", "Uses", "NullWritable", "for", "key", "so", "that", "only", "value", "of", "output", "string", "is", "ultimately", "written" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/consumer/ContextWriter.java#L49-L55
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java
SCXMLGapper.decompose
public Map<String, String> decompose(Frontier frontier, String modelText) { if (!(frontier instanceof SCXMLFrontier)) { return null; } TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState; Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables; Map<String, String> decomposition = new HashMap<String, String>(); decomposition.put("target", target.getId()); StringBuilder packedVariables = new StringBuilder(); for (Map.Entry<String, String> variable : variables.entrySet()) { packedVariables.append(variable.getKey()); packedVariables.append("::"); packedVariables.append(variable.getValue()); packedVariables.append(";"); } decomposition.put("variables", packedVariables.toString()); decomposition.put("model", modelText); return decomposition; }
java
public Map<String, String> decompose(Frontier frontier, String modelText) { if (!(frontier instanceof SCXMLFrontier)) { return null; } TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState; Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables; Map<String, String> decomposition = new HashMap<String, String>(); decomposition.put("target", target.getId()); StringBuilder packedVariables = new StringBuilder(); for (Map.Entry<String, String> variable : variables.entrySet()) { packedVariables.append(variable.getKey()); packedVariables.append("::"); packedVariables.append(variable.getValue()); packedVariables.append(";"); } decomposition.put("variables", packedVariables.toString()); decomposition.put("model", modelText); return decomposition; }
[ "public", "Map", "<", "String", ",", "String", ">", "decompose", "(", "Frontier", "frontier", ",", "String", "modelText", ")", "{", "if", "(", "!", "(", "frontier", "instanceof", "SCXMLFrontier", ")", ")", "{", "return", "null", ";", "}", "TransitionTarget...
Takes a model and an SCXMLFrontier and decomposes the Frontier into a Map of Strings to Strings These strings can be sent over a network to get a Frontier past a 'gap' @param frontier the Frontier @param modelText the model @return the map of strings representing a decomposition
[ "Takes", "a", "model", "and", "an", "SCXMLFrontier", "and", "decomposes", "the", "Frontier", "into", "a", "Map", "of", "Strings", "to", "Strings", "These", "strings", "can", "be", "sent", "over", "a", "network", "to", "get", "a", "Frontier", "past", "a", ...
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java#L75-L98
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/CmdLine.java
CmdLine.printHelp
public static void printHelp(final Options options) { Collection<Option> c = options.getOptions(); System.out.println("Command line options are:"); int longestLongOption = 0; for (Option op : c) { if (op.getLongOpt().length() > longestLongOption) { longestLongOption = op.getLongOpt().length(); } } longestLongOption += 2; String spaces = StringUtils.repeat(" ", longestLongOption); for (Option op : c) { System.out.print("\t-" + op.getOpt() + " --" + op.getLongOpt()); if (op.getLongOpt().length() < spaces.length()) { System.out.print(spaces.substring(op.getLongOpt().length())); } else { System.out.print(" "); } System.out.println(op.getDescription()); } }
java
public static void printHelp(final Options options) { Collection<Option> c = options.getOptions(); System.out.println("Command line options are:"); int longestLongOption = 0; for (Option op : c) { if (op.getLongOpt().length() > longestLongOption) { longestLongOption = op.getLongOpt().length(); } } longestLongOption += 2; String spaces = StringUtils.repeat(" ", longestLongOption); for (Option op : c) { System.out.print("\t-" + op.getOpt() + " --" + op.getLongOpt()); if (op.getLongOpt().length() < spaces.length()) { System.out.print(spaces.substring(op.getLongOpt().length())); } else { System.out.print(" "); } System.out.println(op.getDescription()); } }
[ "public", "static", "void", "printHelp", "(", "final", "Options", "options", ")", "{", "Collection", "<", "Option", ">", "c", "=", "options", ".", "getOptions", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"Command line options are:\"", ")", ...
Prints the help on the command line @param options Options object from commons-cli
[ "Prints", "the", "help", "on", "the", "command", "line" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/CmdLine.java#L62-L84
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/CmdLine.java
CmdLine.main
public static void main(String[] args) { CmdLine cmd = new CmdLine(); Configuration conf = new Configuration(); int res = 0; try { res = ToolRunner.run(conf, cmd, args); } catch (Exception e) { System.err.println("Error while running MR job"); e.printStackTrace(); } System.exit(res); }
java
public static void main(String[] args) { CmdLine cmd = new CmdLine(); Configuration conf = new Configuration(); int res = 0; try { res = ToolRunner.run(conf, cmd, args); } catch (Exception e) { System.err.println("Error while running MR job"); e.printStackTrace(); } System.exit(res); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "CmdLine", "cmd", "=", "new", "CmdLine", "(", ")", ";", "Configuration", "conf", "=", "new", "Configuration", "(", ")", ";", "int", "res", "=", "0", ";", "try", "{", "re...
Entry point for this example Uses HDFS ToolRunner to wrap processing of @param args Command-line arguments for HDFS example
[ "Entry", "point", "for", "this", "example", "Uses", "HDFS", "ToolRunner", "to", "wrap", "processing", "of" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/CmdLine.java#L184-L195
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/Helpers/ScalaInJavaHelper.java
ScalaInJavaHelper.linkedListToScalaIterable
public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) { return JavaConverters.asScalaIterableConverter(linkedList).asScala(); }
java
public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) { return JavaConverters.asScalaIterableConverter(linkedList).asScala(); }
[ "public", "static", "scala", ".", "collection", ".", "Iterable", "linkedListToScalaIterable", "(", "LinkedList", "<", "?", ">", "linkedList", ")", "{", "return", "JavaConverters", ".", "asScalaIterableConverter", "(", "linkedList", ")", ".", "asScala", "(", ")", ...
Convert a Java LinkedList to a Scala Iterable. @param linkedList Java LinkedList to convert @return Scala Iterable
[ "Convert", "a", "Java", "LinkedList", "to", "a", "Scala", "Iterable", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/Helpers/ScalaInJavaHelper.java#L36-L38
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/Helpers/ScalaInJavaHelper.java
ScalaInJavaHelper.flattenOption
public static <T> T flattenOption(scala.Option<T> option) { if (option.isEmpty()) { return null; } else { return option.get(); } }
java
public static <T> T flattenOption(scala.Option<T> option) { if (option.isEmpty()) { return null; } else { return option.get(); } }
[ "public", "static", "<", "T", ">", "T", "flattenOption", "(", "scala", ".", "Option", "<", "T", ">", "option", ")", "{", "if", "(", "option", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "option", ".", "g...
Flattens an option into its value or else null, which is not great but is usually more convenient in Java. @param option Optional value -- either Some(T) or None @param <T> Any type @return The value inside the option, or else null
[ "Flattens", "an", "option", "into", "its", "value", "or", "else", "null", "which", "is", "not", "great", "but", "is", "usually", "more", "convenient", "in", "Java", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/Helpers/ScalaInJavaHelper.java#L46-L52
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/SingleValueAssignExtension.java
SingleValueAssignExtension.pipelinePossibleStates
public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) { for (Map<String, String> possibleState : possibleStateList) { possibleState.put(action.getName(), action.getExpr()); } return possibleStateList; }
java
public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) { for (Map<String, String> possibleState : possibleStateList) { possibleState.put(action.getName(), action.getExpr()); } return possibleStateList; }
[ "public", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "pipelinePossibleStates", "(", "Assign", "action", ",", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "possibleStateList", ")", "{", "for", "(", "Map", "<", "String", "...
Assigns one variable to one value @param action an Assign Action @param possibleStateList a current list of possible states produced so far from expanding a model state @return the same list, with every possible state augmented with an assigned variable, defined by action
[ "Assigns", "one", "variable", "to", "one", "value" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/SingleValueAssignExtension.java#L49-L55
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/writer/JsonWriter.java
JsonWriter.getJsonFormatted
public JSONObject getJsonFormatted(Map<String, String> dataMap) { JSONObject oneRowJson = new JSONObject(); for (int i = 0; i < outTemplate.length; i++) { oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i])); } return oneRowJson; }
java
public JSONObject getJsonFormatted(Map<String, String> dataMap) { JSONObject oneRowJson = new JSONObject(); for (int i = 0; i < outTemplate.length; i++) { oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i])); } return oneRowJson; }
[ "public", "JSONObject", "getJsonFormatted", "(", "Map", "<", "String", ",", "String", ">", "dataMap", ")", "{", "JSONObject", "oneRowJson", "=", "new", "JSONObject", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "outTemplate", ".", "l...
Given an array of variable names, returns a JsonObject of values. @param dataMap an map containing variable names and their corresponding values names. @return a json object of values
[ "Given", "an", "array", "of", "variable", "names", "returns", "a", "JsonObject", "of", "values", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/writer/JsonWriter.java#L80-L89
train
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkStructureBuilder.java
SocialNetworkStructureBuilder.generateAllNodeDataTypeGraphCombinationsOfMaxLength
public Vector<Graph<UserStub>> generateAllNodeDataTypeGraphCombinationsOfMaxLength(int length) { Vector<Graph<UserStub>> graphs = super.generateAllNodeDataTypeGraphCombinationsOfMaxLength(length); if (WRITE_STRUCTURES_IN_PARALLEL) { // Left as an exercise to the student. throw new NotImplementedError(); } else { int i = 0; for (Iterator<Graph<UserStub>> iter = graphs.toIterator(); iter.hasNext();) { Graph<UserStub> graph = iter.next(); graph.setGraphId("S_" + ++i + "_" + graph.allNodes().size()); graph.writeDotFile(outDir + graph.graphId() + ".gv", false, ALSO_WRITE_AS_PNG); } System.out.println("Wrote " + i + " graph files in DOT format to " + outDir + ""); } return graphs; }
java
public Vector<Graph<UserStub>> generateAllNodeDataTypeGraphCombinationsOfMaxLength(int length) { Vector<Graph<UserStub>> graphs = super.generateAllNodeDataTypeGraphCombinationsOfMaxLength(length); if (WRITE_STRUCTURES_IN_PARALLEL) { // Left as an exercise to the student. throw new NotImplementedError(); } else { int i = 0; for (Iterator<Graph<UserStub>> iter = graphs.toIterator(); iter.hasNext();) { Graph<UserStub> graph = iter.next(); graph.setGraphId("S_" + ++i + "_" + graph.allNodes().size()); graph.writeDotFile(outDir + graph.graphId() + ".gv", false, ALSO_WRITE_AS_PNG); } System.out.println("Wrote " + i + " graph files in DOT format to " + outDir + ""); } return graphs; }
[ "public", "Vector", "<", "Graph", "<", "UserStub", ">", ">", "generateAllNodeDataTypeGraphCombinationsOfMaxLength", "(", "int", "length", ")", "{", "Vector", "<", "Graph", "<", "UserStub", ">>", "graphs", "=", "super", ".", "generateAllNodeDataTypeGraphCombinationsOfM...
Build all combinations of graph structures for generic event stubs of a maximum length @param length Maximum number of nodes in each to generate @return All graph combinations of specified length or less
[ "Build", "all", "combinations", "of", "graph", "structures", "for", "generic", "event", "stubs", "of", "a", "maximum", "length" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkStructureBuilder.java#L66-L83
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java
DataConsumer.consume
public int consume(Map<String, String> initialVars) { this.dataPipe = new DataPipe(this); // Set initial variables for (Map.Entry<String, String> ent : initialVars.entrySet()) { dataPipe.getDataMap().put(ent.getKey(), ent.getValue()); } // Call transformers for (DataTransformer dc : dataTransformers) { dc.transform(dataPipe); } // Call writers for (DataWriter oneOw : dataWriters) { try { oneOw.writeOutput(dataPipe); } catch (Exception e) { //NOPMD log.error("Exception in DataWriter", e); } } return 1; }
java
public int consume(Map<String, String> initialVars) { this.dataPipe = new DataPipe(this); // Set initial variables for (Map.Entry<String, String> ent : initialVars.entrySet()) { dataPipe.getDataMap().put(ent.getKey(), ent.getValue()); } // Call transformers for (DataTransformer dc : dataTransformers) { dc.transform(dataPipe); } // Call writers for (DataWriter oneOw : dataWriters) { try { oneOw.writeOutput(dataPipe); } catch (Exception e) { //NOPMD log.error("Exception in DataWriter", e); } } return 1; }
[ "public", "int", "consume", "(", "Map", "<", "String", ",", "String", ">", "initialVars", ")", "{", "this", ".", "dataPipe", "=", "new", "DataPipe", "(", "this", ")", ";", "// Set initial variables\r", "for", "(", "Map", ".", "Entry", "<", "String", ",",...
Consumes a produced result. Calls every transformer in sequence, then calls every dataWriter in sequence. @param initialVars a map containing the initial variables assignments @return the number of lines written
[ "Consumes", "a", "produced", "result", ".", "Calls", "every", "transformer", "in", "sequence", "then", "calls", "every", "dataWriter", "in", "sequence", "." ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java#L138-L161
train
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java
DataConsumer.sendRequest
public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) { return threadPool.submit(new Callable<String>() { @Override public String call() { String response = getResponse(path); if (reportingHandler != null) { reportingHandler.handleResponse(response); } return response; } }); }
java
public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) { return threadPool.submit(new Callable<String>() { @Override public String call() { String response = getResponse(path); if (reportingHandler != null) { reportingHandler.handleResponse(response); } return response; } }); }
[ "public", "Future", "<", "String", ">", "sendRequest", "(", "final", "String", "path", ",", "final", "ReportingHandler", "reportingHandler", ")", "{", "return", "threadPool", ".", "submit", "(", "new", "Callable", "<", "String", ">", "(", ")", "{", "@", "O...
Creates a future that will send a request to the reporting host and call the handler with the response @param path the path at the reporting host which the request will be made @param reportingHandler the handler to receive the response once executed and recieved @return a {@link java.util.concurrent.Future} for handing the request
[ "Creates", "a", "future", "that", "will", "send", "a", "request", "to", "the", "reporting", "host", "and", "call", "the", "handler", "with", "the", "response" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java#L211-L224
train
FINRAOS/DataGenerator
dg-example-default/src/main/java/org/finra/datagenerator/samples/transformer/SampleMachineTransformer.java
SampleMachineTransformer.transform
public void transform(DataPipe cr) { for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { String value = entry.getValue(); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); entry.setValue(String.valueOf(ran)); } } }
java
public void transform(DataPipe cr) { for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { String value = entry.getValue(); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); entry.setValue(String.valueOf(ran)); } } }
[ "public", "void", "transform", "(", "DataPipe", "cr", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "cr", ".", "getDataMap", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "value", "=", "entry...
The transform method for this DataTransformer @param cr a reference to DataPipe from which to read the current map
[ "The", "transform", "method", "for", "this", "DataTransformer" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-default/src/main/java/org/finra/datagenerator/samples/transformer/SampleMachineTransformer.java#L38-L48
train
FINRAOS/DataGenerator
dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/consumer/SampleMachineConsumer.java
SampleMachineConsumer.isExit
public boolean isExit() { if (currentRow > finalRow) { //request new block of work String newBlock = this.sendRequestSync("this/request/block"); LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0); if (newBlock.contains("exit")) { getExitFlag().set(true); makeReport(true); return true; } else { block.buildFromResponse(newBlock); } currentRow = block.getStart(); finalRow = block.getStop(); } else { //report the number of lines written makeReport(false); if (exit.get()) { getExitFlag().set(true); return true; } } return false; }
java
public boolean isExit() { if (currentRow > finalRow) { //request new block of work String newBlock = this.sendRequestSync("this/request/block"); LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0); if (newBlock.contains("exit")) { getExitFlag().set(true); makeReport(true); return true; } else { block.buildFromResponse(newBlock); } currentRow = block.getStart(); finalRow = block.getStop(); } else { //report the number of lines written makeReport(false); if (exit.get()) { getExitFlag().set(true); return true; } } return false; }
[ "public", "boolean", "isExit", "(", ")", "{", "if", "(", "currentRow", ">", "finalRow", ")", "{", "//request new block of work", "String", "newBlock", "=", "this", ".", "sendRequestSync", "(", "\"this/request/block\"", ")", ";", "LineCountManager", ".", "LineCount...
Exit reporting up to distributor, using information gained from status reports to the LineCountManager @return a boolean of whether this consumer should immediately exit
[ "Exit", "reporting", "up", "to", "distributor", "using", "information", "gained", "from", "status", "reports", "to", "the", "LineCountManager" ]
1f69f949401cbed4db4f553c3eb8350832c4d45a
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/consumer/SampleMachineConsumer.java#L101-L126
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java
CountrySpinnerAdapter.getDropDownView
@Override public View getDropDownView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false); viewHolder = new ViewHolder(); viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image); viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name); viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Country country = getItem(position); viewHolder.mImageView.setImageResource(getFlagResource(country)); viewHolder.mNameView.setText(country.getName()); viewHolder.mDialCode.setText(String.format("+%s", country.getDialCode())); return convertView; }
java
@Override public View getDropDownView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false); viewHolder = new ViewHolder(); viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image); viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name); viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Country country = getItem(position); viewHolder.mImageView.setImageResource(getFlagResource(country)); viewHolder.mNameView.setText(country.getName()); viewHolder.mDialCode.setText(String.format("+%s", country.getDialCode())); return convertView; }
[ "@", "Override", "public", "View", "getDropDownView", "(", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "final", "ViewHolder", "viewHolder", ";", "if", "(", "convertView", "==", "null", ")", "{", "convertView", "=", "m...
Drop down item view @param position position of item @param convertView View of item @param parent parent view of item's view @return covertView
[ "Drop", "down", "item", "view" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java#L32-L51
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java
CountrySpinnerAdapter.getView
@Override public View getView(int position, View convertView, ViewGroup parent) { Country country = getItem(position); if (convertView == null) { convertView = new ImageView(getContext()); } ((ImageView) convertView).setImageResource(getFlagResource(country)); return convertView; }
java
@Override public View getView(int position, View convertView, ViewGroup parent) { Country country = getItem(position); if (convertView == null) { convertView = new ImageView(getContext()); } ((ImageView) convertView).setImageResource(getFlagResource(country)); return convertView; }
[ "@", "Override", "public", "View", "getView", "(", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "Country", "country", "=", "getItem", "(", "position", ")", ";", "if", "(", "convertView", "==", "null", ")", "{", "co...
Drop down selected view @param position position of selected item @param convertView View of selected item @param parent parent of selected view @return convertView
[ "Drop", "down", "selected", "view" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java#L61-L72
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java
CountrySpinnerAdapter.getFlagResource
private int getFlagResource(Country country) { return getContext().getResources().getIdentifier("country_" + country.getIso().toLowerCase(), "drawable", getContext().getPackageName()); }
java
private int getFlagResource(Country country) { return getContext().getResources().getIdentifier("country_" + country.getIso().toLowerCase(), "drawable", getContext().getPackageName()); }
[ "private", "int", "getFlagResource", "(", "Country", "country", ")", "{", "return", "getContext", "(", ")", ".", "getResources", "(", ")", ".", "getIdentifier", "(", "\"country_\"", "+", "country", ".", "getIso", "(", ")", ".", "toLowerCase", "(", ")", ","...
Fetch flag resource by Country @param country Country @return int of resource | 0 value if not exists
[ "Fetch", "flag", "resource", "by", "Country" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountrySpinnerAdapter.java#L80-L82
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountriesFetcher.java
CountriesFetcher.getJsonFromRaw
private static String getJsonFromRaw(Context context, int resource) { String json; try { InputStream inputStream = context.getResources().openRawResource(resource); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
java
private static String getJsonFromRaw(Context context, int resource) { String json; try { InputStream inputStream = context.getResources().openRawResource(resource); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
[ "private", "static", "String", "getJsonFromRaw", "(", "Context", "context", ",", "int", "resource", ")", "{", "String", "json", ";", "try", "{", "InputStream", "inputStream", "=", "context", ".", "getResources", "(", ")", ".", "openRawResource", "(", "resource...
Fetch JSON from RAW resource @param context Context @param resource Resource int of the RAW file @return JSON
[ "Fetch", "JSON", "from", "RAW", "resource" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountriesFetcher.java#L24-L38
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountriesFetcher.java
CountriesFetcher.getCountries
public static CountryList getCountries(Context context) { if (mCountries != null) { return mCountries; } mCountries = new CountryList(); try { JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries)); for (int i = 0; i < countries.length(); i++) { try { JSONObject country = (JSONObject) countries.get(i); mCountries.add(new Country(country.getString("name"), country.getString("iso2"), country.getInt("dialCode"))); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } return mCountries; }
java
public static CountryList getCountries(Context context) { if (mCountries != null) { return mCountries; } mCountries = new CountryList(); try { JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries)); for (int i = 0; i < countries.length(); i++) { try { JSONObject country = (JSONObject) countries.get(i); mCountries.add(new Country(country.getString("name"), country.getString("iso2"), country.getInt("dialCode"))); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } return mCountries; }
[ "public", "static", "CountryList", "getCountries", "(", "Context", "context", ")", "{", "if", "(", "mCountries", "!=", "null", ")", "{", "return", "mCountries", ";", "}", "mCountries", "=", "new", "CountryList", "(", ")", ";", "try", "{", "JSONArray", "cou...
Import CountryList from RAW resource @param context Context @return CountryList
[ "Import", "CountryList", "from", "RAW", "resource" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/CountriesFetcher.java#L46-L65
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.init
private void init(AttributeSet attrs) { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); mCountrySpinner.setAdapter(mCountrySpinnerAdapter); mCountries = CountriesFetcher.getCountries(getContext()); mCountrySpinnerAdapter.addAll(mCountries); mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener); setFlagDefaults(attrs); /** * Phone text field */ mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone); mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher); setDefault(); setEditTextDefaults(attrs); }
java
private void init(AttributeSet attrs) { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); mCountrySpinner.setAdapter(mCountrySpinnerAdapter); mCountries = CountriesFetcher.getCountries(getContext()); mCountrySpinnerAdapter.addAll(mCountries); mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener); setFlagDefaults(attrs); /** * Phone text field */ mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone); mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher); setDefault(); setEditTextDefaults(attrs); }
[ "private", "void", "init", "(", "AttributeSet", "attrs", ")", "{", "inflate", "(", "getContext", "(", ")", ",", "R", ".", "layout", ".", "intl_phone_input", ",", "this", ")", ";", "/**+\n * Country spinner\n */", "mCountrySpinner", "=", "(", "Spi...
Init after constructor
[ "Init", "after", "constructor" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L71-L95
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.hideKeyboard
public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); }
java
public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); }
[ "public", "void", "hideKeyboard", "(", ")", "{", "InputMethodManager", "inputMethodManager", "=", "(", "InputMethodManager", ")", "getContext", "(", ")", ".", "getApplicationContext", "(", ")", ".", "getSystemService", "(", "Context", ".", "INPUT_METHOD_SERVICE", ")...
Hide keyboard from phoneEdit field
[ "Hide", "keyboard", "from", "phoneEdit", "field" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L131-L134
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.setDefault
public void setDefault() { try { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); if (phone != null && !phone.isEmpty()) { this.setNumber(phone); } else { String iso = telephonyManager.getNetworkCountryIso(); setEmptyDefault(iso); } } catch (SecurityException e) { setEmptyDefault(); } }
java
public void setDefault() { try { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); if (phone != null && !phone.isEmpty()) { this.setNumber(phone); } else { String iso = telephonyManager.getNetworkCountryIso(); setEmptyDefault(iso); } } catch (SecurityException e) { setEmptyDefault(); } }
[ "public", "void", "setDefault", "(", ")", "{", "try", "{", "TelephonyManager", "telephonyManager", "=", "(", "TelephonyManager", ")", "getContext", "(", ")", ".", "getSystemService", "(", "Context", ".", "TELEPHONY_SERVICE", ")", ";", "String", "phone", "=", "...
Set default value Will try to retrieve phone number from device
[ "Set", "default", "value", "Will", "try", "to", "retrieve", "phone", "number", "from", "device" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L140-L153
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.setEmptyDefault
public void setEmptyDefault(String iso) { if (iso == null || iso.isEmpty()) { iso = DEFAULT_COUNTRY; } int defaultIdx = mCountries.indexOfIso(iso); mSelectedCountry = mCountries.get(defaultIdx); mCountrySpinner.setSelection(defaultIdx); }
java
public void setEmptyDefault(String iso) { if (iso == null || iso.isEmpty()) { iso = DEFAULT_COUNTRY; } int defaultIdx = mCountries.indexOfIso(iso); mSelectedCountry = mCountries.get(defaultIdx); mCountrySpinner.setSelection(defaultIdx); }
[ "public", "void", "setEmptyDefault", "(", "String", "iso", ")", "{", "if", "(", "iso", "==", "null", "||", "iso", ".", "isEmpty", "(", ")", ")", "{", "iso", "=", "DEFAULT_COUNTRY", ";", "}", "int", "defaultIdx", "=", "mCountries", ".", "indexOfIso", "(...
Set default value with @param iso ISO2 of country
[ "Set", "default", "value", "with" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L160-L167
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.setHint
private void setHint() { if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE); if (phoneNumber != null) { mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); } } }
java
private void setHint() { if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE); if (phoneNumber != null) { mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); } } }
[ "private", "void", "setHint", "(", ")", "{", "if", "(", "mPhoneEdit", "!=", "null", "&&", "mSelectedCountry", "!=", "null", "&&", "mSelectedCountry", ".", "getIso", "(", ")", "!=", "null", ")", "{", "Phonenumber", ".", "PhoneNumber", "phoneNumber", "=", "m...
Set hint number for country
[ "Set", "hint", "number", "for", "country" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L179-L186
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.getPhoneNumber
@SuppressWarnings("unused") public Phonenumber.PhoneNumber getPhoneNumber() { try { String iso = null; if (mSelectedCountry != null) { iso = mSelectedCountry.getIso(); } return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso); } catch (NumberParseException ignored) { return null; } }
java
@SuppressWarnings("unused") public Phonenumber.PhoneNumber getPhoneNumber() { try { String iso = null; if (mSelectedCountry != null) { iso = mSelectedCountry.getIso(); } return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso); } catch (NumberParseException ignored) { return null; } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "Phonenumber", ".", "PhoneNumber", "getPhoneNumber", "(", ")", "{", "try", "{", "String", "iso", "=", "null", ";", "if", "(", "mSelectedCountry", "!=", "null", ")", "{", "iso", "=", "mSelectedCountry...
Get PhoneNumber object @return PhonenUmber | null on error
[ "Get", "PhoneNumber", "object" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L302-L313
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.isValid
@SuppressWarnings("unused") public boolean isValid() { Phonenumber.PhoneNumber phoneNumber = getPhoneNumber(); return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber); }
java
@SuppressWarnings("unused") public boolean isValid() { Phonenumber.PhoneNumber phoneNumber = getPhoneNumber(); return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber); }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "boolean", "isValid", "(", ")", "{", "Phonenumber", ".", "PhoneNumber", "phoneNumber", "=", "getPhoneNumber", "(", ")", ";", "return", "phoneNumber", "!=", "null", "&&", "mPhoneUtil", ".", "isValidNumber...
Check if number is valid @return boolean
[ "Check", "if", "number", "is", "valid" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L330-L334
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.setError
@SuppressWarnings("unused") public void setError(CharSequence error, Drawable icon) { mPhoneEdit.setError(error, icon); }
java
@SuppressWarnings("unused") public void setError(CharSequence error, Drawable icon) { mPhoneEdit.setError(error, icon); }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "void", "setError", "(", "CharSequence", "error", ",", "Drawable", "icon", ")", "{", "mPhoneEdit", ".", "setError", "(", "error", ",", "icon", ")", ";", "}" ]
Sets an error message that will be displayed in a popup when the EditText has focus along with an icon displayed at the right-hand side. @param error error message to show
[ "Sets", "an", "error", "message", "that", "will", "be", "displayed", "in", "a", "popup", "when", "the", "EditText", "has", "focus", "along", "with", "an", "icon", "displayed", "at", "the", "right", "-", "hand", "side", "." ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L373-L376
train
AlmogBaku/IntlPhoneInput
intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java
IntlPhoneInput.setOnKeyboardDone
public void setOnKeyboardDone(final IntlPhoneInputListener listener) { mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { listener.done(IntlPhoneInput.this, isValid()); } return false; } }); }
java
public void setOnKeyboardDone(final IntlPhoneInputListener listener) { mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { listener.done(IntlPhoneInput.this, isValid()); } return false; } }); }
[ "public", "void", "setOnKeyboardDone", "(", "final", "IntlPhoneInputListener", "listener", ")", "{", "mPhoneEdit", ".", "setOnEditorActionListener", "(", "new", "TextView", ".", "OnEditorActionListener", "(", ")", "{", "@", "Override", "public", "boolean", "onEditorAc...
Set keyboard done listener to detect when the user click "DONE" on his keyboard @param listener IntlPhoneInputListener
[ "Set", "keyboard", "done", "listener", "to", "detect", "when", "the", "user", "click", "DONE", "on", "his", "keyboard" ]
ac7313a2d1683feb4d535d5dbee6676b53879059
https://github.com/AlmogBaku/IntlPhoneInput/blob/ac7313a2d1683feb4d535d5dbee6676b53879059/intlphoneinput/src/main/java/net/rimoto/intlphoneinput/IntlPhoneInput.java#L397-L407
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.allocateClient
private synchronized Client allocateClient(int targetPlayer, String description) throws IOException { Client result = openClients.get(targetPlayer); if (result == null) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer); if (deviceAnnouncement == null) { throw new IllegalStateException("Player " + targetPlayer + " could not be found " + description); } final int dbServerPort = getPlayerDBServerPort(targetPlayer); if (dbServerPort < 0) { throw new IllegalStateException("Player " + targetPlayer + " does not have a db server " + description); } final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer); Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort); socket = new Socket(); socket.connect(address, socketTimeout.get()); socket.setSoTimeout(socketTimeout.get()); result = new Client(socket, targetPlayer, posingAsPlayerNumber); } catch (IOException e) { try { socket.close(); } catch (IOException e2) { logger.error("Problem closing socket for failed client creation attempt " + description); } throw e; } openClients.put(targetPlayer, result); useCounts.put(result, 0); } useCounts.put(result, useCounts.get(result) + 1); return result; }
java
private synchronized Client allocateClient(int targetPlayer, String description) throws IOException { Client result = openClients.get(targetPlayer); if (result == null) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer); if (deviceAnnouncement == null) { throw new IllegalStateException("Player " + targetPlayer + " could not be found " + description); } final int dbServerPort = getPlayerDBServerPort(targetPlayer); if (dbServerPort < 0) { throw new IllegalStateException("Player " + targetPlayer + " does not have a db server " + description); } final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer); Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort); socket = new Socket(); socket.connect(address, socketTimeout.get()); socket.setSoTimeout(socketTimeout.get()); result = new Client(socket, targetPlayer, posingAsPlayerNumber); } catch (IOException e) { try { socket.close(); } catch (IOException e2) { logger.error("Problem closing socket for failed client creation attempt " + description); } throw e; } openClients.put(targetPlayer, result); useCounts.put(result, 0); } useCounts.put(result, useCounts.get(result) + 1); return result; }
[ "private", "synchronized", "Client", "allocateClient", "(", "int", "targetPlayer", ",", "String", "description", ")", "throws", "IOException", "{", "Client", "result", "=", "openClients", ".", "get", "(", "targetPlayer", ")", ";", "if", "(", "result", "==", "n...
Finds or opens a client to talk to the dbserver on the specified player, incrementing its use count. @param targetPlayer the player number whose database needs to be interacted with @param description a short description of the task being performed for error reporting if it fails, should be a verb phrase like "requesting track metadata" @return the communication client for talking to that player, or {@code null} if the player could not be found @throws IllegalStateException if we can't find the target player or there is no suitable player number for us to pretend to be @throws IOException if there is a problem communicating
[ "Finds", "or", "opens", "a", "client", "to", "talk", "to", "the", "dbserver", "on", "the", "specified", "player", "incrementing", "its", "use", "count", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L103-L138
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.closeClient
private void closeClient(Client client) { logger.debug("Closing client {}", client); client.close(); openClients.remove(client.targetPlayer); useCounts.remove(client); timestamps.remove(client); }
java
private void closeClient(Client client) { logger.debug("Closing client {}", client); client.close(); openClients.remove(client.targetPlayer); useCounts.remove(client); timestamps.remove(client); }
[ "private", "void", "closeClient", "(", "Client", "client", ")", "{", "logger", ".", "debug", "(", "\"Closing client {}\"", ",", "client", ")", ";", "client", ".", "close", "(", ")", ";", "openClients", ".", "remove", "(", "client", ".", "targetPlayer", ")"...
When it is time to actually close a client, do so, and clean up the related data structures. @param client the client which has been idle for long enough to be closed
[ "When", "it", "is", "time", "to", "actually", "close", "a", "client", "do", "so", "and", "clean", "up", "the", "related", "data", "structures", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L145-L151
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.freeClient
private synchronized void freeClient(Client client) { int current = useCounts.get(client); if (current > 0) { timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now. useCounts.put(client, current - 1); if ((current == 1) && (idleLimit.get() == 0)) { closeClient(client); // This was the last use, and we are supposed to immediately close idle clients. } } else { logger.error("Ignoring attempt to free a client that is not allocated: {}", client); } }
java
private synchronized void freeClient(Client client) { int current = useCounts.get(client); if (current > 0) { timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now. useCounts.put(client, current - 1); if ((current == 1) && (idleLimit.get() == 0)) { closeClient(client); // This was the last use, and we are supposed to immediately close idle clients. } } else { logger.error("Ignoring attempt to free a client that is not allocated: {}", client); } }
[ "private", "synchronized", "void", "freeClient", "(", "Client", "client", ")", "{", "int", "current", "=", "useCounts", ".", "get", "(", "client", ")", ";", "if", "(", "current", ">", "0", ")", "{", "timestamps", ".", "put", "(", "client", ",", "System...
Decrements the client's use count, and makes it eligible for closing if it is no longer in use. @param client the dbserver connection client which is no longer being used for a task
[ "Decrements", "the", "client", "s", "use", "count", "and", "makes", "it", "eligible", "for", "closing", "if", "it", "is", "no", "longer", "in", "use", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L158-L169
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.invokeWithClientSession
public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description) throws Exception { if (!isRunning()) { throw new IllegalStateException("ConnectionManager is not running, aborting " + description); } final Client client = allocateClient(targetPlayer, description); try { return task.useClient(client); } finally { freeClient(client); } }
java
public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description) throws Exception { if (!isRunning()) { throw new IllegalStateException("ConnectionManager is not running, aborting " + description); } final Client client = allocateClient(targetPlayer, description); try { return task.useClient(client); } finally { freeClient(client); } }
[ "public", "<", "T", ">", "T", "invokeWithClientSession", "(", "int", "targetPlayer", ",", "ClientTask", "<", "T", ">", "task", ",", "String", "description", ")", "throws", "Exception", "{", "if", "(", "!", "isRunning", "(", ")", ")", "{", "throw", "new",...
Obtain a dbserver client session that can be used to perform some task, call that task with the client, then release the client. @param targetPlayer the player number whose dbserver we wish to communicate with @param task the activity that will be performed with exclusive access to a dbserver connection @param description a short description of the task being performed for error reporting if it fails, should be a verb phrase like "requesting track metadata" @param <T> the type that will be returned by the task to be performed @return the value returned by the completed task @throws IOException if there is a problem communicating @throws Exception from the underlying {@code task}, if any
[ "Obtain", "a", "dbserver", "client", "session", "that", "can", "be", "used", "to", "perform", "some", "task", "call", "that", "task", "with", "the", "client", "then", "release", "the", "client", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L186-L198
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.getPlayerDBServerPort
@SuppressWarnings("WeakerAccess") public int getPlayerDBServerPort(int player) { ensureRunning(); Integer result = dbServerPorts.get(player); if (result == null) { return -1; } return result; }
java
@SuppressWarnings("WeakerAccess") public int getPlayerDBServerPort(int player) { ensureRunning(); Integer result = dbServerPorts.get(player); if (result == null) { return -1; } return result; }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "int", "getPlayerDBServerPort", "(", "int", "player", ")", "{", "ensureRunning", "(", ")", ";", "Integer", "result", "=", "dbServerPorts", ".", "get", "(", "player", ")", ";", "if", "(", "resul...
Look up the database server port reported by a given player. You should not use this port directly; instead ask this class for a session to use while you communicate with the database. @param player the player number of interest @return the port number on which its database server is running, or -1 if unknown @throws IllegalStateException if not running
[ "Look", "up", "the", "database", "server", "port", "reported", "by", "a", "given", "player", ".", "You", "should", "not", "use", "this", "port", "directly", ";", "instead", "ask", "this", "class", "for", "a", "session", "to", "use", "while", "you", "comm...
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L215-L223
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.requestPlayerDBServerPort
private void requestPlayerDBServerPort(DeviceAnnouncement announcement) { Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT); socket = new Socket(); socket.connect(address, socketTimeout.get()); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); socket.setSoTimeout(socketTimeout.get()); os.write(DB_SERVER_QUERY_PACKET); byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet"); if (response.length == 2) { setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2)); } } catch (java.net.ConnectException ce) { logger.info("Player " + announcement.getNumber() + " doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata."); } catch (Exception e) { logger.warn("Problem requesting database server port number", e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { logger.warn("Problem closing database server port request socket", e); } } } }
java
private void requestPlayerDBServerPort(DeviceAnnouncement announcement) { Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT); socket = new Socket(); socket.connect(address, socketTimeout.get()); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); socket.setSoTimeout(socketTimeout.get()); os.write(DB_SERVER_QUERY_PACKET); byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet"); if (response.length == 2) { setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2)); } } catch (java.net.ConnectException ce) { logger.info("Player " + announcement.getNumber() + " doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata."); } catch (Exception e) { logger.warn("Problem requesting database server port number", e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { logger.warn("Problem closing database server port request socket", e); } } } }
[ "private", "void", "requestPlayerDBServerPort", "(", "DeviceAnnouncement", "announcement", ")", "{", "Socket", "socket", "=", "null", ";", "try", "{", "InetSocketAddress", "address", "=", "new", "InetSocketAddress", "(", "announcement", ".", "getAddress", "(", ")", ...
Query a player to determine the port on which its database server is running. @param announcement the device announcement with which we detected a new player on the network.
[ "Query", "a", "player", "to", "determine", "the", "port", "on", "which", "its", "database", "server", "is", "running", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L274-L302
train
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java
ConnectionManager.receiveBytes
private byte[] receiveBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; int len = (is.read(buffer)); if (len < 1) { throw new IOException("receiveBytes read " + len + " bytes."); } return Arrays.copyOf(buffer, len); }
java
private byte[] receiveBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; int len = (is.read(buffer)); if (len < 1) { throw new IOException("receiveBytes read " + len + " bytes."); } return Arrays.copyOf(buffer, len); }
[ "private", "byte", "[", "]", "receiveBytes", "(", "InputStream", "is", ")", "throws", "IOException", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "8192", "]", ";", "int", "len", "=", "(", "is", ".", "read", "(", "buffer", ")", ")", ";"...
Receive some bytes from the player we are requesting metadata from. @param is the input stream associated with the player metadata socket. @return the bytes read. @throws IOException if there is a problem reading the response
[ "Receive", "some", "bytes", "from", "the", "player", "we", "are", "requesting", "metadata", "from", "." ]
f958a2a70e8a87a31a75326d7b4db77c2f0b4212
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/ConnectionManager.java#L343-L350
train