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
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/BackendUser.java
BackendUser.signUpInBackground
public static Observable<BackendUser> signUpInBackground(String username, String email, String password){ return getAM().signUpASync(new SignUpCredentials(username, email, password)); }
java
public static Observable<BackendUser> signUpInBackground(String username, String email, String password){ return getAM().signUpASync(new SignUpCredentials(username, email, password)); }
[ "public", "static", "Observable", "<", "BackendUser", ">", "signUpInBackground", "(", "String", "username", ",", "String", "email", ",", "String", "password", ")", "{", "return", "getAM", "(", ")", ".", "signUpASync", "(", "new", "SignUpCredentials", "(", "use...
Perform asyncronously sign up attempt. @param username user name user will be identified by. @param email user email address @param password user password @return login results as observable.
[ "Perform", "asyncronously", "sign", "up", "attempt", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/BackendUser.java#L193-L195
train
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/BackendUser.java
BackendUser.signUp
public boolean signUp(){ SignUpCredentials creds = new SignUpCredentials(getUsername(),getEmailAddress(),getPassword()); SignUpResponse response = getAM().signUp(creds); if(response.getStatus().isSuccess()){ this.initFrom(response.get()); return true; } else return false; }
java
public boolean signUp(){ SignUpCredentials creds = new SignUpCredentials(getUsername(),getEmailAddress(),getPassword()); SignUpResponse response = getAM().signUp(creds); if(response.getStatus().isSuccess()){ this.initFrom(response.get()); return true; } else return false; }
[ "public", "boolean", "signUp", "(", ")", "{", "SignUpCredentials", "creds", "=", "new", "SignUpCredentials", "(", "getUsername", "(", ")", ",", "getEmailAddress", "(", ")", ",", "getPassword", "(", ")", ")", ";", "SignUpResponse", "response", "=", "getAM", "...
Synchronously sign up using credentials provided via constructor or setters. @return boolean indicating sign up success
[ "Synchronously", "sign", "up", "using", "credentials", "provided", "via", "constructor", "or", "setters", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/BackendUser.java#L212-L219
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.generateKeyPair
public static KeyPair generateKeyPair(final int keyLen) throws NoSuchAlgorithmException { final String name = ASYM_CIPHER_CHAIN_PADDING; final int offset = name.indexOf('/'); final String alg = ((offset < 0) ? name : name.substring(0, offset)); final KeyPairGenerator generator = KeyPairGenerator.getInstance(alg); generator.initialize(keyLen); return generator.genKeyPair(); }
java
public static KeyPair generateKeyPair(final int keyLen) throws NoSuchAlgorithmException { final String name = ASYM_CIPHER_CHAIN_PADDING; final int offset = name.indexOf('/'); final String alg = ((offset < 0) ? name : name.substring(0, offset)); final KeyPairGenerator generator = KeyPairGenerator.getInstance(alg); generator.initialize(keyLen); return generator.genKeyPair(); }
[ "public", "static", "KeyPair", "generateKeyPair", "(", "final", "int", "keyLen", ")", "throws", "NoSuchAlgorithmException", "{", "final", "String", "name", "=", "ASYM_CIPHER_CHAIN_PADDING", ";", "final", "int", "offset", "=", "name", ".", "indexOf", "(", "'", "'...
Generate RSA KeyPair @param keyLen in bits (2048 recomended) @return @throws NoSuchAlgorithmException
[ "Generate", "RSA", "KeyPair" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L491-L498
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.getByteBuffer
public ByteBuffer getByteBuffer() { final ByteBuffer bb = ByteBuffer.wrap(buf); bb.limit(bufLimit); bb.position(bufPosition); return bb; }
java
public ByteBuffer getByteBuffer() { final ByteBuffer bb = ByteBuffer.wrap(buf); bb.limit(bufLimit); bb.position(bufPosition); return bb; }
[ "public", "ByteBuffer", "getByteBuffer", "(", ")", "{", "final", "ByteBuffer", "bb", "=", "ByteBuffer", ".", "wrap", "(", "buf", ")", ";", "bb", ".", "limit", "(", "bufLimit", ")", ";", "bb", ".", "position", "(", "bufPosition", ")", ";", "return", "bb...
Return internal buffer as ByteBuffer @return
[ "Return", "internal", "buffer", "as", "ByteBuffer" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L505-L510
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.outputBytes
public byte[] outputBytes() { byte[] tmpBuf = buf; int len = bufLimit; int flags = 0; if (useCompress) { flags |= FLAG_COMPRESS; tmpBuf = deflate(tmpBuf, len); len = tmpBuf.length; } if (aesKey != null) { flags |= FLAG_AES; try { tmpBuf = crypto(tmpBuf, 0, len, false); } catch (Exception e) { throw new IllegalArgumentException("AES Encryption failed", e); } len = tmpBuf.length; // if (aesIV != null) { switch (aesTypeIV) { case RANDOM_IV: { // useAES + randomIV flags |= FLAG_RANDOM_IV; final byte[] ivBuf = aesIV.getIV(); tmpBuf = resizeBuffer(tmpBuf, len + ivBuf.length); System.arraycopy(ivBuf, 0, tmpBuf, len, ivBuf.length); len = tmpBuf.length; break; } case RANDOM_INT_IV: { // useAES + integerIV flags |= FLAG_RANDOM_INT_IV; final byte[] ivBuf = intToByteArray(integerIV); tmpBuf = resizeBuffer(tmpBuf, len + ivBuf.length); System.arraycopy(ivBuf, 0, tmpBuf, len, ivBuf.length); len = tmpBuf.length; break; } } } } if (rsaKeyForEncrypt != null) { flags |= FLAG_RSA; try { tmpBuf = cryptoAsym(tmpBuf, 0, len, false); } catch (Exception e) { throw new IllegalArgumentException("RSA Encryption failed", e); } len = tmpBuf.length; } if (useCRC) { flags |= FLAG_CRC; tmpBuf = resizeBuffer(tmpBuf, len + 1); tmpBuf[len] = (byte) crc8(tmpBuf, 0, len); len = tmpBuf.length; } if (mdHash != null) { // useHASH flags |= FLAG_HASH; final byte[] mdBuf = hash(tmpBuf, 0, len); tmpBuf = resizeBuffer(tmpBuf, len + mdBuf.length); System.arraycopy(mdBuf, 0, tmpBuf, len, mdBuf.length); len = tmpBuf.length; } if (hMac != null) { // useHMAC flags |= FLAG_HMAC; final byte[] hmacBuf = hmac(tmpBuf, 0, len); tmpBuf = resizeBuffer(tmpBuf, len + hmacBuf.length); System.arraycopy(hmacBuf, 0, tmpBuf, len, hmacBuf.length); len = tmpBuf.length; } if (useFlagFooter) { tmpBuf = resizeBuffer(tmpBuf, ++len); tmpBuf[len - 1] = (byte) (flags & 0xFF); } else { tmpBuf = resizeBuffer(tmpBuf, len); } return tmpBuf; }
java
public byte[] outputBytes() { byte[] tmpBuf = buf; int len = bufLimit; int flags = 0; if (useCompress) { flags |= FLAG_COMPRESS; tmpBuf = deflate(tmpBuf, len); len = tmpBuf.length; } if (aesKey != null) { flags |= FLAG_AES; try { tmpBuf = crypto(tmpBuf, 0, len, false); } catch (Exception e) { throw new IllegalArgumentException("AES Encryption failed", e); } len = tmpBuf.length; // if (aesIV != null) { switch (aesTypeIV) { case RANDOM_IV: { // useAES + randomIV flags |= FLAG_RANDOM_IV; final byte[] ivBuf = aesIV.getIV(); tmpBuf = resizeBuffer(tmpBuf, len + ivBuf.length); System.arraycopy(ivBuf, 0, tmpBuf, len, ivBuf.length); len = tmpBuf.length; break; } case RANDOM_INT_IV: { // useAES + integerIV flags |= FLAG_RANDOM_INT_IV; final byte[] ivBuf = intToByteArray(integerIV); tmpBuf = resizeBuffer(tmpBuf, len + ivBuf.length); System.arraycopy(ivBuf, 0, tmpBuf, len, ivBuf.length); len = tmpBuf.length; break; } } } } if (rsaKeyForEncrypt != null) { flags |= FLAG_RSA; try { tmpBuf = cryptoAsym(tmpBuf, 0, len, false); } catch (Exception e) { throw new IllegalArgumentException("RSA Encryption failed", e); } len = tmpBuf.length; } if (useCRC) { flags |= FLAG_CRC; tmpBuf = resizeBuffer(tmpBuf, len + 1); tmpBuf[len] = (byte) crc8(tmpBuf, 0, len); len = tmpBuf.length; } if (mdHash != null) { // useHASH flags |= FLAG_HASH; final byte[] mdBuf = hash(tmpBuf, 0, len); tmpBuf = resizeBuffer(tmpBuf, len + mdBuf.length); System.arraycopy(mdBuf, 0, tmpBuf, len, mdBuf.length); len = tmpBuf.length; } if (hMac != null) { // useHMAC flags |= FLAG_HMAC; final byte[] hmacBuf = hmac(tmpBuf, 0, len); tmpBuf = resizeBuffer(tmpBuf, len + hmacBuf.length); System.arraycopy(hmacBuf, 0, tmpBuf, len, hmacBuf.length); len = tmpBuf.length; } if (useFlagFooter) { tmpBuf = resizeBuffer(tmpBuf, ++len); tmpBuf[len - 1] = (byte) (flags & 0xFF); } else { tmpBuf = resizeBuffer(tmpBuf, len); } return tmpBuf; }
[ "public", "byte", "[", "]", "outputBytes", "(", ")", "{", "byte", "[", "]", "tmpBuf", "=", "buf", ";", "int", "len", "=", "bufLimit", ";", "int", "flags", "=", "0", ";", "if", "(", "useCompress", ")", "{", "flags", "|=", "FLAG_COMPRESS", ";", "tmpB...
Output bytes in raw format @return @throws IllegalArgumentException @see #loadBytes(byte[]) @see #useCompress(boolean) @see #useCRC(boolean) @see #useHASH(String)
[ "Output", "bytes", "in", "raw", "format" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L841-L916
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.loadStringHex
public Packer loadStringHex(final String in) throws InvalidInputDataException { try { return loadBytes(fromHex(in)); } catch (ParseException e) { throw new IllegalArgumentException("Invalid input string", e); } }
java
public Packer loadStringHex(final String in) throws InvalidInputDataException { try { return loadBytes(fromHex(in)); } catch (ParseException e) { throw new IllegalArgumentException("Invalid input string", e); } }
[ "public", "Packer", "loadStringHex", "(", "final", "String", "in", ")", "throws", "InvalidInputDataException", "{", "try", "{", "return", "loadBytes", "(", "fromHex", "(", "in", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "throw", "n...
Load string in hex format @return @throws InvalidInputDataException @throws ParseException @see #outputStringHex()
[ "Load", "string", "in", "hex", "format" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1266-L1272
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.crypto
final byte[] crypto(final byte[] input, final int offset, final int len, final boolean decrypt) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { aesCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, aesKey, aesIV); return aesCipher.doFinal(input, offset, len); }
java
final byte[] crypto(final byte[] input, final int offset, final int len, final boolean decrypt) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { aesCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, aesKey, aesIV); return aesCipher.doFinal(input, offset, len); }
[ "final", "byte", "[", "]", "crypto", "(", "final", "byte", "[", "]", "input", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "boolean", "decrypt", ")", "throws", "InvalidKeyException", ",", "InvalidAlgorithmParameterException", ",", ...
Encrypt or Decrypt with AES @param input @param offset @param len @param decrypt @return @throws InvalidAlgorithmParameterException @throws InvalidKeyException @throws BadPaddingException @throws IllegalBlockSizeException
[ "Encrypt", "or", "Decrypt", "with", "AES" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1476-L1481
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.cryptoAsym
final byte[] cryptoAsym(final byte[] input, final int offset, final int len, final boolean decrypt) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { rsaCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, decrypt ? rsaKeyForDecrypt : rsaKeyForEncrypt); return rsaCipher.doFinal(input, offset, len); }
java
final byte[] cryptoAsym(final byte[] input, final int offset, final int len, final boolean decrypt) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { rsaCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, decrypt ? rsaKeyForDecrypt : rsaKeyForEncrypt); return rsaCipher.doFinal(input, offset, len); }
[ "final", "byte", "[", "]", "cryptoAsym", "(", "final", "byte", "[", "]", "input", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "boolean", "decrypt", ")", "throws", "InvalidKeyException", ",", "InvalidAlgorithmParameterException", ",...
Encrypt or Decrypt with RSA @param input @param offset @param len @param decrypt @return @throws InvalidAlgorithmParameterException @throws InvalidKeyException @throws BadPaddingException @throws IllegalBlockSizeException
[ "Encrypt", "or", "Decrypt", "with", "RSA" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1496-L1502
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.resizeBuffer
static final byte[] resizeBuffer(final byte[] buf, final int newsize) { if (buf.length == newsize) return buf; final byte[] newbuf = new byte[newsize]; System.arraycopy(buf, 0, newbuf, 0, Math.min(buf.length, newbuf.length)); return newbuf; }
java
static final byte[] resizeBuffer(final byte[] buf, final int newsize) { if (buf.length == newsize) return buf; final byte[] newbuf = new byte[newsize]; System.arraycopy(buf, 0, newbuf, 0, Math.min(buf.length, newbuf.length)); return newbuf; }
[ "static", "final", "byte", "[", "]", "resizeBuffer", "(", "final", "byte", "[", "]", "buf", ",", "final", "int", "newsize", ")", "{", "if", "(", "buf", ".", "length", "==", "newsize", ")", "return", "buf", ";", "final", "byte", "[", "]", "newbuf", ...
Resize input buffer to newsize @param buf @param newsize @return
[ "Resize", "input", "buffer", "to", "newsize" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1511-L1517
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.compareBuffer
static final boolean compareBuffer(final byte[] buf1, final int offset1, final byte[] buf2, final int offset2, final int len) { for (int i = 0; i < len; i++) { final byte b1 = buf1[offset1 + i]; final byte b2 = buf2[offset2 + i]; if (b1 != b2) { return false; } } return true; }
java
static final boolean compareBuffer(final byte[] buf1, final int offset1, final byte[] buf2, final int offset2, final int len) { for (int i = 0; i < len; i++) { final byte b1 = buf1[offset1 + i]; final byte b2 = buf2[offset2 + i]; if (b1 != b2) { return false; } } return true; }
[ "static", "final", "boolean", "compareBuffer", "(", "final", "byte", "[", "]", "buf1", ",", "final", "int", "offset1", ",", "final", "byte", "[", "]", "buf2", ",", "final", "int", "offset2", ",", "final", "int", "len", ")", "{", "for", "(", "int", "i...
Compare buffer1 and buffer2 @param buf1 @param offset1 @param buf2 @param offset2 @param len @return true if all bytes are equal
[ "Compare", "buffer1", "and", "buffer2" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1529-L1539
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.toHex
static final String toHex(final byte[] input, final int len, final boolean upper) { final char[] hex = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { final int bx = input[i]; final int bh = ((bx >> 4) & 0xF); final int bl = (bx & 0xF); if ((bh >= 0) && (bh <= 9)) { hex[j++] |= (bh + '0'); } else if ((bh >= 0xA) && (bh <= 0xF)) { hex[j++] |= (bh - 0xA + (upper ? 'A' : 'a')); } if ((bl >= 0x0) && (bl <= 0x9)) { hex[j++] |= (bl + '0'); } else if ((bl >= 0xA) && (bl <= 0xF)) { hex[j++] |= (bl - 0xA + (upper ? 'A' : 'a')); } } return new String(hex); }
java
static final String toHex(final byte[] input, final int len, final boolean upper) { final char[] hex = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { final int bx = input[i]; final int bh = ((bx >> 4) & 0xF); final int bl = (bx & 0xF); if ((bh >= 0) && (bh <= 9)) { hex[j++] |= (bh + '0'); } else if ((bh >= 0xA) && (bh <= 0xF)) { hex[j++] |= (bh - 0xA + (upper ? 'A' : 'a')); } if ((bl >= 0x0) && (bl <= 0x9)) { hex[j++] |= (bl + '0'); } else if ((bl >= 0xA) && (bl <= 0xF)) { hex[j++] |= (bl - 0xA + (upper ? 'A' : 'a')); } } return new String(hex); }
[ "static", "final", "String", "toHex", "(", "final", "byte", "[", "]", "input", ",", "final", "int", "len", ",", "final", "boolean", "upper", ")", "{", "final", "char", "[", "]", "hex", "=", "new", "char", "[", "len", "<<", "1", "]", ";", "for", "...
Transform byte array to Hex String @param input @return
[ "Transform", "byte", "array", "to", "Hex", "String" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1558-L1576
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.fromHex
static final byte[] fromHex(final String hex) throws ParseException { final int len = hex.length(); final byte[] out = new byte[len / 2]; for (int i = 0, j = 0; i < len; i++) { char c = hex.charAt(i); int v = 0; if ((c >= '0') && (c <= '9')) { v = (c - '0'); } else if ((c >= 'A') && (c <= 'F')) { v = (c - 'A') + 0xA; } else if ((c >= 'a') && (c <= 'f')) { v = (c - 'a') + 0xA; } else { throw new ParseException("Invalid char", j); } if ((i & 1) == 0) { out[j] |= (v << 4); } else { out[j++] |= v; } } return out; }
java
static final byte[] fromHex(final String hex) throws ParseException { final int len = hex.length(); final byte[] out = new byte[len / 2]; for (int i = 0, j = 0; i < len; i++) { char c = hex.charAt(i); int v = 0; if ((c >= '0') && (c <= '9')) { v = (c - '0'); } else if ((c >= 'A') && (c <= 'F')) { v = (c - 'A') + 0xA; } else if ((c >= 'a') && (c <= 'f')) { v = (c - 'a') + 0xA; } else { throw new ParseException("Invalid char", j); } if ((i & 1) == 0) { out[j] |= (v << 4); } else { out[j++] |= v; } } return out; }
[ "static", "final", "byte", "[", "]", "fromHex", "(", "final", "String", "hex", ")", "throws", "ParseException", "{", "final", "int", "len", "=", "hex", ".", "length", "(", ")", ";", "final", "byte", "[", "]", "out", "=", "new", "byte", "[", "len", ...
Transform Hex String to byte array @param hex @return @throws ParseException
[ "Transform", "Hex", "String", "to", "byte", "array" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1596-L1618
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.deflate
static final byte[] deflate(final byte[] in, final int len) { byte[] defBuf = new byte[len << 1]; int payloadLength; synchronized (deflater) { deflater.reset(); deflater.setInput(in, 0, len); deflater.finish(); payloadLength = deflater.deflate(defBuf); } return resizeBuffer(defBuf, payloadLength); }
java
static final byte[] deflate(final byte[] in, final int len) { byte[] defBuf = new byte[len << 1]; int payloadLength; synchronized (deflater) { deflater.reset(); deflater.setInput(in, 0, len); deflater.finish(); payloadLength = deflater.deflate(defBuf); } return resizeBuffer(defBuf, payloadLength); }
[ "static", "final", "byte", "[", "]", "deflate", "(", "final", "byte", "[", "]", "in", ",", "final", "int", "len", ")", "{", "byte", "[", "]", "defBuf", "=", "new", "byte", "[", "len", "<<", "1", "]", ";", "int", "payloadLength", ";", "synchronized"...
Deflate input buffer @param in @param len @return
[ "Deflate", "input", "buffer" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1627-L1637
train
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.inflate
static final byte[] inflate(final byte[] in, final int offset, final int length) throws DataFormatException { byte[] infBuf = new byte[length << 1]; int payloadLength; synchronized (inflater) { inflater.reset(); inflater.setInput(in, offset, length); payloadLength = inflater.inflate(infBuf); } return resizeBuffer(infBuf, payloadLength); }
java
static final byte[] inflate(final byte[] in, final int offset, final int length) throws DataFormatException { byte[] infBuf = new byte[length << 1]; int payloadLength; synchronized (inflater) { inflater.reset(); inflater.setInput(in, offset, length); payloadLength = inflater.inflate(infBuf); } return resizeBuffer(infBuf, payloadLength); }
[ "static", "final", "byte", "[", "]", "inflate", "(", "final", "byte", "[", "]", "in", ",", "final", "int", "offset", ",", "final", "int", "length", ")", "throws", "DataFormatException", "{", "byte", "[", "]", "infBuf", "=", "new", "byte", "[", "length"...
Inflate input buffer @param in @return @throws DataFormatException
[ "Inflate", "input", "buffer" ]
0b37b286a3d0555050eb2e65419dd74f8d8d3e78
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1646-L1656
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/file/FileUtils.java
FileUtils.copyFile
public static boolean copyFile(File srcFile, File destFile) { boolean result = false; try { InputStream in = new FileInputStream(srcFile); try { result = copyToFile(in, destFile); } finally { in.close(); } } catch (IOException e) { result = false; } return result; }
java
public static boolean copyFile(File srcFile, File destFile) { boolean result = false; try { InputStream in = new FileInputStream(srcFile); try { result = copyToFile(in, destFile); } finally { in.close(); } } catch (IOException e) { result = false; } return result; }
[ "public", "static", "boolean", "copyFile", "(", "File", "srcFile", ",", "File", "destFile", ")", "{", "boolean", "result", "=", "false", ";", "try", "{", "InputStream", "in", "=", "new", "FileInputStream", "(", "srcFile", ")", ";", "try", "{", "result", ...
false if fail
[ "false", "if", "fail" ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/file/FileUtils.java#L75-L88
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/file/FileUtils.java
FileUtils.copyToFile
public static boolean copyToFile(InputStream inputStream, File destFile) { try { OutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) >= 0) { out.write(buffer, 0, bytesRead); } } finally { out.close(); } return true; } catch (IOException e) { return false; } }
java
public static boolean copyToFile(InputStream inputStream, File destFile) { try { OutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) >= 0) { out.write(buffer, 0, bytesRead); } } finally { out.close(); } return true; } catch (IOException e) { return false; } }
[ "public", "static", "boolean", "copyToFile", "(", "InputStream", "inputStream", ",", "File", "destFile", ")", "{", "try", "{", "OutputStream", "out", "=", "new", "FileOutputStream", "(", "destFile", ")", ";", "try", "{", "byte", "[", "]", "buffer", "=", "n...
Copy data from a source stream to destFile. Return true if succeed, return false if failed.
[ "Copy", "data", "from", "a", "source", "stream", "to", "destFile", ".", "Return", "true", "if", "succeed", "return", "false", "if", "failed", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/file/FileUtils.java#L94-L110
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/file/FileUtils.java
FileUtils.readTextFile
public static String readTextFile(File file, int max, String ellipsis) throws IOException { InputStream input = new FileInputStream(file); try { if (max > 0) { // "head" mode: read the first N bytes byte[] data = new byte[max + 1]; int length = input.read(data); if (length <= 0) return ""; if (length <= max) return new String(data, 0, length); if (ellipsis == null) return new String(data, 0, max); return new String(data, 0, max) + ellipsis; } else if (max < 0) { // "tail" mode: read it all, keep the last N int len; boolean rolled = false; byte[] last = null, data = null; do { if (last != null) rolled = true; byte[] tmp = last; last = data; data = tmp; if (data == null) data = new byte[-max]; len = input.read(data); } while (len == data.length); if (last == null && len <= 0) return ""; if (last == null) return new String(data, 0, len); if (len > 0) { rolled = true; System.arraycopy(last, len, last, 0, last.length - len); System.arraycopy(data, 0, last, last.length - len, len); } if (ellipsis == null || !rolled) return new String(last); return ellipsis + new String(last); } else { // "cat" mode: read it all ByteArrayOutputStream contents = new ByteArrayOutputStream(); int len; byte[] data = new byte[1024]; do { len = input.read(data); if (len > 0) contents.write(data, 0, len); } while (len == data.length); return contents.toString(); } } finally { input.close(); } }
java
public static String readTextFile(File file, int max, String ellipsis) throws IOException { InputStream input = new FileInputStream(file); try { if (max > 0) { // "head" mode: read the first N bytes byte[] data = new byte[max + 1]; int length = input.read(data); if (length <= 0) return ""; if (length <= max) return new String(data, 0, length); if (ellipsis == null) return new String(data, 0, max); return new String(data, 0, max) + ellipsis; } else if (max < 0) { // "tail" mode: read it all, keep the last N int len; boolean rolled = false; byte[] last = null, data = null; do { if (last != null) rolled = true; byte[] tmp = last; last = data; data = tmp; if (data == null) data = new byte[-max]; len = input.read(data); } while (len == data.length); if (last == null && len <= 0) return ""; if (last == null) return new String(data, 0, len); if (len > 0) { rolled = true; System.arraycopy(last, len, last, 0, last.length - len); System.arraycopy(data, 0, last, last.length - len, len); } if (ellipsis == null || !rolled) return new String(last); return ellipsis + new String(last); } else { // "cat" mode: read it all ByteArrayOutputStream contents = new ByteArrayOutputStream(); int len; byte[] data = new byte[1024]; do { len = input.read(data); if (len > 0) contents.write(data, 0, len); } while (len == data.length); return contents.toString(); } } finally { input.close(); } }
[ "public", "static", "String", "readTextFile", "(", "File", "file", ",", "int", "max", ",", "String", "ellipsis", ")", "throws", "IOException", "{", "InputStream", "input", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "if", "(", "max", ...
Read a text file into a String, optionally limiting the length. @param file to read (will not seek, so things like /proc files are OK) @param max length (positive for head, negative of tail, 0 for no limit) @param ellipsis to add of the file was truncated (can be null) @return the contents of the file, possibly truncated @throws IOException if something goes wrong reading the file
[ "Read", "a", "text", "file", "into", "a", "String", "optionally", "limiting", "the", "length", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/file/FileUtils.java#L131-L174
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/transitory/TransientObject.java
TransientObject.setFilePermissions
public void setFilePermissions(FilePermissions filePermissions){ if(isWritable()){ meta_data.put(PERMISSIONS_KEY.KEY,gson.toJson(filePermissions,FilePermissions.class)); } }
java
public void setFilePermissions(FilePermissions filePermissions){ if(isWritable()){ meta_data.put(PERMISSIONS_KEY.KEY,gson.toJson(filePermissions,FilePermissions.class)); } }
[ "public", "void", "setFilePermissions", "(", "FilePermissions", "filePermissions", ")", "{", "if", "(", "isWritable", "(", ")", ")", "{", "meta_data", ".", "put", "(", "PERMISSIONS_KEY", ".", "KEY", ",", "gson", ".", "toJson", "(", "filePermissions", ",", "F...
Sets new file permissions for this object. @param filePermissions file permissions to be used for this object.
[ "Sets", "new", "file", "permissions", "for", "this", "object", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/transitory/TransientObject.java#L123-L127
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/transitory/TransientObject.java
TransientObject.setOwnerId
protected void setOwnerId(Integer id){ if(getOwnerId() != null){ logger.warn("Attempting to set owner id for an object where it as previously been set. Ignoring new id"); return; } meta_put(OWNER_ID_KEY, id); // dont allow null }
java
protected void setOwnerId(Integer id){ if(getOwnerId() != null){ logger.warn("Attempting to set owner id for an object where it as previously been set. Ignoring new id"); return; } meta_put(OWNER_ID_KEY, id); // dont allow null }
[ "protected", "void", "setOwnerId", "(", "Integer", "id", ")", "{", "if", "(", "getOwnerId", "(", ")", "!=", "null", ")", "{", "logger", ".", "warn", "(", "\"Attempting to set owner id for an object where it as previously been set. Ignoring new id\"", ")", ";", "return...
accessable to subclasses and this class, stupid java.
[ "accessable", "to", "subclasses", "and", "this", "class", "stupid", "java", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/transitory/TransientObject.java#L345-L351
train
ivanceras/orm
src/main/java/com/ivanceras/db/shared/DAOArray.java
DAOArray.fromDao
public DAOArray fromDao(DAO[] daoList) throws DAOArrayException{ for(DAO dao : daoList){ add(dao); } return this; }
java
public DAOArray fromDao(DAO[] daoList) throws DAOArrayException{ for(DAO dao : daoList){ add(dao); } return this; }
[ "public", "DAOArray", "fromDao", "(", "DAO", "[", "]", "daoList", ")", "throws", "DAOArrayException", "{", "for", "(", "DAO", "dao", ":", "daoList", ")", "{", "add", "(", "dao", ")", ";", "}", "return", "this", ";", "}" ]
convert a list of dao into this format @param daoList @return @throws DAOArrayException
[ "convert", "a", "list", "of", "dao", "into", "this", "format" ]
e63213cb8abefd11df0e2d34b1c95477788e600e
https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/shared/DAOArray.java#L52-L57
train
ivanceras/orm
src/main/java/com/ivanceras/db/shared/DAOArray.java
DAOArray.convert
public DAO[] convert(){ int size = data.size(); DAO[] daoList = new DAO[size]; for(int i = 0; i < size; i++){ Object[] dat = data.get(i); DAO dao = new DAO(modelName); for(int j = 0; j < attributes.length; j++){ dao.set_Value(attributes[j], dat[j]); } daoList[i] = dao; } return daoList; }
java
public DAO[] convert(){ int size = data.size(); DAO[] daoList = new DAO[size]; for(int i = 0; i < size; i++){ Object[] dat = data.get(i); DAO dao = new DAO(modelName); for(int j = 0; j < attributes.length; j++){ dao.set_Value(attributes[j], dat[j]); } daoList[i] = dao; } return daoList; }
[ "public", "DAO", "[", "]", "convert", "(", ")", "{", "int", "size", "=", "data", ".", "size", "(", ")", ";", "DAO", "[", "]", "daoList", "=", "new", "DAO", "[", "size", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";",...
From this format convert back to DAO @return
[ "From", "this", "format", "convert", "back", "to", "DAO" ]
e63213cb8abefd11df0e2d34b1c95477788e600e
https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/shared/DAOArray.java#L64-L77
train
jayantk/jklol
src/com/jayantkrish/jklol/util/CountAccumulator.java
CountAccumulator.getSortedKeys
public List<T> getSortedKeys() { List<T> l = Lists.newArrayList(counts.keySet()); Collections.sort(l, Ordering.natural().reverse().onResultOf(Functions.forMap(counts.getBaseMap()))); return l; }
java
public List<T> getSortedKeys() { List<T> l = Lists.newArrayList(counts.keySet()); Collections.sort(l, Ordering.natural().reverse().onResultOf(Functions.forMap(counts.getBaseMap()))); return l; }
[ "public", "List", "<", "T", ">", "getSortedKeys", "(", ")", "{", "List", "<", "T", ">", "l", "=", "Lists", ".", "newArrayList", "(", "counts", ".", "keySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "l", ",", "Ordering", ".", "natural",...
Gets the keys in this sorted order, from the highest count to the lowest count. @return
[ "Gets", "the", "keys", "in", "this", "sorted", "order", "from", "the", "highest", "count", "to", "the", "lowest", "count", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/CountAccumulator.java#L145-L149
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/supertag/ListSupertaggedSentence.java
ListSupertaggedSentence.createWithUnobservedSupertags
public static ListSupertaggedSentence createWithUnobservedSupertags(List<String> words, List<String> pos) { return new ListSupertaggedSentence(WordAndPos.createExample(words, pos), Collections.nCopies(words.size(), Collections.<HeadedSyntacticCategory>emptyList()), Collections.nCopies(words.size(), Collections.<Double>emptyList())); }
java
public static ListSupertaggedSentence createWithUnobservedSupertags(List<String> words, List<String> pos) { return new ListSupertaggedSentence(WordAndPos.createExample(words, pos), Collections.nCopies(words.size(), Collections.<HeadedSyntacticCategory>emptyList()), Collections.nCopies(words.size(), Collections.<Double>emptyList())); }
[ "public", "static", "ListSupertaggedSentence", "createWithUnobservedSupertags", "(", "List", "<", "String", ">", "words", ",", "List", "<", "String", ">", "pos", ")", "{", "return", "new", "ListSupertaggedSentence", "(", "WordAndPos", ".", "createExample", "(", "w...
Creates a supertagged sentence where the supertags for each word are unobserved. Using this sentence during CCG parsing allows any syntactic category to be assigned to each word. @param words @param pos @return
[ "Creates", "a", "supertagged", "sentence", "where", "the", "supertags", "for", "each", "word", "are", "unobserved", ".", "Using", "this", "sentence", "during", "CCG", "parsing", "allows", "any", "syntactic", "category", "to", "be", "assigned", "to", "each", "w...
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/supertag/ListSupertaggedSentence.java#L28-L32
train
cpollet/jixture
core/src/main/java/net/cpollet/jixture/fixtures/GeneratedFixture.java
GeneratedFixture.next
@Override public Object next() { assertGeneratorStarted(); if (!hasNext()) { throw new NoSuchElementException("No more object to generate"); } Object object = currentFixtureGenerator.next(); logger.debug("Generated {}", object); extractorDelegate.extractEntity(object); return object; }
java
@Override public Object next() { assertGeneratorStarted(); if (!hasNext()) { throw new NoSuchElementException("No more object to generate"); } Object object = currentFixtureGenerator.next(); logger.debug("Generated {}", object); extractorDelegate.extractEntity(object); return object; }
[ "@", "Override", "public", "Object", "next", "(", ")", "{", "assertGeneratorStarted", "(", ")", ";", "if", "(", "!", "hasNext", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"No more object to generate\"", ")", ";", "}", "Object", "obj...
Returns the next entity to load. @return the next entity to load. @throws java.util.NoSuchElementException if the iteration has no more elements.
[ "Returns", "the", "next", "entity", "to", "load", "." ]
faef0d4991f81c2cdb5be3ba24176636ef0cc433
https://github.com/cpollet/jixture/blob/faef0d4991f81c2cdb5be3ba24176636ef0cc433/core/src/main/java/net/cpollet/jixture/fixtures/GeneratedFixture.java#L150-L163
train
jayantk/jklol
src/com/jayantkrish/jklol/parallel/MapReduceConfiguration.java
MapReduceConfiguration.getMapReduceExecutor
public static MapReduceExecutor getMapReduceExecutor() { if (executor == null) { // Default to using a local executor with one thread per CPU. executor = new LocalMapReduceExecutor( Runtime.getRuntime().availableProcessors(), 20); } return executor; }
java
public static MapReduceExecutor getMapReduceExecutor() { if (executor == null) { // Default to using a local executor with one thread per CPU. executor = new LocalMapReduceExecutor( Runtime.getRuntime().availableProcessors(), 20); } return executor; }
[ "public", "static", "MapReduceExecutor", "getMapReduceExecutor", "(", ")", "{", "if", "(", "executor", "==", "null", ")", "{", "// Default to using a local executor with one thread per CPU.", "executor", "=", "new", "LocalMapReduceExecutor", "(", "Runtime", ".", "getRunti...
Gets the global map-reduce executor. @return
[ "Gets", "the", "global", "map", "-", "reduce", "executor", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/parallel/MapReduceConfiguration.java#L28-L35
train
jayantk/jklol
src/com/jayantkrish/jklol/models/DiscreteFactor.java
DiscreteFactor.getNonzeroAssignments
public List<Assignment> getNonzeroAssignments() { Iterator<Outcome> outcomeIter = outcomeIterator(); List<Assignment> assignments = Lists.newArrayList(); while (outcomeIter.hasNext()) { Outcome outcome = outcomeIter.next(); if (outcome.getProbability() != 0.0) { assignments.add(outcome.getAssignment()); } } return assignments; }
java
public List<Assignment> getNonzeroAssignments() { Iterator<Outcome> outcomeIter = outcomeIterator(); List<Assignment> assignments = Lists.newArrayList(); while (outcomeIter.hasNext()) { Outcome outcome = outcomeIter.next(); if (outcome.getProbability() != 0.0) { assignments.add(outcome.getAssignment()); } } return assignments; }
[ "public", "List", "<", "Assignment", ">", "getNonzeroAssignments", "(", ")", "{", "Iterator", "<", "Outcome", ">", "outcomeIter", "=", "outcomeIterator", "(", ")", ";", "List", "<", "Assignment", ">", "assignments", "=", "Lists", ".", "newArrayList", "(", ")...
Gets all assignments to this factor which have non-zero weight. @return
[ "Gets", "all", "assignments", "to", "this", "factor", "which", "have", "non", "-", "zero", "weight", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/DiscreteFactor.java#L311-L321
train
jayantk/jklol
src/com/jayantkrish/jklol/models/DiscreteFactor.java
DiscreteFactor.getPartitionFunction
private double getPartitionFunction() { if (partitionFunction != -1.0) { return partitionFunction; } partitionFunction = 0.0; Iterator<Outcome> outcomeIterator = outcomeIterator(); while (outcomeIterator.hasNext()) { partitionFunction += outcomeIterator.next().getProbability(); } return partitionFunction; }
java
private double getPartitionFunction() { if (partitionFunction != -1.0) { return partitionFunction; } partitionFunction = 0.0; Iterator<Outcome> outcomeIterator = outcomeIterator(); while (outcomeIterator.hasNext()) { partitionFunction += outcomeIterator.next().getProbability(); } return partitionFunction; }
[ "private", "double", "getPartitionFunction", "(", ")", "{", "if", "(", "partitionFunction", "!=", "-", "1.0", ")", "{", "return", "partitionFunction", ";", "}", "partitionFunction", "=", "0.0", ";", "Iterator", "<", "Outcome", ">", "outcomeIterator", "=", "out...
Get the partition function = denominator = total sum probability of all assignments.
[ "Get", "the", "partition", "function", "=", "denominator", "=", "total", "sum", "probability", "of", "all", "assignments", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/DiscreteFactor.java#L401-L412
train
jayantk/jklol
src/com/jayantkrish/jklol/util/MapUtils.java
MapUtils.fromLists
public static <A, B> Map<A, B> fromLists(List<A> keys, List<B> values) { Preconditions.checkArgument(keys.size() == values.size()); Map<A, B> map = Maps.newHashMap(); for (int i = 0; i < keys.size(); i++) { map.put(keys.get(i), values.get(i)); } return map; }
java
public static <A, B> Map<A, B> fromLists(List<A> keys, List<B> values) { Preconditions.checkArgument(keys.size() == values.size()); Map<A, B> map = Maps.newHashMap(); for (int i = 0; i < keys.size(); i++) { map.put(keys.get(i), values.get(i)); } return map; }
[ "public", "static", "<", "A", ",", "B", ">", "Map", "<", "A", ",", "B", ">", "fromLists", "(", "List", "<", "A", ">", "keys", ",", "List", "<", "B", ">", "values", ")", "{", "Preconditions", ".", "checkArgument", "(", "keys", ".", "size", "(", ...
Returns a map where the ith element of keys maps to the ith element of values. @param keys @param values @return
[ "Returns", "a", "map", "where", "the", "ith", "element", "of", "keys", "maps", "to", "the", "ith", "element", "of", "values", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/MapUtils.java#L60-L67
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/lambda2/StaticAnalysis.java
StaticAnalysis.inferType
public static Type inferType(Expression2 expression, Type rootType, TypeDeclaration typeDeclaration) { Map<Integer, Type> subexpressionTypeMap = inferTypeMap(expression, rootType, typeDeclaration); return subexpressionTypeMap.get(0); }
java
public static Type inferType(Expression2 expression, Type rootType, TypeDeclaration typeDeclaration) { Map<Integer, Type> subexpressionTypeMap = inferTypeMap(expression, rootType, typeDeclaration); return subexpressionTypeMap.get(0); }
[ "public", "static", "Type", "inferType", "(", "Expression2", "expression", ",", "Type", "rootType", ",", "TypeDeclaration", "typeDeclaration", ")", "{", "Map", "<", "Integer", ",", "Type", ">", "subexpressionTypeMap", "=", "inferTypeMap", "(", "expression", ",", ...
Implementation of type inference that infers types for expressions using the basic type information in typeDeclaration. @param expression @param rootType @param typeDeclaration @return
[ "Implementation", "of", "type", "inference", "that", "infers", "types", "for", "expressions", "using", "the", "basic", "type", "information", "in", "typeDeclaration", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/lambda2/StaticAnalysis.java#L283-L286
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.eventDateValid
public static boolean eventDateValid(String eventDate) { boolean result = false; if (extractDate(eventDate)!=null) { result = true; } else { Interval interval = extractInterval(eventDate); if (interval!=null) { if (interval.getStart().isBefore(interval.getEnd())) { result = true; } } } return result; }
java
public static boolean eventDateValid(String eventDate) { boolean result = false; if (extractDate(eventDate)!=null) { result = true; } else { Interval interval = extractInterval(eventDate); if (interval!=null) { if (interval.getStart().isBefore(interval.getEnd())) { result = true; } } } return result; }
[ "public", "static", "boolean", "eventDateValid", "(", "String", "eventDate", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "extractDate", "(", "eventDate", ")", "!=", "null", ")", "{", "result", "=", "true", ";", "}", "else", "{", "Interva...
Test to see whether an eventDate contains a string in an expected ISO format. @param eventDate string to test for expected format. @return true if eventDate is in an expected format for eventDate, otherwise false.
[ "Test", "to", "see", "whether", "an", "eventDate", "contains", "a", "string", "in", "an", "expected", "ISO", "format", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L98-L111
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.extractDateFromVerbatim
public static Map<String,String> extractDateFromVerbatim(String verbatimEventDate) { return extractDateFromVerbatim(verbatimEventDate, DateUtils.YEAR_BEFORE_SUSPECT); }
java
public static Map<String,String> extractDateFromVerbatim(String verbatimEventDate) { return extractDateFromVerbatim(verbatimEventDate, DateUtils.YEAR_BEFORE_SUSPECT); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "extractDateFromVerbatim", "(", "String", "verbatimEventDate", ")", "{", "return", "extractDateFromVerbatim", "(", "verbatimEventDate", ",", "DateUtils", ".", "YEAR_BEFORE_SUSPECT", ")", ";", "}" ]
Attempt to extract a date or date range in standard format from a provided verbatim date string. @param verbatimEventDate a string containing a verbatim event date. @return a map with result and resultState as keys @deprecated @see #extractDateFromVerbatimER(String) replacement method.
[ "Attempt", "to", "extract", "a", "date", "or", "date", "range", "in", "standard", "format", "from", "a", "provided", "verbatim", "date", "string", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L243-L245
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.isRange
public static boolean isRange(String eventDate) { boolean isRange = false; if (eventDate!=null) { String[] dateBits = eventDate.split("/"); if (dateBits!=null && dateBits.length==2) { //probably a range. DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { // must be at least a 4 digit year. if (dateBits[0].length()>3 && dateBits[1].length()>3) { DateMidnight startDate = LocalDate.parse(dateBits[0],formatter).toDateMidnight(); DateMidnight endDate = LocalDate.parse(dateBits[1],formatter).toDateMidnight(); // both start date and end date must parse as dates. isRange = true; } } catch (Exception e) { // not a date range e.printStackTrace(); logger.debug(e.getMessage()); } } else if (dateBits!=null && dateBits.length==1) { logger.debug(dateBits[0]); // Date bits does not contain a / // Is eventDate in the form yyyy-mm-dd, if so, not a range DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM-dd").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { DateMidnight date = DateMidnight.parse(eventDate,formatter); isRange = false; } catch (Exception e) { logger.debug(e.getMessage()); // not parsable with the yyyy-mm-dd parser. DateTimeParser[] parsers2 = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), }; formatter = new DateTimeFormatterBuilder().append( null, parsers2 ).toFormatter(); try { // must be at least a 4 digit year. if (dateBits[0].length()>3) { DateMidnight startDate = DateMidnight.parse(dateBits[0],formatter); // date must parse as either year or year and month dates. isRange = true; } } catch (Exception e1) { // not a date range } } } } return isRange; }
java
public static boolean isRange(String eventDate) { boolean isRange = false; if (eventDate!=null) { String[] dateBits = eventDate.split("/"); if (dateBits!=null && dateBits.length==2) { //probably a range. DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { // must be at least a 4 digit year. if (dateBits[0].length()>3 && dateBits[1].length()>3) { DateMidnight startDate = LocalDate.parse(dateBits[0],formatter).toDateMidnight(); DateMidnight endDate = LocalDate.parse(dateBits[1],formatter).toDateMidnight(); // both start date and end date must parse as dates. isRange = true; } } catch (Exception e) { // not a date range e.printStackTrace(); logger.debug(e.getMessage()); } } else if (dateBits!=null && dateBits.length==1) { logger.debug(dateBits[0]); // Date bits does not contain a / // Is eventDate in the form yyyy-mm-dd, if so, not a range DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM-dd").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { DateMidnight date = DateMidnight.parse(eventDate,formatter); isRange = false; } catch (Exception e) { logger.debug(e.getMessage()); // not parsable with the yyyy-mm-dd parser. DateTimeParser[] parsers2 = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), }; formatter = new DateTimeFormatterBuilder().append( null, parsers2 ).toFormatter(); try { // must be at least a 4 digit year. if (dateBits[0].length()>3) { DateMidnight startDate = DateMidnight.parse(dateBits[0],formatter); // date must parse as either year or year and month dates. isRange = true; } } catch (Exception e1) { // not a date range } } } } return isRange; }
[ "public", "static", "boolean", "isRange", "(", "String", "eventDate", ")", "{", "boolean", "isRange", "=", "false", ";", "if", "(", "eventDate", "!=", "null", ")", "{", "String", "[", "]", "dateBits", "=", "eventDate", ".", "split", "(", "\"/\"", ")", ...
Test to see if a string appears to represent a date range of more than one day. @param eventDate to check @return true if a date range, false otherwise.
[ "Test", "to", "see", "if", "a", "string", "appears", "to", "represent", "a", "date", "range", "of", "more", "than", "one", "day", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1504-L1564
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.extractInterval
public static Interval extractInterval(String eventDate) { Interval result = null; DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); if (eventDate!=null && eventDate.contains("/") && isRange(eventDate)) { String[] dateBits = eventDate.split("/"); try { // must be at least a 4 digit year. if (dateBits[0].length()>3 && dateBits[1].length()>3) { DateMidnight startDate = DateMidnight.parse(dateBits[0],formatter); DateTime endDate = DateTime.parse(dateBits[1],formatter); logger.debug(startDate); logger.debug(endDate); if (dateBits[1].length()==4) { result = new Interval(startDate,endDate.plusMonths(12).minus(1l)); } else if (dateBits[1].length()==7) { result = new Interval(startDate,endDate.plusMonths(1).minus(1l)); } else { result = new Interval(startDate, endDate.plusDays(1).minus(1l)); } logger.debug(result); } } catch (Exception e) { // not a date range logger.error(e.getMessage()); } } else { try { DateMidnight startDate = DateMidnight.parse(eventDate, formatter); logger.debug(startDate); if (eventDate.length()==4) { DateTime endDate = startDate.toDateTime().plusMonths(12).minus(1l); result = new Interval(startDate, endDate); logger.debug(result); } else if (eventDate.length()==7) { DateTime endDate = startDate.toDateTime().plusMonths(1).minus(1l); result = new Interval(startDate,endDate); logger.debug(result); } else { DateTime endDate = startDate.toDateTime().plusDays(1).minus(1l); result = new Interval(startDate,endDate); logger.debug(result); } } catch (Exception e) { // not a date logger.error(e.getMessage()); } } return result; }
java
public static Interval extractInterval(String eventDate) { Interval result = null; DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); if (eventDate!=null && eventDate.contains("/") && isRange(eventDate)) { String[] dateBits = eventDate.split("/"); try { // must be at least a 4 digit year. if (dateBits[0].length()>3 && dateBits[1].length()>3) { DateMidnight startDate = DateMidnight.parse(dateBits[0],formatter); DateTime endDate = DateTime.parse(dateBits[1],formatter); logger.debug(startDate); logger.debug(endDate); if (dateBits[1].length()==4) { result = new Interval(startDate,endDate.plusMonths(12).minus(1l)); } else if (dateBits[1].length()==7) { result = new Interval(startDate,endDate.plusMonths(1).minus(1l)); } else { result = new Interval(startDate, endDate.plusDays(1).minus(1l)); } logger.debug(result); } } catch (Exception e) { // not a date range logger.error(e.getMessage()); } } else { try { DateMidnight startDate = DateMidnight.parse(eventDate, formatter); logger.debug(startDate); if (eventDate.length()==4) { DateTime endDate = startDate.toDateTime().plusMonths(12).minus(1l); result = new Interval(startDate, endDate); logger.debug(result); } else if (eventDate.length()==7) { DateTime endDate = startDate.toDateTime().plusMonths(1).minus(1l); result = new Interval(startDate,endDate); logger.debug(result); } else { DateTime endDate = startDate.toDateTime().plusDays(1).minus(1l); result = new Interval(startDate,endDate); logger.debug(result); } } catch (Exception e) { // not a date logger.error(e.getMessage()); } } return result; }
[ "public", "static", "Interval", "extractInterval", "(", "String", "eventDate", ")", "{", "Interval", "result", "=", "null", ";", "DateTimeParser", "[", "]", "parsers", "=", "{", "DateTimeFormat", ".", "forPattern", "(", "\"yyyy-MM\"", ")", ".", "getParser", "(...
Given a string that may be a date or a date range, extract a interval of dates from that date range, up to the end milisecond of the last day. @see DateUtils#extractDateInterval(String) which returns a pair of DateMidnights. @param eventDate a string containing a dwc:eventDate from which to extract an interval. @return an interval from the beginning of event date to the end of event date.
[ "Given", "a", "string", "that", "may", "be", "a", "date", "or", "a", "date", "range", "extract", "a", "interval", "of", "dates", "from", "that", "date", "range", "up", "to", "the", "end", "milisecond", "of", "the", "last", "day", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1641-L1694
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.extractDate
public static DateMidnight extractDate(String eventDate) { DateMidnight result = null; DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), DateTimeFormat.forPattern("yyyy-MM-dd/yyyy-MM-dd").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser(), ISODateTimeFormat.date().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { result = DateMidnight.parse(eventDate, formatter); logger.debug(result); } catch (Exception e) { // not a date logger.error(e.getMessage()); } return result; }
java
public static DateMidnight extractDate(String eventDate) { DateMidnight result = null; DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(), DateTimeFormat.forPattern("yyyy").getParser(), DateTimeFormat.forPattern("yyyy-MM-dd/yyyy-MM-dd").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser(), ISODateTimeFormat.date().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter(); try { result = DateMidnight.parse(eventDate, formatter); logger.debug(result); } catch (Exception e) { // not a date logger.error(e.getMessage()); } return result; }
[ "public", "static", "DateMidnight", "extractDate", "(", "String", "eventDate", ")", "{", "DateMidnight", "result", "=", "null", ";", "DateTimeParser", "[", "]", "parsers", "=", "{", "DateTimeFormat", ".", "forPattern", "(", "\"yyyy-MM\"", ")", ".", "getParser", ...
Extract a single joda date from an event date. @param eventDate an event date from which to try to extract a DateMidnight @return a DateMidnight or null if a date cannot be extracted
[ "Extract", "a", "single", "joda", "date", "from", "an", "event", "date", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1702-L1720
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.isConsistent
public static boolean isConsistent(String eventDate, String startDayOfYear, String endDayOfYear, String year, String month, String day) { if (isEmpty(eventDate) || (isEmpty(startDayOfYear) && isEmpty(endDayOfYear) && isEmpty(year) && isEmpty(month) && isEmpty(day))) { return true; } // TODO: Add support for eventTime boolean result = false; result = isConsistent(eventDate,year,month,day); logger.debug(result); if ((result || (!isEmpty(eventDate) && isEmpty(year) && isEmpty(month) && isEmpty(day))) && (!isEmpty(startDayOfYear) || !isEmpty(endDayOfYear))) { if (endDayOfYear==null || endDayOfYear.trim().length()==0 || startDayOfYear.trim().equals(endDayOfYear.trim())) { int startDayInt = -1; try { startDayInt = Integer.parseInt(startDayOfYear); } catch (NumberFormatException e) { logger.debug(e.getMessage()); logger.debug(startDayOfYear + " is not an integer."); result = false; } if (DateUtils.extractDate(eventDate)!=null && DateUtils.extractDate(eventDate).getDayOfYear() == startDayInt) { result=true; } else { result = false; } } else { int startDayInt = -1; int endDayInt = -1; try { startDayInt = Integer.parseInt(startDayOfYear); endDayInt = Integer.parseInt(endDayOfYear); } catch (NumberFormatException e) { logger.debug(e.getMessage()); result = false; } Interval eventDateInterval = DateUtils.extractDateInterval(eventDate); logger.debug(eventDateInterval); int endDayOfInterval = eventDateInterval.getEnd().getDayOfYear(); // midnight on the next day, so subtract 1 to get the same integer day. if (eventDateInterval.getStart().getDayOfYear() == startDayInt && endDayOfInterval == endDayInt ) { result=true; } else { result = false; } } } return result; }
java
public static boolean isConsistent(String eventDate, String startDayOfYear, String endDayOfYear, String year, String month, String day) { if (isEmpty(eventDate) || (isEmpty(startDayOfYear) && isEmpty(endDayOfYear) && isEmpty(year) && isEmpty(month) && isEmpty(day))) { return true; } // TODO: Add support for eventTime boolean result = false; result = isConsistent(eventDate,year,month,day); logger.debug(result); if ((result || (!isEmpty(eventDate) && isEmpty(year) && isEmpty(month) && isEmpty(day))) && (!isEmpty(startDayOfYear) || !isEmpty(endDayOfYear))) { if (endDayOfYear==null || endDayOfYear.trim().length()==0 || startDayOfYear.trim().equals(endDayOfYear.trim())) { int startDayInt = -1; try { startDayInt = Integer.parseInt(startDayOfYear); } catch (NumberFormatException e) { logger.debug(e.getMessage()); logger.debug(startDayOfYear + " is not an integer."); result = false; } if (DateUtils.extractDate(eventDate)!=null && DateUtils.extractDate(eventDate).getDayOfYear() == startDayInt) { result=true; } else { result = false; } } else { int startDayInt = -1; int endDayInt = -1; try { startDayInt = Integer.parseInt(startDayOfYear); endDayInt = Integer.parseInt(endDayOfYear); } catch (NumberFormatException e) { logger.debug(e.getMessage()); result = false; } Interval eventDateInterval = DateUtils.extractDateInterval(eventDate); logger.debug(eventDateInterval); int endDayOfInterval = eventDateInterval.getEnd().getDayOfYear(); // midnight on the next day, so subtract 1 to get the same integer day. if (eventDateInterval.getStart().getDayOfYear() == startDayInt && endDayOfInterval == endDayInt ) { result=true; } else { result = false; } } } return result; }
[ "public", "static", "boolean", "isConsistent", "(", "String", "eventDate", ",", "String", "startDayOfYear", ",", "String", "endDayOfYear", ",", "String", "year", ",", "String", "month", ",", "String", "day", ")", "{", "if", "(", "isEmpty", "(", "eventDate", ...
Identify whether an event date is consistent with its atomic parts. @param eventDate dwc:eventDate string to compare with atomic parts. @param startDayOfYear dwc:startDayOfYear for comparison with eventDate @param endDayOfYear dwc:endDayOfYear for comparison with eventDate @param year dwc:year for comparison with eventDate @param month dwc:month for comparison with eventDate @param day dwc:day for comparison with eventDate @return true if consistent, or if eventDate is empty, or if all atomic parts are empty, otherwise false.
[ "Identify", "whether", "an", "event", "date", "is", "consistent", "with", "its", "atomic", "parts", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1735-L1779
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.isEmpty
public static boolean isEmpty(String aString) { boolean result = true; if (aString != null && aString.trim().length()>0) { if (!aString.trim().toUpperCase().equals("NULL")) { result = false; } } return result; }
java
public static boolean isEmpty(String aString) { boolean result = true; if (aString != null && aString.trim().length()>0) { if (!aString.trim().toUpperCase().equals("NULL")) { result = false; } } return result; }
[ "public", "static", "boolean", "isEmpty", "(", "String", "aString", ")", "{", "boolean", "result", "=", "true", ";", "if", "(", "aString", "!=", "null", "&&", "aString", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "if", "(",...
Does a string contain a non-blank value. @param aString to check @return true if the string is null, is an empty string, is equal to the value 'NULL' or contains only whitespace.
[ "Does", "a", "string", "contain", "a", "non", "-", "blank", "value", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1857-L1865
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.specificToDay
public static boolean specificToDay(String eventDate) { boolean result = false; if (!isEmpty(eventDate)) { Interval eventDateInterval = extractInterval(eventDate); logger.debug(eventDateInterval); logger.debug(eventDateInterval.toDuration()); if (eventDateInterval.toDuration().getStandardDays()<1l) { result = true; } else if (eventDateInterval.toDuration().getStandardDays()==1l && eventDateInterval.getStart().getDayOfYear()==eventDateInterval.getEnd().getDayOfYear()) { result = true; } } return result; }
java
public static boolean specificToDay(String eventDate) { boolean result = false; if (!isEmpty(eventDate)) { Interval eventDateInterval = extractInterval(eventDate); logger.debug(eventDateInterval); logger.debug(eventDateInterval.toDuration()); if (eventDateInterval.toDuration().getStandardDays()<1l) { result = true; } else if (eventDateInterval.toDuration().getStandardDays()==1l && eventDateInterval.getStart().getDayOfYear()==eventDateInterval.getEnd().getDayOfYear()) { result = true; } } return result; }
[ "public", "static", "boolean", "specificToDay", "(", "String", "eventDate", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "!", "isEmpty", "(", "eventDate", ")", ")", "{", "Interval", "eventDateInterval", "=", "extractInterval", "(", "eventDate",...
Test if an event date specifies a duration of one day or less. @param eventDate to test. @return true if duration is one day or less.
[ "Test", "if", "an", "event", "date", "specifies", "a", "duration", "of", "one", "day", "or", "less", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L1988-L2001
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.specificToDecadeScale
public static boolean specificToDecadeScale(String eventDate) { boolean result = false; if (!isEmpty(eventDate)) { Interval eventDateInterval = extractDateInterval(eventDate); if (eventDateInterval.toDuration().getStandardDays()<=3650l) { result = true; } } return result; }
java
public static boolean specificToDecadeScale(String eventDate) { boolean result = false; if (!isEmpty(eventDate)) { Interval eventDateInterval = extractDateInterval(eventDate); if (eventDateInterval.toDuration().getStandardDays()<=3650l) { result = true; } } return result; }
[ "public", "static", "boolean", "specificToDecadeScale", "(", "String", "eventDate", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "!", "isEmpty", "(", "eventDate", ")", ")", "{", "Interval", "eventDateInterval", "=", "extractDateInterval", "(", ...
Test if an event date specifies a duration of 10 years or less. @param eventDate to test. @return true if duration is 10 years or or less.
[ "Test", "if", "an", "event", "date", "specifies", "a", "duration", "of", "10", "years", "or", "less", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L2047-L2056
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.instantToStringTime
protected static String instantToStringTime(Instant instant) { String result = ""; if (instant!=null) { StringBuffer time = new StringBuffer(); time.append(String.format("%02d",instant.get(DateTimeFieldType.hourOfDay()))); time.append(":").append(String.format("%02d",instant.get(DateTimeFieldType.minuteOfHour()))); time.append(":").append(String.format("%02d",instant.get(DateTimeFieldType.secondOfMinute()))); time.append(".").append(String.format("%03d",instant.get(DateTimeFieldType.millisOfSecond()))); String timeZone = instant.getZone().getID(); if (timeZone.equals("UTC")) { time.append("Z"); } else { time.append(timeZone); } result = time.toString(); } return result; }
java
protected static String instantToStringTime(Instant instant) { String result = ""; if (instant!=null) { StringBuffer time = new StringBuffer(); time.append(String.format("%02d",instant.get(DateTimeFieldType.hourOfDay()))); time.append(":").append(String.format("%02d",instant.get(DateTimeFieldType.minuteOfHour()))); time.append(":").append(String.format("%02d",instant.get(DateTimeFieldType.secondOfMinute()))); time.append(".").append(String.format("%03d",instant.get(DateTimeFieldType.millisOfSecond()))); String timeZone = instant.getZone().getID(); if (timeZone.equals("UTC")) { time.append("Z"); } else { time.append(timeZone); } result = time.toString(); } return result; }
[ "protected", "static", "String", "instantToStringTime", "(", "Instant", "instant", ")", "{", "String", "result", "=", "\"\"", ";", "if", "(", "instant", "!=", "null", ")", "{", "StringBuffer", "time", "=", "new", "StringBuffer", "(", ")", ";", "time", ".",...
Given an instant, return the time within one day that it represents as a string. @param instant to obtain time from. @return string in the form hh:mm:ss.sssZ or an empty string if instant is null.
[ "Given", "an", "instant", "return", "the", "time", "within", "one", "day", "that", "it", "represents", "as", "a", "string", "." ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L2092-L2109
train
FilteredPush/event_date_qc
src/main/java/org/filteredpush/qc/date/DateUtils.java
DateUtils.countLeapDays
public static int countLeapDays(String eventDate) { int result = 0; if (!DateUtils.isEmpty(eventDate) && DateUtils.eventDateValid(eventDate)) { Interval interval = extractInterval(eventDate); Integer sYear = interval.getStart().getYear(); Integer eYear = interval.getEnd().getYear(); String startYear = Integer.toString(sYear).trim(); String endYear = Integer.toString(eYear).trim(); String leapDay = startYear + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result = 1; } } // Range spanning more than one year, check last year if (!endYear.equals(startYear)) { leapDay = endYear + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result++; } } } // Ranges of more than two years, check intermediate years if (eYear > sYear + 1) { for (int testYear = sYear+1; testYear<eYear; testYear++) { leapDay = Integer.toString(testYear).trim() + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result++; } } } } } return result; }
java
public static int countLeapDays(String eventDate) { int result = 0; if (!DateUtils.isEmpty(eventDate) && DateUtils.eventDateValid(eventDate)) { Interval interval = extractInterval(eventDate); Integer sYear = interval.getStart().getYear(); Integer eYear = interval.getEnd().getYear(); String startYear = Integer.toString(sYear).trim(); String endYear = Integer.toString(eYear).trim(); String leapDay = startYear + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result = 1; } } // Range spanning more than one year, check last year if (!endYear.equals(startYear)) { leapDay = endYear + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result++; } } } // Ranges of more than two years, check intermediate years if (eYear > sYear + 1) { for (int testYear = sYear+1; testYear<eYear; testYear++) { leapDay = Integer.toString(testYear).trim() + "-02-29"; logger.debug(leapDay); if (DateUtils.eventDateValid(leapDay)) { if (interval.contains(DateUtils.extractInterval(leapDay))) { result++; } } } } } return result; }
[ "public", "static", "int", "countLeapDays", "(", "String", "eventDate", ")", "{", "int", "result", "=", "0", ";", "if", "(", "!", "DateUtils", ".", "isEmpty", "(", "eventDate", ")", "&&", "DateUtils", ".", "eventDateValid", "(", "eventDate", ")", ")", "{...
Count the number of leap days present in an event date @param eventDate to check for leap days @return number of leap days present in eventDate, 0 if no leap days are present or if eventDate does not contain a date.
[ "Count", "the", "number", "of", "leap", "days", "present", "in", "an", "event", "date" ]
52957a71b94b00b767e37924f976e2c7e8868ff3
https://github.com/FilteredPush/event_date_qc/blob/52957a71b94b00b767e37924f976e2c7e8868ff3/src/main/java/org/filteredpush/qc/date/DateUtils.java#L2534-L2573
train
getlantern/kaleidoscope
src/main/java/org/kaleidoscope/JsonFileRoutingPersistence.java
JsonFileRoutingPersistence.store
@Override public void store(final RandomRoutingTable.Snapshot snapshot) throws IOException { try { saveString(serialize(snapshot)); } catch (final JsonGenerationException e) { throw new IOException("Error serializing routing snapshot", e); } catch (final JsonMappingException e) { throw new IOException("Error serializing routing snapshot", e); } }
java
@Override public void store(final RandomRoutingTable.Snapshot snapshot) throws IOException { try { saveString(serialize(snapshot)); } catch (final JsonGenerationException e) { throw new IOException("Error serializing routing snapshot", e); } catch (final JsonMappingException e) { throw new IOException("Error serializing routing snapshot", e); } }
[ "@", "Override", "public", "void", "store", "(", "final", "RandomRoutingTable", ".", "Snapshot", "snapshot", ")", "throws", "IOException", "{", "try", "{", "saveString", "(", "serialize", "(", "snapshot", ")", ")", ";", "}", "catch", "(", "final", "JsonGener...
Store routing table information via this mechanism. @param snapshot a RandomRoutingTable state
[ "Store", "routing", "table", "information", "via", "this", "mechanism", "." ]
7516f05724c8f54e5d535d23da9116817c08a09f
https://github.com/getlantern/kaleidoscope/blob/7516f05724c8f54e5d535d23da9116817c08a09f/src/main/java/org/kaleidoscope/JsonFileRoutingPersistence.java#L38-L47
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/XmlExporter.java
XmlExporter.buildClassListTag
private <T> String buildClassListTag(final T t) { return (exportClassFullName != null) ? exportClassFullName : t.getClass().getSimpleName() + exportClassEnding; }
java
private <T> String buildClassListTag(final T t) { return (exportClassFullName != null) ? exportClassFullName : t.getClass().getSimpleName() + exportClassEnding; }
[ "private", "<", "T", ">", "String", "buildClassListTag", "(", "final", "T", "t", ")", "{", "return", "(", "exportClassFullName", "!=", "null", ")", "?", "exportClassFullName", ":", "t", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "exp...
Build XML list tag determined by fullname status and ending class phrase @return XML list tag @see #exportClassEnding @see #exportClassFullName
[ "Build", "XML", "list", "tag", "determined", "by", "fullname", "status", "and", "ending", "class", "phrase" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/XmlExporter.java#L152-L156
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.buildDefaultDataTypeMap
private HashMap<Class, String> buildDefaultDataTypeMap() { return new HashMap<Class, String>() {{ put(boolean.class, "BOOLEAN"); put(Boolean.class, "BOOLEAN"); put(byte.class, "BYTE"); put(Byte.class, "BYTE"); put(short.class, "INT"); put(Short.class, "INT"); put(int.class, "INT"); put(Integer.class, "INT"); put(long.class, "BIGINT"); put(Long.class, "BIGINT"); put(float.class, "DOUBLE PRECISION"); put(Float.class, "DOUBLE PRECISION"); put(double.class, "DOUBLE PRECISION"); put(Double.class, "DOUBLE PRECISION"); put(char.class, "CHAR"); put(Character.class, "CHAR"); put(Date.class, "BIGINT"); put(String.class, "VARCHAR"); put(Object.class, "VARCHAR"); put(Timestamp.class, "TIMESTAMP"); put(LocalDate.class, "TIMESTAMP"); put(LocalTime.class, "TIMESTAMP"); put(LocalDateTime.class, "TIMESTAMP"); }}; }
java
private HashMap<Class, String> buildDefaultDataTypeMap() { return new HashMap<Class, String>() {{ put(boolean.class, "BOOLEAN"); put(Boolean.class, "BOOLEAN"); put(byte.class, "BYTE"); put(Byte.class, "BYTE"); put(short.class, "INT"); put(Short.class, "INT"); put(int.class, "INT"); put(Integer.class, "INT"); put(long.class, "BIGINT"); put(Long.class, "BIGINT"); put(float.class, "DOUBLE PRECISION"); put(Float.class, "DOUBLE PRECISION"); put(double.class, "DOUBLE PRECISION"); put(Double.class, "DOUBLE PRECISION"); put(char.class, "CHAR"); put(Character.class, "CHAR"); put(Date.class, "BIGINT"); put(String.class, "VARCHAR"); put(Object.class, "VARCHAR"); put(Timestamp.class, "TIMESTAMP"); put(LocalDate.class, "TIMESTAMP"); put(LocalTime.class, "TIMESTAMP"); put(LocalDateTime.class, "TIMESTAMP"); }}; }
[ "private", "HashMap", "<", "Class", ",", "String", ">", "buildDefaultDataTypeMap", "(", ")", "{", "return", "new", "HashMap", "<", "Class", ",", "String", ">", "(", ")", "{", "{", "put", "(", "boolean", ".", "class", ",", "\"BOOLEAN\"", ")", ";", "put"...
Build default data types @see #dataTypes
[ "Build", "default", "data", "types" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L87-L113
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.buildCreateTableQuery
private String buildCreateTableQuery(final IClassContainer container, final String primaryKeyField) { final StringBuilder builder = new StringBuilder("CREATE TABLE IF NOT EXISTS ") .append(container.getExportClassName().toLowerCase()) .append("(\n"); final String resultValues = container.getFormatSupported(Format.SQL).entrySet().stream() .map(e -> "\t" + buildInsertNameTypeQuery(e.getValue().getExportName(), container)) .collect(Collectors.joining(",\n")); builder.append(resultValues); // Write primary key constraint return builder.append(",\n") .append("\tPRIMARY KEY (") .append(primaryKeyField) .append(")\n);\n") .toString(); }
java
private String buildCreateTableQuery(final IClassContainer container, final String primaryKeyField) { final StringBuilder builder = new StringBuilder("CREATE TABLE IF NOT EXISTS ") .append(container.getExportClassName().toLowerCase()) .append("(\n"); final String resultValues = container.getFormatSupported(Format.SQL).entrySet().stream() .map(e -> "\t" + buildInsertNameTypeQuery(e.getValue().getExportName(), container)) .collect(Collectors.joining(",\n")); builder.append(resultValues); // Write primary key constraint return builder.append(",\n") .append("\tPRIMARY KEY (") .append(primaryKeyField) .append(")\n);\n") .toString(); }
[ "private", "String", "buildCreateTableQuery", "(", "final", "IClassContainer", "container", ",", "final", "String", "primaryKeyField", ")", "{", "final", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "\"CREATE TABLE IF NOT EXISTS \"", ")", ".", "append",...
Create String of Create Table Query
[ "Create", "String", "of", "Create", "Table", "Query" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L132-L150
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.buildInsertNameTypeQuery
private String buildInsertNameTypeQuery(final String finalFieldName, final IClassContainer container) { final Class<?> exportFieldType = container.getField(finalFieldName).getType(); switch (container.getContainer(finalFieldName).getType()) { case ARRAY: case COLLECTION: final Class<?> type = exportFieldType.getComponentType(); return finalFieldName + "\t" + translateJavaTypeToSqlType(type) + "[]"; case ARRAY_2D: final Class<?> type2D = exportFieldType.getComponentType().getComponentType(); return finalFieldName + "\t" + translateJavaTypeToSqlType(type2D) + "[][]"; default: return finalFieldName + "\t" + translateJavaTypeToSqlType(exportFieldType); } }
java
private String buildInsertNameTypeQuery(final String finalFieldName, final IClassContainer container) { final Class<?> exportFieldType = container.getField(finalFieldName).getType(); switch (container.getContainer(finalFieldName).getType()) { case ARRAY: case COLLECTION: final Class<?> type = exportFieldType.getComponentType(); return finalFieldName + "\t" + translateJavaTypeToSqlType(type) + "[]"; case ARRAY_2D: final Class<?> type2D = exportFieldType.getComponentType().getComponentType(); return finalFieldName + "\t" + translateJavaTypeToSqlType(type2D) + "[][]"; default: return finalFieldName + "\t" + translateJavaTypeToSqlType(exportFieldType); } }
[ "private", "String", "buildInsertNameTypeQuery", "(", "final", "String", "finalFieldName", ",", "final", "IClassContainer", "container", ")", "{", "final", "Class", "<", "?", ">", "exportFieldType", "=", "container", ".", "getField", "(", "finalFieldName", ")", "....
Creates String of Create Table Insert Quert @param finalFieldName final field name @return sql create table (name - type)
[ "Creates", "String", "of", "Create", "Table", "Insert", "Quert" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L158-L172
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.buildInsertQuery
private <T> String buildInsertQuery(final T t, final IClassContainer container) { final List<ExportContainer> exportContainers = extractExportContainers(t, container); final StringBuilder builder = new StringBuilder("INSERT INTO ") .append(container.getExportClassName().toLowerCase()) .append(" ("); final String names = exportContainers.stream() .map(ExportContainer::getExportName) .collect(Collectors.joining(", ")); return builder.append(names) .append(") ") .append("VALUES\n") .toString(); }
java
private <T> String buildInsertQuery(final T t, final IClassContainer container) { final List<ExportContainer> exportContainers = extractExportContainers(t, container); final StringBuilder builder = new StringBuilder("INSERT INTO ") .append(container.getExportClassName().toLowerCase()) .append(" ("); final String names = exportContainers.stream() .map(ExportContainer::getExportName) .collect(Collectors.joining(", ")); return builder.append(names) .append(") ") .append("VALUES\n") .toString(); }
[ "private", "<", "T", ">", "String", "buildInsertQuery", "(", "final", "T", "t", ",", "final", "IClassContainer", "container", ")", "{", "final", "List", "<", "ExportContainer", ">", "exportContainers", "=", "extractExportContainers", "(", "t", ",", "container", ...
Build insert query part with values
[ "Build", "insert", "query", "part", "with", "values" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L177-L192
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.format
private <T> String format(final T t, final IClassContainer container) { final List<ExportContainer> exportContainers = extractExportContainers(t, container); final String resultValues = exportContainers.stream() .map(c -> convertFieldValue(container.getField(c.getExportName()), c)) .collect(Collectors.joining(", ")); return "(" + resultValues + ")"; }
java
private <T> String format(final T t, final IClassContainer container) { final List<ExportContainer> exportContainers = extractExportContainers(t, container); final String resultValues = exportContainers.stream() .map(c -> convertFieldValue(container.getField(c.getExportName()), c)) .collect(Collectors.joining(", ")); return "(" + resultValues + ")"; }
[ "private", "<", "T", ">", "String", "format", "(", "final", "T", "t", ",", "final", "IClassContainer", "container", ")", "{", "final", "List", "<", "ExportContainer", ">", "exportContainers", "=", "extractExportContainers", "(", "t", ",", "container", ")", "...
Creates insert query field name
[ "Creates", "insert", "query", "field", "name" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L197-L206
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.isTypeTimestampConvertible
private boolean isTypeTimestampConvertible(final Field field) { return dataTypes.entrySet().stream() .anyMatch(e -> e.getValue().equals("TIMESTAMP") && e.getKey().equals(field.getType())); }
java
private boolean isTypeTimestampConvertible(final Field field) { return dataTypes.entrySet().stream() .anyMatch(e -> e.getValue().equals("TIMESTAMP") && e.getKey().equals(field.getType())); }
[ "private", "boolean", "isTypeTimestampConvertible", "(", "final", "Field", "field", ")", "{", "return", "dataTypes", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "anyMatch", "(", "e", "->", "e", ".", "getValue", "(", ")", ".", "equals", "(", ...
Check data types for field class compatibility with Timestamp class
[ "Check", "data", "types", "for", "field", "class", "compatibility", "with", "Timestamp", "class" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L234-L237
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.convertFieldValue
private String convertFieldValue(final Field field, final ExportContainer container) { final boolean isArray2D = (container.getType() == FieldContainer.Type.ARRAY_2D); if (field.getType().equals(String.class)) { return wrapWithComma(container.getExportValue()); } else if (isTypeTimestampConvertible(field)) { return wrapWithComma(String.valueOf(convertFieldValueToTimestamp(field, container))); } else if (container.getType() == FieldContainer.Type.ARRAY || isArray2D || container.getType() == FieldContainer.Type.COLLECTION) { final Class<?> componentType = extractType(container.getType(), field); final String sqlType = dataTypes.getOrDefault(componentType, "VARCHAR"); final String result = (sqlType.equals("VARCHAR") || sqlType.equals("CHAR")) ? container.getExportValue().replace("[", "{\"").replace("]", "\"}").replace(",", "\",\"").replace(" ", "") : container.getExportValue().replace("[", "{").replace("]", "}"); return wrapWithComma(result); } return container.getExportValue(); }
java
private String convertFieldValue(final Field field, final ExportContainer container) { final boolean isArray2D = (container.getType() == FieldContainer.Type.ARRAY_2D); if (field.getType().equals(String.class)) { return wrapWithComma(container.getExportValue()); } else if (isTypeTimestampConvertible(field)) { return wrapWithComma(String.valueOf(convertFieldValueToTimestamp(field, container))); } else if (container.getType() == FieldContainer.Type.ARRAY || isArray2D || container.getType() == FieldContainer.Type.COLLECTION) { final Class<?> componentType = extractType(container.getType(), field); final String sqlType = dataTypes.getOrDefault(componentType, "VARCHAR"); final String result = (sqlType.equals("VARCHAR") || sqlType.equals("CHAR")) ? container.getExportValue().replace("[", "{\"").replace("]", "\"}").replace(",", "\",\"").replace(" ", "") : container.getExportValue().replace("[", "{").replace("]", "}"); return wrapWithComma(result); } return container.getExportValue(); }
[ "private", "String", "convertFieldValue", "(", "final", "Field", "field", ",", "final", "ExportContainer", "container", ")", "{", "final", "boolean", "isArray2D", "=", "(", "container", ".", "getType", "(", ")", "==", "FieldContainer", ".", "Type", ".", "ARRAY...
Convert container value to Sql specific value type
[ "Convert", "container", "value", "to", "Sql", "specific", "value", "type" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L242-L262
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/SqlExporter.java
SqlExporter.convertFieldValueToTimestamp
private Timestamp convertFieldValueToTimestamp(final Field field, final ExportContainer exportContainer) { if (field.getType().equals(LocalDateTime.class)) { return convertToTimestamp(parseDateTime(exportContainer.getExportValue())); } else if (field.getType().equals(LocalDate.class)) { return convertToTimestamp(parseDate(exportContainer.getExportValue())); } else if (field.getType().equals(LocalTime.class)) { return convertToTimestamp(parseTime(exportContainer.getExportValue())); } else if (field.getType().equals(Date.class)) { return convertToTimestamp(parseSimpleDateLong(exportContainer.getExportValue())); } else if (field.getType().equals(Timestamp.class)) { return Timestamp.valueOf(exportContainer.getExportValue()); } return null; }
java
private Timestamp convertFieldValueToTimestamp(final Field field, final ExportContainer exportContainer) { if (field.getType().equals(LocalDateTime.class)) { return convertToTimestamp(parseDateTime(exportContainer.getExportValue())); } else if (field.getType().equals(LocalDate.class)) { return convertToTimestamp(parseDate(exportContainer.getExportValue())); } else if (field.getType().equals(LocalTime.class)) { return convertToTimestamp(parseTime(exportContainer.getExportValue())); } else if (field.getType().equals(Date.class)) { return convertToTimestamp(parseSimpleDateLong(exportContainer.getExportValue())); } else if (field.getType().equals(Timestamp.class)) { return Timestamp.valueOf(exportContainer.getExportValue()); } return null; }
[ "private", "Timestamp", "convertFieldValueToTimestamp", "(", "final", "Field", "field", ",", "final", "ExportContainer", "exportContainer", ")", "{", "if", "(", "field", ".", "getType", "(", ")", ".", "equals", "(", "LocalDateTime", ".", "class", ")", ")", "{"...
Convert container export value to timestamp value type
[ "Convert", "container", "export", "value", "to", "timestamp", "value", "type" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/SqlExporter.java#L281-L295
train
jayantk/jklol
src/com/jayantkrish/jklol/models/VariableNumMap.java
VariableNumMap.getDiscreteVariables
public final List<DiscreteVariable> getDiscreteVariables() { List<DiscreteVariable> discreteVars = new ArrayList<DiscreteVariable>(); for (int i = 0; i < vars.length; i++) { if (vars[i] instanceof DiscreteVariable) { discreteVars.add((DiscreteVariable) vars[i]); } } return discreteVars; }
java
public final List<DiscreteVariable> getDiscreteVariables() { List<DiscreteVariable> discreteVars = new ArrayList<DiscreteVariable>(); for (int i = 0; i < vars.length; i++) { if (vars[i] instanceof DiscreteVariable) { discreteVars.add((DiscreteVariable) vars[i]); } } return discreteVars; }
[ "public", "final", "List", "<", "DiscreteVariable", ">", "getDiscreteVariables", "(", ")", "{", "List", "<", "DiscreteVariable", ">", "discreteVars", "=", "new", "ArrayList", "<", "DiscreteVariable", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";...
Get the discrete variables in this map, ordered by variable index.
[ "Get", "the", "discrete", "variables", "in", "this", "map", "ordered", "by", "variable", "index", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/VariableNumMap.java#L250-L258
train
jayantk/jklol
src/com/jayantkrish/jklol/models/VariableNumMap.java
VariableNumMap.checkCompatibility
private final void checkCompatibility(VariableNumMap other) { int i = 0, j = 0; int[] otherNums = other.nums; String[] otherNames = other.names; Variable[] otherVars = other.vars; while (i < nums.length && j < otherNums.length) { if (nums[i] < otherNums[j]) { i++; } else if (nums[i] > otherNums[j]) { j++; } else { // Equal Preconditions.checkArgument(names[i].equals(otherNames[j])); Preconditions.checkArgument(vars[i].getName().equals(otherVars[j].getName())); i++; j++; } } }
java
private final void checkCompatibility(VariableNumMap other) { int i = 0, j = 0; int[] otherNums = other.nums; String[] otherNames = other.names; Variable[] otherVars = other.vars; while (i < nums.length && j < otherNums.length) { if (nums[i] < otherNums[j]) { i++; } else if (nums[i] > otherNums[j]) { j++; } else { // Equal Preconditions.checkArgument(names[i].equals(otherNames[j])); Preconditions.checkArgument(vars[i].getName().equals(otherVars[j].getName())); i++; j++; } } }
[ "private", "final", "void", "checkCompatibility", "(", "VariableNumMap", "other", ")", "{", "int", "i", "=", "0", ",", "j", "=", "0", ";", "int", "[", "]", "otherNums", "=", "other", ".", "nums", ";", "String", "[", "]", "otherNames", "=", "other", "...
Ensures that all variable numbers which are shared between other and this are mapped to the same variables.
[ "Ensures", "that", "all", "variable", "numbers", "which", "are", "shared", "between", "other", "and", "this", "are", "mapped", "to", "the", "same", "variables", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/VariableNumMap.java#L522-L539
train
jayantk/jklol
src/com/jayantkrish/jklol/models/VariableNumMap.java
VariableNumMap.outcomeToAssignment
public Assignment outcomeToAssignment(Object[] outcome) { Preconditions.checkArgument(outcome.length == nums.length, "outcome %s cannot be assigned to %s (wrong number of values)", outcome, this); return Assignment.fromSortedArrays(nums, outcome); }
java
public Assignment outcomeToAssignment(Object[] outcome) { Preconditions.checkArgument(outcome.length == nums.length, "outcome %s cannot be assigned to %s (wrong number of values)", outcome, this); return Assignment.fromSortedArrays(nums, outcome); }
[ "public", "Assignment", "outcomeToAssignment", "(", "Object", "[", "]", "outcome", ")", "{", "Preconditions", ".", "checkArgument", "(", "outcome", ".", "length", "==", "nums", ".", "length", ",", "\"outcome %s cannot be assigned to %s (wrong number of values)\"", ",", ...
Get the assignment corresponding to a particular setting of the variables in this factor.
[ "Get", "the", "assignment", "corresponding", "to", "a", "particular", "setting", "of", "the", "variables", "in", "this", "factor", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/VariableNumMap.java#L778-L782
train
jayantk/jklol
src/com/jayantkrish/jklol/models/VariableNumMap.java
VariableNumMap.unionAll
public static VariableNumMap unionAll(Collection<VariableNumMap> varNumMaps) { VariableNumMap curMap = EMPTY; for (VariableNumMap varNumMap : varNumMaps) { curMap = curMap.union(varNumMap); } return curMap; }
java
public static VariableNumMap unionAll(Collection<VariableNumMap> varNumMaps) { VariableNumMap curMap = EMPTY; for (VariableNumMap varNumMap : varNumMaps) { curMap = curMap.union(varNumMap); } return curMap; }
[ "public", "static", "VariableNumMap", "unionAll", "(", "Collection", "<", "VariableNumMap", ">", "varNumMaps", ")", "{", "VariableNumMap", "curMap", "=", "EMPTY", ";", "for", "(", "VariableNumMap", "varNumMap", ":", "varNumMaps", ")", "{", "curMap", "=", "curMap...
Returns the union of all of the passed-in maps, which may not contain conflicting mappings for any variable number. @param varNumMaps @return
[ "Returns", "the", "union", "of", "all", "of", "the", "passed", "-", "in", "maps", "which", "may", "not", "contain", "conflicting", "mappings", "for", "any", "variable", "number", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/VariableNumMap.java#L931-L937
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/util/DaoUtils.java
DaoUtils.getUserByEmail
public static Credentials getUserByEmail(DAO serverDao, String email) throws DAO.DAOException { Query query = new QueryBuilder() .select() .from(Credentials.class) .where(Credentials.EMAIL_KEY, OPERAND.EQ,email) .build(); TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query)); if(to==null){ return null; } else { return to(Credentials.class, to); } }
java
public static Credentials getUserByEmail(DAO serverDao, String email) throws DAO.DAOException { Query query = new QueryBuilder() .select() .from(Credentials.class) .where(Credentials.EMAIL_KEY, OPERAND.EQ,email) .build(); TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query)); if(to==null){ return null; } else { return to(Credentials.class, to); } }
[ "public", "static", "Credentials", "getUserByEmail", "(", "DAO", "serverDao", ",", "String", "email", ")", "throws", "DAO", ".", "DAOException", "{", "Query", "query", "=", "new", "QueryBuilder", "(", ")", ".", "select", "(", ")", ".", "from", "(", "Creden...
Convience method to do a Credentials query against an email address @param serverDao dao object to query against. @param email email address used in query. @return Credentials object found or null. @throws io.divide.shared.server.DAO.DAOException
[ "Convience", "method", "to", "do", "a", "Credentials", "query", "against", "an", "email", "address" ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/util/DaoUtils.java#L38-L51
train
HiddenStage/divide
Shared/src/main/java/io/divide/shared/util/DaoUtils.java
DaoUtils.getUserById
public static Credentials getUserById(DAO serverDao, String userId) throws DAO.DAOException { Query query = new QueryBuilder() .select() .from(Credentials.class) .where(Credentials.OWNER_ID_KEY,OPERAND.EQ,userId) .build(); TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query)); if(to==null){ return null; } else { return to(Credentials.class,to); } }
java
public static Credentials getUserById(DAO serverDao, String userId) throws DAO.DAOException { Query query = new QueryBuilder() .select() .from(Credentials.class) .where(Credentials.OWNER_ID_KEY,OPERAND.EQ,userId) .build(); TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query)); if(to==null){ return null; } else { return to(Credentials.class,to); } }
[ "public", "static", "Credentials", "getUserById", "(", "DAO", "serverDao", ",", "String", "userId", ")", "throws", "DAO", ".", "DAOException", "{", "Query", "query", "=", "new", "QueryBuilder", "(", ")", ".", "select", "(", ")", ".", "from", "(", "Credenti...
Convience method to do a Credentials query against an user id. @param serverDao dao object to query against. @param userId user id used in query. @return Credentials object found or null. @throws io.divide.shared.server.DAO.DAOException
[ "Convience", "method", "to", "do", "a", "Credentials", "query", "against", "an", "user", "id", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/util/DaoUtils.java#L60-L73
train
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/Password.java
Password.getSalt
private static String getSalt(byte[] value) { byte[] salt = new byte[Generate.SALT_BYTES]; System.arraycopy(value, 0, salt, 0, salt.length); return ByteArray.toBase64(salt); }
java
private static String getSalt(byte[] value) { byte[] salt = new byte[Generate.SALT_BYTES]; System.arraycopy(value, 0, salt, 0, salt.length); return ByteArray.toBase64(salt); }
[ "private", "static", "String", "getSalt", "(", "byte", "[", "]", "value", ")", "{", "byte", "[", "]", "salt", "=", "new", "byte", "[", "Generate", ".", "SALT_BYTES", "]", ";", "System", ".", "arraycopy", "(", "value", ",", "0", ",", "salt", ",", "0...
Retrieves the salt from the given value. @param value The overall password hash value. @return The salt, which is the first {@value Generate#SALT_BYTES} bytes of the
[ "Retrieves", "the", "salt", "from", "the", "given", "value", "." ]
e67954181a04ffc9beb1d9abca1421195fcf9764
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/Password.java#L150-L155
train
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/Password.java
Password.getHash
private static byte[] getHash(byte[] value) { byte[] hash = new byte[value.length - Generate.SALT_BYTES]; System.arraycopy(value, Generate.SALT_BYTES, hash, 0, hash.length); return hash; }
java
private static byte[] getHash(byte[] value) { byte[] hash = new byte[value.length - Generate.SALT_BYTES]; System.arraycopy(value, Generate.SALT_BYTES, hash, 0, hash.length); return hash; }
[ "private", "static", "byte", "[", "]", "getHash", "(", "byte", "[", "]", "value", ")", "{", "byte", "[", "]", "hash", "=", "new", "byte", "[", "value", ".", "length", "-", "Generate", ".", "SALT_BYTES", "]", ";", "System", ".", "arraycopy", "(", "v...
Retrieves the hash from the given value. @param value The overall password hash value. @return The salt, which is the first {@value Generate#SALT_BYTES} bytes of the
[ "Retrieves", "the", "hash", "from", "the", "given", "value", "." ]
e67954181a04ffc9beb1d9abca1421195fcf9764
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/Password.java#L163-L168
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/ParametricCcgParser.java
ParametricCcgParser.getNewSufficientStatistics
@Override public SufficientStatistics getNewSufficientStatistics() { List<SufficientStatistics> lexiconParameterList = Lists.newArrayList(); List<String> lexiconParameterNames = Lists.newArrayList(); for (int i = 0; i < lexiconFamilies.size(); i++) { ParametricCcgLexicon lexiconFamily = lexiconFamilies.get(i); lexiconParameterList.add(lexiconFamily.getNewSufficientStatistics()); lexiconParameterNames.add(Integer.toString(i)); } SufficientStatistics lexiconParameters = new ListSufficientStatistics( lexiconParameterNames, lexiconParameterList); List<SufficientStatistics> lexiconScorerParameterList = Lists.newArrayList(); List<String> lexiconScorerParameterNames = Lists.newArrayList(); for (int i = 0; i < lexiconScorerFamilies.size(); i++) { ParametricLexiconScorer lexiconScorerFamily = lexiconScorerFamilies.get(i); lexiconScorerParameterList.add(lexiconScorerFamily.getNewSufficientStatistics()); lexiconScorerParameterNames.add(Integer.toString(i)); } SufficientStatistics lexiconScorerParameters = new ListSufficientStatistics( lexiconScorerParameterNames, lexiconScorerParameterList); SufficientStatistics wordSkipParameters = ListSufficientStatistics.empty(); if (wordSkipFamily != null) { wordSkipParameters = wordSkipFamily.getNewSufficientStatistics(); } SufficientStatistics dependencyParameters = dependencyFamily.getNewSufficientStatistics(); SufficientStatistics wordDistanceParameters = wordDistanceFamily.getNewSufficientStatistics(); SufficientStatistics puncDistanceParameters = puncDistanceFamily.getNewSufficientStatistics(); SufficientStatistics verbDistanceParameters = verbDistanceFamily.getNewSufficientStatistics(); SufficientStatistics syntaxParameters = syntaxFamily.getNewSufficientStatistics(); SufficientStatistics unaryRuleParameters = unaryRuleFamily.getNewSufficientStatistics(); SufficientStatistics headedBinaryRuleParameters = headedBinaryRuleFamily.getNewSufficientStatistics(); SufficientStatistics rootSyntaxParameters = rootSyntaxFamily.getNewSufficientStatistics(); SufficientStatistics headedRootSyntaxParameters = headedRootSyntaxFamily.getNewSufficientStatistics(); return new ListSufficientStatistics(STATISTIC_NAME_LIST, Arrays.asList(lexiconParameters, lexiconScorerParameters, wordSkipParameters, dependencyParameters, wordDistanceParameters, puncDistanceParameters, verbDistanceParameters, syntaxParameters, unaryRuleParameters, headedBinaryRuleParameters, rootSyntaxParameters, headedRootSyntaxParameters)); }
java
@Override public SufficientStatistics getNewSufficientStatistics() { List<SufficientStatistics> lexiconParameterList = Lists.newArrayList(); List<String> lexiconParameterNames = Lists.newArrayList(); for (int i = 0; i < lexiconFamilies.size(); i++) { ParametricCcgLexicon lexiconFamily = lexiconFamilies.get(i); lexiconParameterList.add(lexiconFamily.getNewSufficientStatistics()); lexiconParameterNames.add(Integer.toString(i)); } SufficientStatistics lexiconParameters = new ListSufficientStatistics( lexiconParameterNames, lexiconParameterList); List<SufficientStatistics> lexiconScorerParameterList = Lists.newArrayList(); List<String> lexiconScorerParameterNames = Lists.newArrayList(); for (int i = 0; i < lexiconScorerFamilies.size(); i++) { ParametricLexiconScorer lexiconScorerFamily = lexiconScorerFamilies.get(i); lexiconScorerParameterList.add(lexiconScorerFamily.getNewSufficientStatistics()); lexiconScorerParameterNames.add(Integer.toString(i)); } SufficientStatistics lexiconScorerParameters = new ListSufficientStatistics( lexiconScorerParameterNames, lexiconScorerParameterList); SufficientStatistics wordSkipParameters = ListSufficientStatistics.empty(); if (wordSkipFamily != null) { wordSkipParameters = wordSkipFamily.getNewSufficientStatistics(); } SufficientStatistics dependencyParameters = dependencyFamily.getNewSufficientStatistics(); SufficientStatistics wordDistanceParameters = wordDistanceFamily.getNewSufficientStatistics(); SufficientStatistics puncDistanceParameters = puncDistanceFamily.getNewSufficientStatistics(); SufficientStatistics verbDistanceParameters = verbDistanceFamily.getNewSufficientStatistics(); SufficientStatistics syntaxParameters = syntaxFamily.getNewSufficientStatistics(); SufficientStatistics unaryRuleParameters = unaryRuleFamily.getNewSufficientStatistics(); SufficientStatistics headedBinaryRuleParameters = headedBinaryRuleFamily.getNewSufficientStatistics(); SufficientStatistics rootSyntaxParameters = rootSyntaxFamily.getNewSufficientStatistics(); SufficientStatistics headedRootSyntaxParameters = headedRootSyntaxFamily.getNewSufficientStatistics(); return new ListSufficientStatistics(STATISTIC_NAME_LIST, Arrays.asList(lexiconParameters, lexiconScorerParameters, wordSkipParameters, dependencyParameters, wordDistanceParameters, puncDistanceParameters, verbDistanceParameters, syntaxParameters, unaryRuleParameters, headedBinaryRuleParameters, rootSyntaxParameters, headedRootSyntaxParameters)); }
[ "@", "Override", "public", "SufficientStatistics", "getNewSufficientStatistics", "(", ")", "{", "List", "<", "SufficientStatistics", ">", "lexiconParameterList", "=", "Lists", ".", "newArrayList", "(", ")", ";", "List", "<", "String", ">", "lexiconParameterNames", "...
Gets a new all-zero parameter vector. @return
[ "Gets", "a", "new", "all", "-", "zero", "parameter", "vector", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/ParametricCcgParser.java#L492-L533
train
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/Backend.java
Backend.init
public static synchronized <BackendType extends Backend> BackendType init(Config<BackendType> config) { // if(initialized) throw new RuntimeException("Backend already initialized!"); logger.debug("Initializing... " + config); Guice.createInjector(config.getModule()); return injector.getInstance(config.getModuleType()); }
java
public static synchronized <BackendType extends Backend> BackendType init(Config<BackendType> config) { // if(initialized) throw new RuntimeException("Backend already initialized!"); logger.debug("Initializing... " + config); Guice.createInjector(config.getModule()); return injector.getInstance(config.getModuleType()); }
[ "public", "static", "synchronized", "<", "BackendType", "extends", "Backend", ">", "BackendType", "init", "(", "Config", "<", "BackendType", ">", "config", ")", "{", "// if(initialized) throw new RuntimeException(\"Backend already initialized!\");", "logger", ".", "d...
Initialization point for divide. Returns an instance of the Divide object. Only one instance may exist at a time. @param config Configuration information for Divide. @see Config @param <BackendType> Specific type of Backend to return, for extentions on the Backend class. @return
[ "Initialization", "point", "for", "divide", ".", "Returns", "an", "instance", "of", "the", "Divide", "object", ".", "Only", "one", "instance", "may", "exist", "at", "a", "time", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/Backend.java#L74-L80
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/util/BasicCastUtils.java
BasicCastUtils.getGenericType
public static Type getGenericType(final Type type, final int paramNumber) { try { final ParameterizedType parameterizedType = ((ParameterizedType) type); return (parameterizedType.getActualTypeArguments().length < paramNumber) ? Object.class : parameterizedType.getActualTypeArguments()[paramNumber]; } catch (Exception e) { return Object.class; } }
java
public static Type getGenericType(final Type type, final int paramNumber) { try { final ParameterizedType parameterizedType = ((ParameterizedType) type); return (parameterizedType.getActualTypeArguments().length < paramNumber) ? Object.class : parameterizedType.getActualTypeArguments()[paramNumber]; } catch (Exception e) { return Object.class; } }
[ "public", "static", "Type", "getGenericType", "(", "final", "Type", "type", ",", "final", "int", "paramNumber", ")", "{", "try", "{", "final", "ParameterizedType", "parameterizedType", "=", "(", "(", "ParameterizedType", ")", "type", ")", ";", "return", "(", ...
Extracts generic type @param type to extract from @param paramNumber actual param number in parameterized type array @return actual type or object if length is not presented
[ "Extracts", "generic", "type" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/util/BasicCastUtils.java#L124-L134
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/util/BasicCastUtils.java
BasicCastUtils.areEquals
public static boolean areEquals(final Class<?> firstClass, final Class<?> secondClass) { final boolean isFirstShort = firstClass.isAssignableFrom(Short.class); final boolean isSecondShort = secondClass.isAssignableFrom(Short.class); if (isFirstShort && isSecondShort || isFirstShort && secondClass.equals(short.class) || firstClass.equals(short.class) && isSecondShort) return true; final boolean isFirstByte = firstClass.isAssignableFrom(Byte.class); final boolean isSecondByte = secondClass.isAssignableFrom(Byte.class); if (isFirstByte && isSecondByte || isFirstByte && secondClass.equals(byte.class) || firstClass.equals(byte.class) && isSecondByte) return true; final boolean isFirstInt = firstClass.isAssignableFrom(Integer.class); final boolean isSecondInt = secondClass.isAssignableFrom(Integer.class); if (isFirstInt && isSecondInt || isFirstInt && secondClass.equals(int.class) || firstClass.equals(int.class) && isSecondInt) return true; final boolean isFirstLong = firstClass.isAssignableFrom(Long.class); final boolean isSecondLong = secondClass.isAssignableFrom(Long.class); if (isFirstLong && isSecondLong || isFirstLong && secondClass.equals(long.class) || firstClass.equals(long.class) && isSecondLong) return true; final boolean isFirstDouble = firstClass.isAssignableFrom(Double.class); final boolean isSecondDouble = secondClass.isAssignableFrom(Double.class); if (isFirstDouble && isSecondDouble || isFirstDouble && secondClass.equals(double.class) || firstClass.equals(double.class) && isSecondDouble) return true; final boolean isFirstFloat = firstClass.isAssignableFrom(Float.class); final boolean isSecondFloat = secondClass.isAssignableFrom(Float.class); if (isFirstFloat && isSecondFloat || isFirstFloat && secondClass.equals(float.class) || firstClass.equals(float.class) && isSecondFloat) return true; final boolean isFirstChar = firstClass.isAssignableFrom(Character.class); final boolean isSecondChar = secondClass.isAssignableFrom(Character.class); if (isFirstChar && isSecondChar || isFirstChar && secondClass.equals(char.class) || firstClass.equals(char.class) && isSecondChar) return true; final boolean isFirstBool = firstClass.isAssignableFrom(Boolean.class); final boolean isSecondBool = secondClass.isAssignableFrom(Boolean.class); if (isFirstBool && isSecondBool || isFirstChar && secondClass.equals(boolean.class) || firstClass.equals(boolean.class) && isSecondChar) return true; return firstClass.equals(secondClass); }
java
public static boolean areEquals(final Class<?> firstClass, final Class<?> secondClass) { final boolean isFirstShort = firstClass.isAssignableFrom(Short.class); final boolean isSecondShort = secondClass.isAssignableFrom(Short.class); if (isFirstShort && isSecondShort || isFirstShort && secondClass.equals(short.class) || firstClass.equals(short.class) && isSecondShort) return true; final boolean isFirstByte = firstClass.isAssignableFrom(Byte.class); final boolean isSecondByte = secondClass.isAssignableFrom(Byte.class); if (isFirstByte && isSecondByte || isFirstByte && secondClass.equals(byte.class) || firstClass.equals(byte.class) && isSecondByte) return true; final boolean isFirstInt = firstClass.isAssignableFrom(Integer.class); final boolean isSecondInt = secondClass.isAssignableFrom(Integer.class); if (isFirstInt && isSecondInt || isFirstInt && secondClass.equals(int.class) || firstClass.equals(int.class) && isSecondInt) return true; final boolean isFirstLong = firstClass.isAssignableFrom(Long.class); final boolean isSecondLong = secondClass.isAssignableFrom(Long.class); if (isFirstLong && isSecondLong || isFirstLong && secondClass.equals(long.class) || firstClass.equals(long.class) && isSecondLong) return true; final boolean isFirstDouble = firstClass.isAssignableFrom(Double.class); final boolean isSecondDouble = secondClass.isAssignableFrom(Double.class); if (isFirstDouble && isSecondDouble || isFirstDouble && secondClass.equals(double.class) || firstClass.equals(double.class) && isSecondDouble) return true; final boolean isFirstFloat = firstClass.isAssignableFrom(Float.class); final boolean isSecondFloat = secondClass.isAssignableFrom(Float.class); if (isFirstFloat && isSecondFloat || isFirstFloat && secondClass.equals(float.class) || firstClass.equals(float.class) && isSecondFloat) return true; final boolean isFirstChar = firstClass.isAssignableFrom(Character.class); final boolean isSecondChar = secondClass.isAssignableFrom(Character.class); if (isFirstChar && isSecondChar || isFirstChar && secondClass.equals(char.class) || firstClass.equals(char.class) && isSecondChar) return true; final boolean isFirstBool = firstClass.isAssignableFrom(Boolean.class); final boolean isSecondBool = secondClass.isAssignableFrom(Boolean.class); if (isFirstBool && isSecondBool || isFirstChar && secondClass.equals(boolean.class) || firstClass.equals(boolean.class) && isSecondChar) return true; return firstClass.equals(secondClass); }
[ "public", "static", "boolean", "areEquals", "(", "final", "Class", "<", "?", ">", "firstClass", ",", "final", "Class", "<", "?", ">", "secondClass", ")", "{", "final", "boolean", "isFirstShort", "=", "firstClass", ".", "isAssignableFrom", "(", "Short", ".", ...
Check if objects have equals types, even if they are primitive
[ "Check", "if", "objects", "have", "equals", "types", "even", "if", "they", "are", "primitive" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/util/BasicCastUtils.java#L169-L228
train
ivanceras/orm
src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java
SynchronousEntityManager.insert
@Override public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys) throws DatabaseException{ ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName()); if(excludePrimaryKeys){ dao.add_IgnoreColumn( model.getPrimaryAttributes()); } return insertRecord(dao, model, true); }
java
@Override public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys) throws DatabaseException{ ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName()); if(excludePrimaryKeys){ dao.add_IgnoreColumn( model.getPrimaryAttributes()); } return insertRecord(dao, model, true); }
[ "@", "Override", "public", "<", "T", "extends", "DAO", ">", "T", "insert", "(", "DAO", "dao", ",", "boolean", "excludePrimaryKeys", ")", "throws", "DatabaseException", "{", "ModelDef", "model", "=", "db", ".", "getModelMetaDataDefinition", "(", ")", ".", "ge...
The primary keys should have defaults on the database to make this work
[ "The", "primary", "keys", "should", "have", "defaults", "on", "the", "database", "to", "make", "this", "work" ]
e63213cb8abefd11df0e2d34b1c95477788e600e
https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java#L280-L287
train
ivanceras/orm
src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java
SynchronousEntityManager.insertNoChangeLog
@Override public <T extends DAO> T insertNoChangeLog(DAO dao, ModelDef model) throws DatabaseException{ DAO ret = db.insert(dao, null, model, null); Class<? extends DAO> clazz = getDaoClass(dao.getModelName()); return cast(clazz, ret); }
java
@Override public <T extends DAO> T insertNoChangeLog(DAO dao, ModelDef model) throws DatabaseException{ DAO ret = db.insert(dao, null, model, null); Class<? extends DAO> clazz = getDaoClass(dao.getModelName()); return cast(clazz, ret); }
[ "@", "Override", "public", "<", "T", "extends", "DAO", ">", "T", "insertNoChangeLog", "(", "DAO", "dao", ",", "ModelDef", "model", ")", "throws", "DatabaseException", "{", "DAO", "ret", "=", "db", ".", "insert", "(", "dao", ",", "null", ",", "model", "...
Insert the record without bothering changelog, to avoid infinite method recursive calls when inserting changelogs into record_changelog table @param dao @param model @return @throws DatabaseException
[ "Insert", "the", "record", "without", "bothering", "changelog", "to", "avoid", "infinite", "method", "recursive", "calls", "when", "inserting", "changelogs", "into", "record_changelog", "table" ]
e63213cb8abefd11df0e2d34b1c95477788e600e
https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java#L301-L306
train
cpollet/jixture
core/src/main/java/net/cpollet/jixture/fixtures/MappingFixture.java
MappingFixture.addObjects
@Override public Fixture addObjects(Object... objectsToAdd) { if (0 < objectsToAdd.length) { Collections.addAll(objects, objectsToAdd); } return this; }
java
@Override public Fixture addObjects(Object... objectsToAdd) { if (0 < objectsToAdd.length) { Collections.addAll(objects, objectsToAdd); } return this; }
[ "@", "Override", "public", "Fixture", "addObjects", "(", "Object", "...", "objectsToAdd", ")", "{", "if", "(", "0", "<", "objectsToAdd", ".", "length", ")", "{", "Collections", ".", "addAll", "(", "objects", ",", "objectsToAdd", ")", ";", "}", "return", ...
Add entities to the current list of entities to load. @param objectsToAdd the list of entities to add. Objects are loaded in order. @return the current fixture instance.
[ "Add", "entities", "to", "the", "current", "list", "of", "entities", "to", "load", "." ]
faef0d4991f81c2cdb5be3ba24176636ef0cc433
https://github.com/cpollet/jixture/blob/faef0d4991f81c2cdb5be3ba24176636ef0cc433/core/src/main/java/net/cpollet/jixture/fixtures/MappingFixture.java#L49-L56
train
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/HashMac.java
HashMac.digest
public String digest(String message) { try { Mac mac = Mac.getInstance(algorithm); SecretKeySpec macKey = new SecretKeySpec(key, algorithm); mac.init(macKey); byte[] digest = mac.doFinal(ByteArray.fromString(message)); return ByteArray.toHex(digest); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm unavailable: " + algorithm, e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("Unable to construct key for " + algorithm + ". Please check the value passed in when this class was initialised.", e); } }
java
public String digest(String message) { try { Mac mac = Mac.getInstance(algorithm); SecretKeySpec macKey = new SecretKeySpec(key, algorithm); mac.init(macKey); byte[] digest = mac.doFinal(ByteArray.fromString(message)); return ByteArray.toHex(digest); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm unavailable: " + algorithm, e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("Unable to construct key for " + algorithm + ". Please check the value passed in when this class was initialised.", e); } }
[ "public", "String", "digest", "(", "String", "message", ")", "{", "try", "{", "Mac", "mac", "=", "Mac", ".", "getInstance", "(", "algorithm", ")", ";", "SecretKeySpec", "macKey", "=", "new", "SecretKeySpec", "(", "key", ",", "algorithm", ")", ";", "mac",...
Computes an HMAC for the given message, using the key passed to the constructor. @param message The message. @return The HMAC value for the message and key.
[ "Computes", "an", "HMAC", "for", "the", "given", "message", "using", "the", "key", "passed", "to", "the", "constructor", "." ]
e67954181a04ffc9beb1d9abca1421195fcf9764
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/HashMac.java#L66-L80
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/CcgParser.java
CcgParser.reweightRootEntries
public void reweightRootEntries(CcgChart chart) { int spanStart = 0; int spanEnd = chart.size() - 1; int numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd); // Apply unary rules. ChartEntry[] entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd), numChartEntries); double[] probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd), numChartEntries); chart.clearChartEntriesForSpan(spanStart, spanEnd); for (int i = 0; i < entries.length; i++) { chart.addChartEntryForSpan(entries[i], probs[i], spanStart, spanEnd, syntaxVarType); applyUnaryRules(chart, entries[i], probs[i], spanStart, spanEnd); } chart.doneAddingChartEntriesForSpan(spanStart, spanEnd); // Apply root factor. numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd); entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd), numChartEntries); probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd), numChartEntries); chart.clearChartEntriesForSpan(spanStart, spanEnd); for (int i = 0; i < entries.length; i++) { ChartEntry entry = entries[i]; double rootProb = scoreRootEntry(entry, chart); chart.addChartEntryForSpan(entry, probs[i] * rootProb, spanStart, spanEnd, syntaxVarType); } chart.doneAddingChartEntriesForSpan(spanStart, spanEnd); }
java
public void reweightRootEntries(CcgChart chart) { int spanStart = 0; int spanEnd = chart.size() - 1; int numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd); // Apply unary rules. ChartEntry[] entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd), numChartEntries); double[] probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd), numChartEntries); chart.clearChartEntriesForSpan(spanStart, spanEnd); for (int i = 0; i < entries.length; i++) { chart.addChartEntryForSpan(entries[i], probs[i], spanStart, spanEnd, syntaxVarType); applyUnaryRules(chart, entries[i], probs[i], spanStart, spanEnd); } chart.doneAddingChartEntriesForSpan(spanStart, spanEnd); // Apply root factor. numChartEntries = chart.getNumChartEntriesForSpan(spanStart, spanEnd); entries = CcgBeamSearchChart.copyChartEntryArray(chart.getChartEntriesForSpan(spanStart, spanEnd), numChartEntries); probs = ArrayUtils.copyOf(chart.getChartEntryProbsForSpan(spanStart, spanEnd), numChartEntries); chart.clearChartEntriesForSpan(spanStart, spanEnd); for (int i = 0; i < entries.length; i++) { ChartEntry entry = entries[i]; double rootProb = scoreRootEntry(entry, chart); chart.addChartEntryForSpan(entry, probs[i] * rootProb, spanStart, spanEnd, syntaxVarType); } chart.doneAddingChartEntriesForSpan(spanStart, spanEnd); }
[ "public", "void", "reweightRootEntries", "(", "CcgChart", "chart", ")", "{", "int", "spanStart", "=", "0", ";", "int", "spanEnd", "=", "chart", ".", "size", "(", ")", "-", "1", ";", "int", "numChartEntries", "=", "chart", ".", "getNumChartEntriesForSpan", ...
Updates entries in the beam for the root node with a factor for the root syntactic category and any unary rules. @param chart
[ "Updates", "entries", "in", "the", "beam", "for", "the", "root", "node", "with", "a", "factor", "for", "the", "root", "syntactic", "category", "and", "any", "unary", "rules", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgParser.java#L780-L812
train
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/data/DataManager.java
DataManager.send
public <B extends BackendObject> Observable<Void> send(final Collection<B> objects){ return getWebService().save(isLoggedIn(),objects) .subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
java
public <B extends BackendObject> Observable<Void> send(final Collection<B> objects){ return getWebService().save(isLoggedIn(),objects) .subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
[ "public", "<", "B", "extends", "BackendObject", ">", "Observable", "<", "Void", ">", "send", "(", "final", "Collection", "<", "B", ">", "objects", ")", "{", "return", "getWebService", "(", ")", ".", "save", "(", "isLoggedIn", "(", ")", ",", "objects", ...
Function used to save objects on remote server. @param objects Collection of objects to be saved. @param <B> Object type that extends BackendObject. @return Observable, no entity returned.
[ "Function", "used", "to", "save", "objects", "on", "remote", "server", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/data/DataManager.java#L60-L63
train
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/data/DataManager.java
DataManager.get
public <B extends BackendObject> Observable<Collection<B>> get(final Class<B> type, final Collection<String> objects){ return Observable.create(new Observable.OnSubscribe<Collection<B>>() { @Override public void call(Subscriber<? super Collection<B>> observer) { try { observer.onNext(convertRequest(getArrayType(type), getWebService().get(isLoggedIn(),Query.safeTable(type), objects))); observer.onCompleted(); } catch (Exception e) { observer.onError(e); } } }).subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
java
public <B extends BackendObject> Observable<Collection<B>> get(final Class<B> type, final Collection<String> objects){ return Observable.create(new Observable.OnSubscribe<Collection<B>>() { @Override public void call(Subscriber<? super Collection<B>> observer) { try { observer.onNext(convertRequest(getArrayType(type), getWebService().get(isLoggedIn(),Query.safeTable(type), objects))); observer.onCompleted(); } catch (Exception e) { observer.onError(e); } } }).subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
[ "public", "<", "B", "extends", "BackendObject", ">", "Observable", "<", "Collection", "<", "B", ">", ">", "get", "(", "final", "Class", "<", "B", ">", "type", ",", "final", "Collection", "<", "String", ">", "objects", ")", "{", "return", "Observable", ...
Function used to return specific objects corrosponding to the object keys provided. @param type Type of objects to be returned, if an object of a key provided does not match Type, it will not be returned. @param objects Collection of keys you wish to return from remote server. @param <B> Class type to be returned, extends BackendObject. @return Collection of objects corrosponding to keys provided.
[ "Function", "used", "to", "return", "specific", "objects", "corrosponding", "to", "the", "object", "keys", "provided", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/data/DataManager.java#L72-L85
train
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/data/DataManager.java
DataManager.count
public <B extends BackendObject> Observable<Integer> count(final Class<B> type){ return getWebService().count(isLoggedIn(),Query.safeTable(type)) .subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
java
public <B extends BackendObject> Observable<Integer> count(final Class<B> type){ return getWebService().count(isLoggedIn(),Query.safeTable(type)) .subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
[ "public", "<", "B", "extends", "BackendObject", ">", "Observable", "<", "Integer", ">", "count", "(", "final", "Class", "<", "B", ">", "type", ")", "{", "return", "getWebService", "(", ")", ".", "count", "(", "isLoggedIn", "(", ")", ",", "Query", ".", ...
Functin used to perform a count query against remote sever for specifed type. @param type Type to be counted. @param <B> Type extending BackendObject @return Count of objects on remote server matching specified type.
[ "Functin", "used", "to", "perform", "a", "count", "query", "against", "remote", "sever", "for", "specifed", "type", "." ]
14e36598c50d92b4393e6649915e32b86141c598
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/data/DataManager.java#L114-L117
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/CcgGrammarUtils.java
CcgGrammarUtils.getSyntacticCategoryClosure
public static Set<HeadedSyntacticCategory> getSyntacticCategoryClosure( Collection<HeadedSyntacticCategory> syntacticCategories) { Set<String> featureValues = Sets.newHashSet(); for (HeadedSyntacticCategory cat : syntacticCategories) { getAllFeatureValues(cat.getSyntax(), featureValues); } // Compute the closure of syntactic categories, assuming the only // operations are function application and feature assignment. Queue<HeadedSyntacticCategory> unprocessed = new LinkedList<HeadedSyntacticCategory>(); unprocessed.addAll(syntacticCategories); Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet(); while (unprocessed.size() > 0) { HeadedSyntacticCategory cat = unprocessed.poll(); Preconditions.checkArgument(cat.isCanonicalForm()); allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues))); if (!cat.isAtomic()) { HeadedSyntacticCategory ret = cat.getReturnType().getCanonicalForm(); if (!allCategories.contains(ret) && !unprocessed.contains(ret)) { unprocessed.offer(ret); } HeadedSyntacticCategory arg = cat.getArgumentType().getCanonicalForm(); if (!allCategories.contains(arg) && !unprocessed.contains(arg)) { unprocessed.offer(arg); } } } // XXX: jayantk 1/8/2016 I think this loop does exactly the same thing as // the previous one. /* Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet(); for (HeadedSyntacticCategory cat : syntacticCategories) { Preconditions.checkArgument(cat.isCanonicalForm()); allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues))); while (!cat.getSyntax().isAtomic()) { allCategories.addAll(canonicalizeCategories(cat.getArgumentType().getCanonicalForm().getSubcategories(featureValues))); allCategories.addAll(canonicalizeCategories(cat.getReturnType().getCanonicalForm().getSubcategories(featureValues))); cat = cat.getReturnType(); } } */ return allCategories; }
java
public static Set<HeadedSyntacticCategory> getSyntacticCategoryClosure( Collection<HeadedSyntacticCategory> syntacticCategories) { Set<String> featureValues = Sets.newHashSet(); for (HeadedSyntacticCategory cat : syntacticCategories) { getAllFeatureValues(cat.getSyntax(), featureValues); } // Compute the closure of syntactic categories, assuming the only // operations are function application and feature assignment. Queue<HeadedSyntacticCategory> unprocessed = new LinkedList<HeadedSyntacticCategory>(); unprocessed.addAll(syntacticCategories); Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet(); while (unprocessed.size() > 0) { HeadedSyntacticCategory cat = unprocessed.poll(); Preconditions.checkArgument(cat.isCanonicalForm()); allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues))); if (!cat.isAtomic()) { HeadedSyntacticCategory ret = cat.getReturnType().getCanonicalForm(); if (!allCategories.contains(ret) && !unprocessed.contains(ret)) { unprocessed.offer(ret); } HeadedSyntacticCategory arg = cat.getArgumentType().getCanonicalForm(); if (!allCategories.contains(arg) && !unprocessed.contains(arg)) { unprocessed.offer(arg); } } } // XXX: jayantk 1/8/2016 I think this loop does exactly the same thing as // the previous one. /* Set<HeadedSyntacticCategory> allCategories = Sets.newHashSet(); for (HeadedSyntacticCategory cat : syntacticCategories) { Preconditions.checkArgument(cat.isCanonicalForm()); allCategories.addAll(canonicalizeCategories(cat.getSubcategories(featureValues))); while (!cat.getSyntax().isAtomic()) { allCategories.addAll(canonicalizeCategories(cat.getArgumentType().getCanonicalForm().getSubcategories(featureValues))); allCategories.addAll(canonicalizeCategories(cat.getReturnType().getCanonicalForm().getSubcategories(featureValues))); cat = cat.getReturnType(); } } */ return allCategories; }
[ "public", "static", "Set", "<", "HeadedSyntacticCategory", ">", "getSyntacticCategoryClosure", "(", "Collection", "<", "HeadedSyntacticCategory", ">", "syntacticCategories", ")", "{", "Set", "<", "String", ">", "featureValues", "=", "Sets", ".", "newHashSet", "(", "...
Gets the closure of a set of syntactic categories under function application and feature assignment. @param syntacticCategories - the categories to get the closure of. Must be provided in canonical form. @return closure of the argument categories, in canonical form.
[ "Gets", "the", "closure", "of", "a", "set", "of", "syntactic", "categories", "under", "function", "application", "and", "feature", "assignment", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgGrammarUtils.java#L49-L98
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/CcgGrammarUtils.java
CcgGrammarUtils.buildUnrestrictedBinaryDistribution
public static DiscreteFactor buildUnrestrictedBinaryDistribution(DiscreteVariable syntaxType, Iterable<CcgBinaryRule> rules, boolean allowComposition) { List<HeadedSyntacticCategory> allCategories = syntaxType.getValuesWithCast(HeadedSyntacticCategory.class); Set<List<Object>> validOutcomes = Sets.newHashSet(); Set<Combinator> combinators = Sets.newHashSet(); // Compute function application rules. for (HeadedSyntacticCategory functionCat : allCategories) { for (HeadedSyntacticCategory argumentCat : allCategories) { appendApplicationRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators); } } if (allowComposition) { // Compute function composition rules. for (HeadedSyntacticCategory functionCat : allCategories) { for (HeadedSyntacticCategory argumentCat : allCategories) { appendCompositionRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators); } } } appendBinaryRules(rules, syntaxType, validOutcomes, combinators); return buildSyntaxDistribution(syntaxType, validOutcomes, combinators); }
java
public static DiscreteFactor buildUnrestrictedBinaryDistribution(DiscreteVariable syntaxType, Iterable<CcgBinaryRule> rules, boolean allowComposition) { List<HeadedSyntacticCategory> allCategories = syntaxType.getValuesWithCast(HeadedSyntacticCategory.class); Set<List<Object>> validOutcomes = Sets.newHashSet(); Set<Combinator> combinators = Sets.newHashSet(); // Compute function application rules. for (HeadedSyntacticCategory functionCat : allCategories) { for (HeadedSyntacticCategory argumentCat : allCategories) { appendApplicationRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators); } } if (allowComposition) { // Compute function composition rules. for (HeadedSyntacticCategory functionCat : allCategories) { for (HeadedSyntacticCategory argumentCat : allCategories) { appendCompositionRules(functionCat, argumentCat, syntaxType, validOutcomes, combinators); } } } appendBinaryRules(rules, syntaxType, validOutcomes, combinators); return buildSyntaxDistribution(syntaxType, validOutcomes, combinators); }
[ "public", "static", "DiscreteFactor", "buildUnrestrictedBinaryDistribution", "(", "DiscreteVariable", "syntaxType", ",", "Iterable", "<", "CcgBinaryRule", ">", "rules", ",", "boolean", "allowComposition", ")", "{", "List", "<", "HeadedSyntacticCategory", ">", "allCategori...
Constructs a distribution over binary combination rules for CCG, given a set of syntactic categories. This method compiles out all of the possible ways to combine two adjacent CCG categories using function application, composition, and any other binary rules. @param syntaxType @param rules @param allowComposition @return
[ "Constructs", "a", "distribution", "over", "binary", "combination", "rules", "for", "CCG", "given", "a", "set", "of", "syntactic", "categories", ".", "This", "method", "compiles", "out", "all", "of", "the", "possible", "ways", "to", "combine", "two", "adjacent...
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgGrammarUtils.java#L139-L162
train
cpollet/jixture
core/src/main/java/net/cpollet/jixture/fixtures/BaseObjectFixture.java
BaseObjectFixture.getClassesToDelete
private LinkedList<Class> getClassesToDelete() { LinkedHashSet<Class> classesToDelete = new LinkedHashSet<Class>(); for (Object object : getObjects()) { classesToDelete.add(object.getClass()); } return new LinkedList<Class>(classesToDelete); }
java
private LinkedList<Class> getClassesToDelete() { LinkedHashSet<Class> classesToDelete = new LinkedHashSet<Class>(); for (Object object : getObjects()) { classesToDelete.add(object.getClass()); } return new LinkedList<Class>(classesToDelete); }
[ "private", "LinkedList", "<", "Class", ">", "getClassesToDelete", "(", ")", "{", "LinkedHashSet", "<", "Class", ">", "classesToDelete", "=", "new", "LinkedHashSet", "<", "Class", ">", "(", ")", ";", "for", "(", "Object", "object", ":", "getObjects", "(", "...
Returns the list of mapping classes representing the tables to truncate. @return the list of mapping classes representing the tables to truncate.
[ "Returns", "the", "list", "of", "mapping", "classes", "representing", "the", "tables", "to", "truncate", "." ]
faef0d4991f81c2cdb5be3ba24176636ef0cc433
https://github.com/cpollet/jixture/blob/faef0d4991f81c2cdb5be3ba24176636ef0cc433/core/src/main/java/net/cpollet/jixture/fixtures/BaseObjectFixture.java#L58-L66
train
jayantk/jklol
src/com/jayantkrish/jklol/tensor/SparseTensor.java
SparseTensor.diagonal
public static SparseTensor diagonal(int[] dimensionNumbers, int[] dimensionSizes, double value) { int minDimensionSize = Ints.min(dimensionSizes); double[] values = new double[minDimensionSize]; Arrays.fill(values, value); return diagonal(dimensionNumbers, dimensionSizes, values); }
java
public static SparseTensor diagonal(int[] dimensionNumbers, int[] dimensionSizes, double value) { int minDimensionSize = Ints.min(dimensionSizes); double[] values = new double[minDimensionSize]; Arrays.fill(values, value); return diagonal(dimensionNumbers, dimensionSizes, values); }
[ "public", "static", "SparseTensor", "diagonal", "(", "int", "[", "]", "dimensionNumbers", ",", "int", "[", "]", "dimensionSizes", ",", "double", "value", ")", "{", "int", "minDimensionSize", "=", "Ints", ".", "min", "(", "dimensionSizes", ")", ";", "double",...
Creates a tensor whose only non-zero entries are on its main diagonal. @param dimensionNumbers @param dimensionSizes @param value weight assigned to the keys on the main diagonal. @return
[ "Creates", "a", "tensor", "whose", "only", "non", "-", "zero", "entries", "are", "on", "its", "main", "diagonal", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/tensor/SparseTensor.java#L1225-L1231
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/CcgCategory.java
CcgCategory.fromSyntaxLf
public static CcgCategory fromSyntaxLf(HeadedSyntacticCategory cat, Expression2 lf) { String head = lf.toString(); head = head.replaceAll(" ", "_"); List<String> subjects = Lists.newArrayList(); List<Integer> argumentNums = Lists.newArrayList(); List<Integer> objects = Lists.newArrayList(); List<HeadedSyntacticCategory> argumentCats = Lists.newArrayList(cat.getArgumentTypes()); Collections.reverse(argumentCats); for (int i = 0; i < argumentCats.size(); i++) { subjects.add(head); argumentNums.add(i + 1); objects.add(argumentCats.get(i).getHeadVariable()); } List<Set<String>> assignments = Lists.newArrayList(); for (int i = 0; i < cat.getUniqueVariables().length; i++) { assignments.add(Collections.<String>emptySet()); } int headVar = cat.getHeadVariable(); assignments.set(headVar, Sets.newHashSet(head)); return new CcgCategory(cat, lf, subjects, argumentNums, objects, assignments); }
java
public static CcgCategory fromSyntaxLf(HeadedSyntacticCategory cat, Expression2 lf) { String head = lf.toString(); head = head.replaceAll(" ", "_"); List<String> subjects = Lists.newArrayList(); List<Integer> argumentNums = Lists.newArrayList(); List<Integer> objects = Lists.newArrayList(); List<HeadedSyntacticCategory> argumentCats = Lists.newArrayList(cat.getArgumentTypes()); Collections.reverse(argumentCats); for (int i = 0; i < argumentCats.size(); i++) { subjects.add(head); argumentNums.add(i + 1); objects.add(argumentCats.get(i).getHeadVariable()); } List<Set<String>> assignments = Lists.newArrayList(); for (int i = 0; i < cat.getUniqueVariables().length; i++) { assignments.add(Collections.<String>emptySet()); } int headVar = cat.getHeadVariable(); assignments.set(headVar, Sets.newHashSet(head)); return new CcgCategory(cat, lf, subjects, argumentNums, objects, assignments); }
[ "public", "static", "CcgCategory", "fromSyntaxLf", "(", "HeadedSyntacticCategory", "cat", ",", "Expression2", "lf", ")", "{", "String", "head", "=", "lf", ".", "toString", "(", ")", ";", "head", "=", "head", ".", "replaceAll", "(", "\" \"", ",", "\"_\"", "...
Generates a CCG category with head and dependency information automatically populated from the syntactic category and logical form. The logical form itself is used as the semantic head of the returned category. @param cat @param logicalForm @return
[ "Generates", "a", "CCG", "category", "with", "head", "and", "dependency", "information", "automatically", "populated", "from", "the", "syntactic", "category", "and", "logical", "form", ".", "The", "logical", "form", "itself", "is", "used", "as", "the", "semantic...
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgCategory.java#L250-L273
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/CcgCategory.java
CcgCategory.getSemanticHeads
public List<String> getSemanticHeads() { int headSemanticVariable = syntax.getHeadVariable(); int[] allSemanticVariables = getSemanticVariables(); for (int i = 0; i < allSemanticVariables.length; i++) { if (allSemanticVariables[i] == headSemanticVariable) { return Lists.newArrayList(variableAssignments.get(i)); } } return Collections.emptyList(); }
java
public List<String> getSemanticHeads() { int headSemanticVariable = syntax.getHeadVariable(); int[] allSemanticVariables = getSemanticVariables(); for (int i = 0; i < allSemanticVariables.length; i++) { if (allSemanticVariables[i] == headSemanticVariable) { return Lists.newArrayList(variableAssignments.get(i)); } } return Collections.emptyList(); }
[ "public", "List", "<", "String", ">", "getSemanticHeads", "(", ")", "{", "int", "headSemanticVariable", "=", "syntax", ".", "getHeadVariable", "(", ")", ";", "int", "[", "]", "allSemanticVariables", "=", "getSemanticVariables", "(", ")", ";", "for", "(", "in...
The semantic head of this category, i.e., the assignment to the semantic variable at the root of the syntactic tree. @return
[ "The", "semantic", "head", "of", "this", "category", "i", ".", "e", ".", "the", "assignment", "to", "the", "semantic", "variable", "at", "the", "root", "of", "the", "syntactic", "tree", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgCategory.java#L314-L323
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/chart/ChartEntry.java
ChartEntry.getDerivingCombinatorType
public Combinator.Type getDerivingCombinatorType() { if (combinator == null) { return Combinator.Type.OTHER; } else { return combinator.getType(); } }
java
public Combinator.Type getDerivingCombinatorType() { if (combinator == null) { return Combinator.Type.OTHER; } else { return combinator.getType(); } }
[ "public", "Combinator", ".", "Type", "getDerivingCombinatorType", "(", ")", "{", "if", "(", "combinator", "==", "null", ")", "{", "return", "Combinator", ".", "Type", ".", "OTHER", ";", "}", "else", "{", "return", "combinator", ".", "getType", "(", ")", ...
Gets the type of the combinator used to produce this chart entry. @return
[ "Gets", "the", "type", "of", "the", "combinator", "used", "to", "produce", "this", "chart", "entry", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/chart/ChartEntry.java#L292-L298
train
jayantk/jklol
src/com/jayantkrish/jklol/tensor/Backpointers.java
Backpointers.getOldKeyIndicatorTensor
public SparseTensor getOldKeyIndicatorTensor() { double[] values = new double[oldKeyNums.length]; Arrays.fill(values, 1.0); return SparseTensor.fromUnorderedKeyValues(oldTensor.getDimensionNumbers(), oldTensor.getDimensionSizes(), oldKeyNums, values); }
java
public SparseTensor getOldKeyIndicatorTensor() { double[] values = new double[oldKeyNums.length]; Arrays.fill(values, 1.0); return SparseTensor.fromUnorderedKeyValues(oldTensor.getDimensionNumbers(), oldTensor.getDimensionSizes(), oldKeyNums, values); }
[ "public", "SparseTensor", "getOldKeyIndicatorTensor", "(", ")", "{", "double", "[", "]", "values", "=", "new", "double", "[", "oldKeyNums", ".", "length", "]", ";", "Arrays", ".", "fill", "(", "values", ",", "1.0", ")", ";", "return", "SparseTensor", ".", ...
Gets a tensor of indicator variables for the old key values in this. The returned tensor has value 1 for all keys in this, and 0 for all other keys. @return
[ "Gets", "a", "tensor", "of", "indicator", "variables", "for", "the", "old", "key", "values", "in", "this", ".", "The", "returned", "tensor", "has", "value", "1", "for", "all", "keys", "in", "this", "and", "0", "for", "all", "other", "keys", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/tensor/Backpointers.java#L56-L61
train
jayantk/jklol
src/com/jayantkrish/jklol/lisp/LispUtil.java
LispUtil.readProgram
public static SExpression readProgram(List<String> filenames, IndexedList<String> symbolTable) { StringBuilder programBuilder = new StringBuilder(); programBuilder.append("(begin "); for (String filename : filenames) { for (String line : IoUtils.readLines(filename)) { line = line.replaceAll("^[ \t]*;.*", ""); programBuilder.append(line); programBuilder.append(" "); } } programBuilder.append(" )"); String program = programBuilder.toString(); ExpressionParser<SExpression> parser = ExpressionParser.sExpression(symbolTable); SExpression programExpression = parser.parse(program); return programExpression; }
java
public static SExpression readProgram(List<String> filenames, IndexedList<String> symbolTable) { StringBuilder programBuilder = new StringBuilder(); programBuilder.append("(begin "); for (String filename : filenames) { for (String line : IoUtils.readLines(filename)) { line = line.replaceAll("^[ \t]*;.*", ""); programBuilder.append(line); programBuilder.append(" "); } } programBuilder.append(" )"); String program = programBuilder.toString(); ExpressionParser<SExpression> parser = ExpressionParser.sExpression(symbolTable); SExpression programExpression = parser.parse(program); return programExpression; }
[ "public", "static", "SExpression", "readProgram", "(", "List", "<", "String", ">", "filenames", ",", "IndexedList", "<", "String", ">", "symbolTable", ")", "{", "StringBuilder", "programBuilder", "=", "new", "StringBuilder", "(", ")", ";", "programBuilder", ".",...
Reads a program from a list of files. Lines starting with any amount of whitespace followed by ; are ignored as comments. @param filenames @param symbolTable @return
[ "Reads", "a", "program", "from", "a", "list", "of", "files", ".", "Lines", "starting", "with", "any", "amount", "of", "whitespace", "followed", "by", ";", "are", "ignored", "as", "comments", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/lisp/LispUtil.java#L26-L43
train
lite2073/email-validator
src/com/dominicsayers/isemail/dns/DNSLookup.java
DNSLookup.hasRecords
public static boolean hasRecords(String hostName, String dnsType) throws DNSLookupException { return DNSLookup.doLookup(hostName, dnsType) > 0; }
java
public static boolean hasRecords(String hostName, String dnsType) throws DNSLookupException { return DNSLookup.doLookup(hostName, dnsType) > 0; }
[ "public", "static", "boolean", "hasRecords", "(", "String", "hostName", ",", "String", "dnsType", ")", "throws", "DNSLookupException", "{", "return", "DNSLookup", ".", "doLookup", "(", "hostName", ",", "dnsType", ")", ">", "0", ";", "}" ]
Checks if a host name has a valid record. @param hostName The hostname @param dnsType The kind of record (A, AAAA, MX, ...) @return Whether the record is available or not @throws DNSLookupException Appears on a fatal error like dnsType invalid or initial context error.
[ "Checks", "if", "a", "host", "name", "has", "a", "valid", "record", "." ]
cfdda77ed630854b44d62def0d5b7228d5c4e712
https://github.com/lite2073/email-validator/blob/cfdda77ed630854b44d62def0d5b7228d5c4e712/src/com/dominicsayers/isemail/dns/DNSLookup.java#L29-L32
train
lite2073/email-validator
src/com/dominicsayers/isemail/dns/DNSLookup.java
DNSLookup.doLookup
public static int doLookup(String hostName, String dnsType) throws DNSLookupException { // JNDI cannot take two-byte chars, so we convert the hostname into Punycode hostName = UniPunyCode.toPunycodeIfPossible(hostName); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx; try { ictx = new InitialDirContext(env); } catch (NamingException e) { throw new DNSInitialContextException(e); } Attributes attrs; try { attrs = ictx.getAttributes(hostName, new String[] { dnsType }); } catch (NameNotFoundException e) { // The hostname was not found or is invalid return -1; } catch (InvalidAttributeIdentifierException e) { // The DNS type is invalid throw new DNSInvalidTypeException(e); } catch (NamingException e) { // Unknown reason throw new DNSLookupException(e); } Attribute attr = attrs.get(dnsType); if (attr == null) { return 0; } return attr.size(); }
java
public static int doLookup(String hostName, String dnsType) throws DNSLookupException { // JNDI cannot take two-byte chars, so we convert the hostname into Punycode hostName = UniPunyCode.toPunycodeIfPossible(hostName); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx; try { ictx = new InitialDirContext(env); } catch (NamingException e) { throw new DNSInitialContextException(e); } Attributes attrs; try { attrs = ictx.getAttributes(hostName, new String[] { dnsType }); } catch (NameNotFoundException e) { // The hostname was not found or is invalid return -1; } catch (InvalidAttributeIdentifierException e) { // The DNS type is invalid throw new DNSInvalidTypeException(e); } catch (NamingException e) { // Unknown reason throw new DNSLookupException(e); } Attribute attr = attrs.get(dnsType); if (attr == null) { return 0; } return attr.size(); }
[ "public", "static", "int", "doLookup", "(", "String", "hostName", ",", "String", "dnsType", ")", "throws", "DNSLookupException", "{", "// JNDI cannot take two-byte chars, so we convert the hostname into Punycode\r", "hostName", "=", "UniPunyCode", ".", "toPunycodeIfPossible", ...
Counts the number of records found for hostname and the specific type. Outputs 0 if no record is found or -1 if the hostname is unknown invalid! @param hostName The hostname @param dnsType The kind of record (A, AAAA, MX, ...) @return Whether the record is available or not @throws DNSLookupException Appears on a fatal error like dnsType invalid or initial context error.
[ "Counts", "the", "number", "of", "records", "found", "for", "hostname", "and", "the", "specific", "type", ".", "Outputs", "0", "if", "no", "record", "is", "found", "or", "-", "1", "if", "the", "hostname", "is", "unknown", "invalid!" ]
cfdda77ed630854b44d62def0d5b7228d5c4e712
https://github.com/lite2073/email-validator/blob/cfdda77ed630854b44d62def0d5b7228d5c4e712/src/com/dominicsayers/isemail/dns/DNSLookup.java#L47-L83
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.shutdown
public static void shutdown() { if (MetricsManager.executorService != null) { MetricsManager.executorService.shutdown(); MetricsManager.executorService = null; } if (MetricsManager.instance != null) { MetricsManager.instance = null; MetricsManager.poolManager.shutdown(); MetricsManager.poolManager = null; MetricsManager.httpClient = null; MetricsManager.rootMetricsLogger = null; } }
java
public static void shutdown() { if (MetricsManager.executorService != null) { MetricsManager.executorService.shutdown(); MetricsManager.executorService = null; } if (MetricsManager.instance != null) { MetricsManager.instance = null; MetricsManager.poolManager.shutdown(); MetricsManager.poolManager = null; MetricsManager.httpClient = null; MetricsManager.rootMetricsLogger = null; } }
[ "public", "static", "void", "shutdown", "(", ")", "{", "if", "(", "MetricsManager", ".", "executorService", "!=", "null", ")", "{", "MetricsManager", ".", "executorService", ".", "shutdown", "(", ")", ";", "MetricsManager", ".", "executorService", "=", "null",...
Shutdown MetricsManager, clean up resources This method is not thread-safe, only use it to clean up resources when your application is shutting down.
[ "Shutdown", "MetricsManager", "clean", "up", "resources", "This", "method", "is", "not", "thread", "-", "safe", "only", "use", "it", "to", "clean", "up", "resources", "when", "your", "application", "is", "shutting", "down", "." ]
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L142-L154
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.getMetricsLogger
public static MetricsLogger getMetricsLogger(final String dimensions) { if (MetricsManager.instance != null) { final Map<String, String> dimensionsMap = DimensionsUtils.parseDimensions(dimensions); if (!dimensionsMap.isEmpty()) { dimensionsMap.put("service", MetricsManager.instance.serviceName); if (MetricsManager.instance.env.length() > 0) { dimensionsMap.put("env", MetricsManager.instance.env); } return MetricsManager.instance.metricsLoggers.computeIfAbsent( DimensionsUtils.serializeDimensionsToString(dimensionsMap), key -> new MetricsLogger(dimensionsMap)); } else { throw new IllegalArgumentException("Dimensions must be valid and non-empty"); } } return dummyLogger; }
java
public static MetricsLogger getMetricsLogger(final String dimensions) { if (MetricsManager.instance != null) { final Map<String, String> dimensionsMap = DimensionsUtils.parseDimensions(dimensions); if (!dimensionsMap.isEmpty()) { dimensionsMap.put("service", MetricsManager.instance.serviceName); if (MetricsManager.instance.env.length() > 0) { dimensionsMap.put("env", MetricsManager.instance.env); } return MetricsManager.instance.metricsLoggers.computeIfAbsent( DimensionsUtils.serializeDimensionsToString(dimensionsMap), key -> new MetricsLogger(dimensionsMap)); } else { throw new IllegalArgumentException("Dimensions must be valid and non-empty"); } } return dummyLogger; }
[ "public", "static", "MetricsLogger", "getMetricsLogger", "(", "final", "String", "dimensions", ")", "{", "if", "(", "MetricsManager", ".", "instance", "!=", "null", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "dimensionsMap", "=", "DimensionsU...
Get MetricsLogger to start collecting metrics. MetricsLogger can be used to collect Counter, Timer or Recorder @param dimensions, key-value pairs aka dimensions for example "api=Upload, region=DUB" @return metrics logger
[ "Get", "MetricsLogger", "to", "start", "collecting", "metrics", ".", "MetricsLogger", "can", "be", "used", "to", "collect", "Counter", "Timer", "or", "Recorder" ]
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L191-L206
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.flushAll
public static void flushAll(long now) { if (MetricsManager.instance != null) { MetricsManager.instance.metricsLoggers.values().forEach(MetricsManager::flushMetricsLogger); flushToServer(now); } }
java
public static void flushAll(long now) { if (MetricsManager.instance != null) { MetricsManager.instance.metricsLoggers.values().forEach(MetricsManager::flushMetricsLogger); flushToServer(now); } }
[ "public", "static", "void", "flushAll", "(", "long", "now", ")", "{", "if", "(", "MetricsManager", ".", "instance", "!=", "null", ")", "{", "MetricsManager", ".", "instance", ".", "metricsLoggers", ".", "values", "(", ")", ".", "forEach", "(", "MetricsMana...
Flush all metrics which have been collected so far by all MetricsLoggers. Metrics can also be flushed by each MetricsLogger individually.
[ "Flush", "all", "metrics", "which", "have", "been", "collected", "so", "far", "by", "all", "MetricsLoggers", ".", "Metrics", "can", "also", "be", "flushed", "by", "each", "MetricsLogger", "individually", "." ]
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L224-L229
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.flushToServer
static void flushToServer(long now) { LOG.debug("Flush to BeeInstant Server"); Collection<String> readyToSubmit = new ArrayList<>(); metricsQueue.drainTo(readyToSubmit); StringBuilder builder = new StringBuilder(); readyToSubmit.forEach(string -> { builder.append(string); builder.append("\n"); }); if (!readyToSubmit.isEmpty() && beeInstantHost != null) { try { final String body = builder.toString(); StringEntity entity = new StringEntity(body); entity.setContentType("text/plain"); String uri = "/PutMetric"; final String signature = sign(entity); if (!signature.isEmpty()) { uri += "?signature=" + URLEncoder.encode(signature, "UTF-8"); uri += "&publicKey=" + URLEncoder.encode(publicKey, "UTF-8"); uri += "&timestamp=" + now; HttpPost putMetricCommand = new HttpPost(uri); try { putMetricCommand.setEntity(entity); HttpResponse response = httpClient.execute(beeInstantHost, putMetricCommand); LOG.info("Response: " + response.getStatusLine().getStatusCode()); } finally { putMetricCommand.releaseConnection(); } } } catch (Throwable e) { LOG.error("Fail to emit metrics", e); } } }
java
static void flushToServer(long now) { LOG.debug("Flush to BeeInstant Server"); Collection<String> readyToSubmit = new ArrayList<>(); metricsQueue.drainTo(readyToSubmit); StringBuilder builder = new StringBuilder(); readyToSubmit.forEach(string -> { builder.append(string); builder.append("\n"); }); if (!readyToSubmit.isEmpty() && beeInstantHost != null) { try { final String body = builder.toString(); StringEntity entity = new StringEntity(body); entity.setContentType("text/plain"); String uri = "/PutMetric"; final String signature = sign(entity); if (!signature.isEmpty()) { uri += "?signature=" + URLEncoder.encode(signature, "UTF-8"); uri += "&publicKey=" + URLEncoder.encode(publicKey, "UTF-8"); uri += "&timestamp=" + now; HttpPost putMetricCommand = new HttpPost(uri); try { putMetricCommand.setEntity(entity); HttpResponse response = httpClient.execute(beeInstantHost, putMetricCommand); LOG.info("Response: " + response.getStatusLine().getStatusCode()); } finally { putMetricCommand.releaseConnection(); } } } catch (Throwable e) { LOG.error("Fail to emit metrics", e); } } }
[ "static", "void", "flushToServer", "(", "long", "now", ")", "{", "LOG", ".", "debug", "(", "\"Flush to BeeInstant Server\"", ")", ";", "Collection", "<", "String", ">", "readyToSubmit", "=", "new", "ArrayList", "<>", "(", ")", ";", "metricsQueue", ".", "drai...
Flush metrics to BeeInstant Server
[ "Flush", "metrics", "to", "BeeInstant", "Server" ]
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L234-L270
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.reportError
static void reportError(final String errorMessage) { if (MetricsManager.instance != null) { MetricsManager.rootMetricsLogger.incCounter(METRIC_ERRORS, 1); } LOG.error(errorMessage); }
java
static void reportError(final String errorMessage) { if (MetricsManager.instance != null) { MetricsManager.rootMetricsLogger.incCounter(METRIC_ERRORS, 1); } LOG.error(errorMessage); }
[ "static", "void", "reportError", "(", "final", "String", "errorMessage", ")", "{", "if", "(", "MetricsManager", ".", "instance", "!=", "null", ")", "{", "MetricsManager", ".", "rootMetricsLogger", ".", "incCounter", "(", "METRIC_ERRORS", ",", "1", ")", ";", ...
Report errors during metric data collecting process. Report in two forms, a host level metric which counts number of errors and a log line with message for each error. Will be used by MetricsLogger to report errors. @param errorMessage, error message during metric data collecting process
[ "Report", "errors", "during", "metric", "data", "collecting", "process", ".", "Report", "in", "two", "forms", "a", "host", "level", "metric", "which", "counts", "number", "of", "errors", "and", "a", "log", "line", "with", "message", "for", "each", "error", ...
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L314-L319
train
beeinstant-dev/beeinstant-java-sdk
src/main/java/com/beeinstant/metrics/MetricsManager.java
MetricsManager.flushMetricsLogger
static void flushMetricsLogger(final MetricsLogger metricsLogger) { metricsLogger.flushToString(MetricsManager::queue); MetricsManager.rootMetricsLogger.flushToString(MetricsManager::queue); }
java
static void flushMetricsLogger(final MetricsLogger metricsLogger) { metricsLogger.flushToString(MetricsManager::queue); MetricsManager.rootMetricsLogger.flushToString(MetricsManager::queue); }
[ "static", "void", "flushMetricsLogger", "(", "final", "MetricsLogger", "metricsLogger", ")", "{", "metricsLogger", ".", "flushToString", "(", "MetricsManager", "::", "queue", ")", ";", "MetricsManager", ".", "rootMetricsLogger", ".", "flushToString", "(", "MetricsMana...
Flush metrics collected by MetricsLogger to log files. Will be used by MetricsLogger to flush itself. @param metricsLogger, contain metric dimensions, metric names, metric data (counter, timer, recorder)
[ "Flush", "metrics", "collected", "by", "MetricsLogger", "to", "log", "files", ".", "Will", "be", "used", "by", "MetricsLogger", "to", "flush", "itself", "." ]
c51d7e931bd5f057f77406d393760cf42caf0599
https://github.com/beeinstant-dev/beeinstant-java-sdk/blob/c51d7e931bd5f057f77406d393760cf42caf0599/src/main/java/com/beeinstant/metrics/MetricsManager.java#L326-L329
train
jayantk/jklol
src/com/jayantkrish/jklol/parallel/Mappers.java
Mappers.identity
public static <A> Mapper<A, A> identity() { return new Mapper<A, A>() { @Override public A map(A item) { return item; } }; }
java
public static <A> Mapper<A, A> identity() { return new Mapper<A, A>() { @Override public A map(A item) { return item; } }; }
[ "public", "static", "<", "A", ">", "Mapper", "<", "A", ",", "A", ">", "identity", "(", ")", "{", "return", "new", "Mapper", "<", "A", ",", "A", ">", "(", ")", "{", "@", "Override", "public", "A", "map", "(", "A", "item", ")", "{", "return", "...
Gets the identity mapper. @return
[ "Gets", "the", "identity", "mapper", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/parallel/Mappers.java#L32-L39
train
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/KeyWrapper.java
KeyWrapper.unwrapKeyPair
public KeyPair unwrapKeyPair(String wrappedPrivateKey, String encodedPublicKey) { PrivateKey privateKey = unwrapPrivateKey(wrappedPrivateKey); PublicKey publicKey = decodePublicKey(encodedPublicKey); return new KeyPair(publicKey, privateKey); }
java
public KeyPair unwrapKeyPair(String wrappedPrivateKey, String encodedPublicKey) { PrivateKey privateKey = unwrapPrivateKey(wrappedPrivateKey); PublicKey publicKey = decodePublicKey(encodedPublicKey); return new KeyPair(publicKey, privateKey); }
[ "public", "KeyPair", "unwrapKeyPair", "(", "String", "wrappedPrivateKey", ",", "String", "encodedPublicKey", ")", "{", "PrivateKey", "privateKey", "=", "unwrapPrivateKey", "(", "wrappedPrivateKey", ")", ";", "PublicKey", "publicKey", "=", "decodePublicKey", "(", "enco...
Convenience method to unwrap a public-private key pain in a single call. @param wrappedPrivateKey The wrapped key, base-64 encoded, as returned by {@link #wrapPrivateKey(PrivateKey)}. @param encodedPublicKey The public key, base-64 encoded, as returned by {@link #encodePublicKey(PublicKey)}. @return A {@link KeyPair} containing the unwrapped {@link PrivateKey} and the decoded {@link PublicKey}.
[ "Convenience", "method", "to", "unwrap", "a", "public", "-", "private", "key", "pain", "in", "a", "single", "call", "." ]
e67954181a04ffc9beb1d9abca1421195fcf9764
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/KeyWrapper.java#L264-L269
train
jayantk/jklol
src/com/jayantkrish/jklol/tensor/AbstractTensorBase.java
AbstractTensorBase.mergeDimensions
public static final DimensionSpec mergeDimensions(int[] firstDimensionNums, int[] firstDimensionSizes, int[] secondDimensionNums, int[] secondDimensionSizes) { SortedSet<Integer> first = Sets.newTreeSet(Ints.asList(firstDimensionNums)); SortedSet<Integer> second = Sets.newTreeSet(Ints.asList(secondDimensionNums)); SortedSet<Integer> all = Sets.newTreeSet(first); all.addAll(second); int[] resultDims = Ints.toArray(all); int[] resultSizes = new int[resultDims.length]; for (int i = 0; i < resultDims.length; i++) { int dim = resultDims[i]; if (first.contains(dim) && second.contains(dim)) { int firstIndex = Ints.indexOf(firstDimensionNums, dim); int secondIndex = Ints.indexOf(secondDimensionNums, dim); int firstSize = firstDimensionSizes[firstIndex]; int secondSize = secondDimensionSizes[secondIndex]; Preconditions.checkArgument(firstSize == secondSize, "Dimension sizes do not match: dim %s, sizes %s and %s.", dim, firstSize, secondSize); resultSizes[i] = firstSize; } else if (first.contains(dim)) { int firstIndex = Ints.indexOf(firstDimensionNums, dim); int firstSize = firstDimensionSizes[firstIndex]; resultSizes[i] = firstSize; } else { int secondIndex = Ints.indexOf(secondDimensionNums, dim); int secondSize = secondDimensionSizes[secondIndex]; resultSizes[i] = secondSize; } } return new DimensionSpec(resultDims, resultSizes); }
java
public static final DimensionSpec mergeDimensions(int[] firstDimensionNums, int[] firstDimensionSizes, int[] secondDimensionNums, int[] secondDimensionSizes) { SortedSet<Integer> first = Sets.newTreeSet(Ints.asList(firstDimensionNums)); SortedSet<Integer> second = Sets.newTreeSet(Ints.asList(secondDimensionNums)); SortedSet<Integer> all = Sets.newTreeSet(first); all.addAll(second); int[] resultDims = Ints.toArray(all); int[] resultSizes = new int[resultDims.length]; for (int i = 0; i < resultDims.length; i++) { int dim = resultDims[i]; if (first.contains(dim) && second.contains(dim)) { int firstIndex = Ints.indexOf(firstDimensionNums, dim); int secondIndex = Ints.indexOf(secondDimensionNums, dim); int firstSize = firstDimensionSizes[firstIndex]; int secondSize = secondDimensionSizes[secondIndex]; Preconditions.checkArgument(firstSize == secondSize, "Dimension sizes do not match: dim %s, sizes %s and %s.", dim, firstSize, secondSize); resultSizes[i] = firstSize; } else if (first.contains(dim)) { int firstIndex = Ints.indexOf(firstDimensionNums, dim); int firstSize = firstDimensionSizes[firstIndex]; resultSizes[i] = firstSize; } else { int secondIndex = Ints.indexOf(secondDimensionNums, dim); int secondSize = secondDimensionSizes[secondIndex]; resultSizes[i] = secondSize; } } return new DimensionSpec(resultDims, resultSizes); }
[ "public", "static", "final", "DimensionSpec", "mergeDimensions", "(", "int", "[", "]", "firstDimensionNums", ",", "int", "[", "]", "firstDimensionSizes", ",", "int", "[", "]", "secondDimensionNums", ",", "int", "[", "]", "secondDimensionSizes", ")", "{", "Sorted...
Merges the given sets of dimensions, verifying that any dimensions in both sets have the same size. @param firstDimensionNums @param firstDimensionSizes @param secondDimensionNums @param secondDimensionSizes @return
[ "Merges", "the", "given", "sets", "of", "dimensions", "verifying", "that", "any", "dimensions", "in", "both", "sets", "have", "the", "same", "size", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/tensor/AbstractTensorBase.java#L94-L125
train
cpollet/jixture
core/src/main/java/net/cpollet/jixture/fixtures/generator/field/ListSequence.java
ListSequence.next
@Override public T next() { if (!hasNext()) { throw new NoSuchElementException(toString() + " ended"); } current = iterator.next(); return current(); }
java
@Override public T next() { if (!hasNext()) { throw new NoSuchElementException(toString() + " ended"); } current = iterator.next(); return current(); }
[ "@", "Override", "public", "T", "next", "(", ")", "{", "if", "(", "!", "hasNext", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "toString", "(", ")", "+", "\" ended\"", ")", ";", "}", "current", "=", "iterator", ".", "next", "(",...
Returns the next value in list. @return the next value in list. @throws java.util.NoSuchElementException if the iteration has no more value.
[ "Returns", "the", "next", "value", "in", "list", "." ]
faef0d4991f81c2cdb5be3ba24176636ef0cc433
https://github.com/cpollet/jixture/blob/faef0d4991f81c2cdb5be3ba24176636ef0cc433/core/src/main/java/net/cpollet/jixture/fixtures/generator/field/ListSequence.java#L93-L102
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/BasicExporter.java
BasicExporter.buildClassContainer
<T> IClassContainer buildClassContainer(final List<T> list) { return (BasicCollectionUtils.isNotEmpty(list)) ? buildClassContainer(list.get(0)) : null; }
java
<T> IClassContainer buildClassContainer(final List<T> list) { return (BasicCollectionUtils.isNotEmpty(list)) ? buildClassContainer(list.get(0)) : null; }
[ "<", "T", ">", "IClassContainer", "buildClassContainer", "(", "final", "List", "<", "T", ">", "list", ")", "{", "return", "(", "BasicCollectionUtils", ".", "isNotEmpty", "(", "list", ")", ")", "?", "buildClassContainer", "(", "list", ".", "get", "(", "0", ...
Build class container with export entity parameters
[ "Build", "class", "container", "with", "export", "entity", "parameters" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/BasicExporter.java#L71-L75
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/BasicExporter.java
BasicExporter.buildWriter
IWriter buildWriter(final IClassContainer classContainer) { try { return new BufferedFileWriter(classContainer.getExportClassName(), path, format.getExtension()); } catch (IOException e) { logger.warning(e.getMessage()); return null; } }
java
IWriter buildWriter(final IClassContainer classContainer) { try { return new BufferedFileWriter(classContainer.getExportClassName(), path, format.getExtension()); } catch (IOException e) { logger.warning(e.getMessage()); return null; } }
[ "IWriter", "buildWriter", "(", "final", "IClassContainer", "classContainer", ")", "{", "try", "{", "return", "new", "BufferedFileWriter", "(", "classContainer", ".", "getExportClassName", "(", ")", ",", "path", ",", "format", ".", "getExtension", "(", ")", ")", ...
Build buffered writer for export @see #export(Object) @see #export(List)
[ "Build", "buffered", "writer", "for", "export" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/BasicExporter.java#L83-L90
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/BasicExporter.java
BasicExporter.extractExportContainers
<T> List<ExportContainer> extractExportContainers(final T t, final IClassContainer classContainer) { final List<ExportContainer> exports = new ArrayList<>(); // Using only SIMPLE values containers classContainer.getFormatSupported(format).forEach((k, v) -> { try { k.setAccessible(true); final String exportFieldName = v.getExportName(); final Object exportFieldValue = k.get(t); exports.add(buildContainer(exportFieldName, exportFieldValue, v.getType())); k.setAccessible(false); } catch (Exception ex) { logger.warning(ex.getMessage()); } }); return exports; }
java
<T> List<ExportContainer> extractExportContainers(final T t, final IClassContainer classContainer) { final List<ExportContainer> exports = new ArrayList<>(); // Using only SIMPLE values containers classContainer.getFormatSupported(format).forEach((k, v) -> { try { k.setAccessible(true); final String exportFieldName = v.getExportName(); final Object exportFieldValue = k.get(t); exports.add(buildContainer(exportFieldName, exportFieldValue, v.getType())); k.setAccessible(false); } catch (Exception ex) { logger.warning(ex.getMessage()); } }); return exports; }
[ "<", "T", ">", "List", "<", "ExportContainer", ">", "extractExportContainers", "(", "final", "T", "t", ",", "final", "IClassContainer", "classContainer", ")", "{", "final", "List", "<", "ExportContainer", ">", "exports", "=", "new", "ArrayList", "<>", "(", "...
Generates class export field-value map @param t class to export @return export containers @see ExportContainer
[ "Generates", "class", "export", "field", "-", "value", "map" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/BasicExporter.java#L99-L121
train
GoodforGod/dummymaker
src/main/java/io/dummymaker/export/impl/BasicExporter.java
BasicExporter.isExportEntityInvalid
<T> boolean isExportEntityInvalid(final List<T> t) { return (BasicCollectionUtils.isEmpty(t) || isExportEntityInvalid(t.get(0))); }
java
<T> boolean isExportEntityInvalid(final List<T> t) { return (BasicCollectionUtils.isEmpty(t) || isExportEntityInvalid(t.get(0))); }
[ "<", "T", ">", "boolean", "isExportEntityInvalid", "(", "final", "List", "<", "T", ">", "t", ")", "{", "return", "(", "BasicCollectionUtils", ".", "isEmpty", "(", "t", ")", "||", "isExportEntityInvalid", "(", "t", ".", "get", "(", "0", ")", ")", ")", ...
Validate export arguments @param t class to validate @return validation result
[ "Validate", "export", "arguments" ]
a4809c0a8139ab9cdb42814a3e37772717a313b4
https://github.com/GoodforGod/dummymaker/blob/a4809c0a8139ab9cdb42814a3e37772717a313b4/src/main/java/io/dummymaker/export/impl/BasicExporter.java#L218-L220
train
jayantk/jklol
src/com/jayantkrish/jklol/ccg/lambda2/ExpressionSimplifier.java
ExpressionSimplifier.lambdaCalculus
public static ExpressionSimplifier lambdaCalculus() { List<ExpressionReplacementRule> rules = Lists.newArrayList(); rules.add(new LambdaApplicationReplacementRule()); rules.add(new VariableCanonicalizationReplacementRule()); return new ExpressionSimplifier(rules); }
java
public static ExpressionSimplifier lambdaCalculus() { List<ExpressionReplacementRule> rules = Lists.newArrayList(); rules.add(new LambdaApplicationReplacementRule()); rules.add(new VariableCanonicalizationReplacementRule()); return new ExpressionSimplifier(rules); }
[ "public", "static", "ExpressionSimplifier", "lambdaCalculus", "(", ")", "{", "List", "<", "ExpressionReplacementRule", ">", "rules", "=", "Lists", ".", "newArrayList", "(", ")", ";", "rules", ".", "add", "(", "new", "LambdaApplicationReplacementRule", "(", ")", ...
Default simplifier for lambda calculus expressions. This simplifier performs beta reduction of lambda expressions and canonicalizes variable names. @return
[ "Default", "simplifier", "for", "lambda", "calculus", "expressions", ".", "This", "simplifier", "performs", "beta", "reduction", "of", "lambda", "expressions", "and", "canonicalizes", "variable", "names", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/lambda2/ExpressionSimplifier.java#L35-L40
train
lite2073/email-validator
src/com/dominicsayers/isemail/IsEMail.java
IsEMail.is_email
public static boolean is_email(String email, boolean checkDNS) throws DNSLookupException { return (is_email_verbose(email, checkDNS).getState() == GeneralState.OK); }
java
public static boolean is_email(String email, boolean checkDNS) throws DNSLookupException { return (is_email_verbose(email, checkDNS).getState() == GeneralState.OK); }
[ "public", "static", "boolean", "is_email", "(", "String", "email", ",", "boolean", "checkDNS", ")", "throws", "DNSLookupException", "{", "return", "(", "is_email_verbose", "(", "email", ",", "checkDNS", ")", ".", "getState", "(", ")", "==", "GeneralState", "."...
Checks the syntax of an email address. @param email The email address to be checked. @param checkDNS Whether a DNS check should be performed or not. @return True if the email address is valid. @throws DNSLookupException Is thrown if an internal error in the DNS lookup appeared.
[ "Checks", "the", "syntax", "of", "an", "email", "address", "." ]
cfdda77ed630854b44d62def0d5b7228d5c4e712
https://github.com/lite2073/email-validator/blob/cfdda77ed630854b44d62def0d5b7228d5c4e712/src/com/dominicsayers/isemail/IsEMail.java#L73-L76
train
lite2073/email-validator
src/com/dominicsayers/isemail/IsEMail.java
IsEMail.replaceCharAt
private static String replaceCharAt(String s, int pos, char c) { return s.substring(0, pos) + c + s.substring(pos + 1); }
java
private static String replaceCharAt(String s, int pos, char c) { return s.substring(0, pos) + c + s.substring(pos + 1); }
[ "private", "static", "String", "replaceCharAt", "(", "String", "s", ",", "int", "pos", ",", "char", "c", ")", "{", "return", "s", ".", "substring", "(", "0", ",", "pos", ")", "+", "c", "+", "s", ".", "substring", "(", "pos", "+", "1", ")", ";", ...
Replaces a char in a String @param s The input string @param pos The position of the char to be replaced @param c The new char @return The new String @see Source: http://www.rgagnon.com/javadetails/java-0030.html
[ "Replaces", "a", "char", "in", "a", "String" ]
cfdda77ed630854b44d62def0d5b7228d5c4e712
https://github.com/lite2073/email-validator/blob/cfdda77ed630854b44d62def0d5b7228d5c4e712/src/com/dominicsayers/isemail/IsEMail.java#L745-L747
train
jayantk/jklol
src/com/jayantkrish/jklol/cfg/CfgParseChart.java
CfgParseChart.updateOutsideEntry
public void updateOutsideEntry(int spanStart, int spanEnd, double[] values, Factor factor, VariableNumMap var) { if (sumProduct) { updateEntrySumProduct(outsideChart[spanStart][spanEnd], values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum()); } else { updateEntryMaxProduct(outsideChart[spanStart][spanEnd], values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum()); } }
java
public void updateOutsideEntry(int spanStart, int spanEnd, double[] values, Factor factor, VariableNumMap var) { if (sumProduct) { updateEntrySumProduct(outsideChart[spanStart][spanEnd], values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum()); } else { updateEntryMaxProduct(outsideChart[spanStart][spanEnd], values, factor.coerceToDiscrete().getWeights(), var.getOnlyVariableNum()); } }
[ "public", "void", "updateOutsideEntry", "(", "int", "spanStart", ",", "int", "spanEnd", ",", "double", "[", "]", "values", ",", "Factor", "factor", ",", "VariableNumMap", "var", ")", "{", "if", "(", "sumProduct", ")", "{", "updateEntrySumProduct", "(", "outs...
Update an entry of the outside chart with a new production. Depending on the type of the chart, this performs either a sum or max over productions of the same type in the same entry.
[ "Update", "an", "entry", "of", "the", "outside", "chart", "with", "a", "new", "production", ".", "Depending", "on", "the", "type", "of", "the", "chart", "this", "performs", "either", "a", "sum", "or", "max", "over", "productions", "of", "the", "same", "t...
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/cfg/CfgParseChart.java#L185-L193
train
jayantk/jklol
src/com/jayantkrish/jklol/cfg/CfgParseChart.java
CfgParseChart.getInsideEntries
public Factor getInsideEntries(int spanStart, int spanEnd) { Tensor entries = new DenseTensor(parentVar.getVariableNumsArray(), parentVar.getVariableSizes(), insideChart[spanStart][spanEnd]); return new TableFactor(parentVar, entries); }
java
public Factor getInsideEntries(int spanStart, int spanEnd) { Tensor entries = new DenseTensor(parentVar.getVariableNumsArray(), parentVar.getVariableSizes(), insideChart[spanStart][spanEnd]); return new TableFactor(parentVar, entries); }
[ "public", "Factor", "getInsideEntries", "(", "int", "spanStart", ",", "int", "spanEnd", ")", "{", "Tensor", "entries", "=", "new", "DenseTensor", "(", "parentVar", ".", "getVariableNumsArray", "(", ")", ",", "parentVar", ".", "getVariableSizes", "(", ")", ",",...
Get the inside unnormalized probabilities over productions at a particular span in the tree.
[ "Get", "the", "inside", "unnormalized", "probabilities", "over", "productions", "at", "a", "particular", "span", "in", "the", "tree", "." ]
d27532ca83e212d51066cf28f52621acc3fd44cc
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/cfg/CfgParseChart.java#L253-L257
train