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
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java
IdGenerator.waitTillNextTick
public static long waitTillNextTick(long currentTick, long tickSize) { long nextBlock = System.currentTimeMillis() / tickSize; for (; nextBlock <= currentTick; nextBlock = System.currentTimeMillis() / tickSize) { Thread.yield(); } return nextBlock; }
java
public static long waitTillNextTick(long currentTick, long tickSize) { long nextBlock = System.currentTimeMillis() / tickSize; for (; nextBlock <= currentTick; nextBlock = System.currentTimeMillis() / tickSize) { Thread.yield(); } return nextBlock; }
[ "public", "static", "long", "waitTillNextTick", "(", "long", "currentTick", ",", "long", "tickSize", ")", "{", "long", "nextBlock", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "tickSize", ";", "for", "(", ";", "nextBlock", "<=", "currentTick", ";...
Waits till clock moves to the next tick. @param currentTick @param tickSize tick size in milliseconds @return the "next" tick
[ "Waits", "till", "clock", "moves", "to", "the", "next", "tick", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java#L190-L196
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java
IdGenerator.generateId48
synchronized public long generateId48() { final long blockSize = 1000L; // block 1000 ms long timestamp = System.currentTimeMillis() / blockSize; long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get() / blockSize) { timestamp = waitTillNextSecond(timestamp); } if (timestamp == lastTimestampMillisec.get() / blockSize) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_48) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextSecond(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp * blockSize); timestamp = ((timestamp * blockSize - TIMESTAMP_EPOCH) / blockSize) & MASK_TIMESTAMP_48; return timestamp << SHIFT_TIMESTAMP_48 | template48 | (sequence & MASK_SEQUENCE_48); }
java
synchronized public long generateId48() { final long blockSize = 1000L; // block 1000 ms long timestamp = System.currentTimeMillis() / blockSize; long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get() / blockSize) { timestamp = waitTillNextSecond(timestamp); } if (timestamp == lastTimestampMillisec.get() / blockSize) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_48) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextSecond(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp * blockSize); timestamp = ((timestamp * blockSize - TIMESTAMP_EPOCH) / blockSize) & MASK_TIMESTAMP_48; return timestamp << SHIFT_TIMESTAMP_48 | template48 | (sequence & MASK_SEQUENCE_48); }
[ "synchronized", "public", "long", "generateId48", "(", ")", "{", "final", "long", "blockSize", "=", "1000L", ";", "// block 1000 ms", "long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "blockSize", ";", "long", "sequence", "=", "0", ...
Generates a 48-bit id. <p> Format: {@code <32-bit:timestamp><3-bit:node id><13 bit:sequence number>}. Where {@code timestamp} is in seconds, minus the epoch. </p> @return
[ "Generates", "a", "48", "-", "bit", "id", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java#L352-L377
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java
IdGenerator.generateId64
synchronized public long generateId64() { long timestamp = System.currentTimeMillis(); long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get()) { timestamp = waitTillNextMillisec(timestamp); } if (timestamp == lastTimestampMillisec.get()) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_64) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextMillisec(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp); timestamp = (timestamp - TIMESTAMP_EPOCH) & MASK_TIMESTAMP_64; return timestamp << SHIFT_TIMESTAMP_64 | template64 | (sequence & MASK_SEQUENCE_64); }
java
synchronized public long generateId64() { long timestamp = System.currentTimeMillis(); long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get()) { timestamp = waitTillNextMillisec(timestamp); } if (timestamp == lastTimestampMillisec.get()) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_64) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextMillisec(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp); timestamp = (timestamp - TIMESTAMP_EPOCH) & MASK_TIMESTAMP_64; return timestamp << SHIFT_TIMESTAMP_64 | template64 | (sequence & MASK_SEQUENCE_64); }
[ "synchronized", "public", "long", "generateId64", "(", ")", "{", "long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "sequence", "=", "0", ";", "boolean", "done", "=", "false", ";", "while", "(", "!", "done", ")", "{", ...
Generates a 64-bit id. <p> Format: {@code <41-bit:timestamp><10-bit:node-id><13-bit:sequence-number>}. Where {@code timestamp} is in milliseconds, minus the epoch. </p> @return
[ "Generates", "a", "64", "-", "bit", "id", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java#L544-L568
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java
IdGenerator.generateId128
synchronized public BigInteger generateId128() { long timestamp = System.currentTimeMillis(); long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get()) { timestamp = waitTillNextMillisec(timestamp); } if (timestamp == lastTimestampMillisec.get()) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_128) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextMillisec(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp); BigInteger biSequence = BigInteger.valueOf(sequence & MASK_SEQUENCE_128); BigInteger biResult = BigInteger.valueOf(timestamp); biResult = biResult.shiftLeft((int) SHIFT_TIMESTAMP_128); biResult = biResult.or(template128).or(biSequence); return biResult; }
java
synchronized public BigInteger generateId128() { long timestamp = System.currentTimeMillis(); long sequence = 0; boolean done = false; while (!done) { done = true; while (timestamp < lastTimestampMillisec.get()) { timestamp = waitTillNextMillisec(timestamp); } if (timestamp == lastTimestampMillisec.get()) { // increase sequence sequence = sequenceMillisec.incrementAndGet(); if (sequence > MAX_SEQUENCE_128) { // reset sequence sequenceMillisec.set(sequence = 0); timestamp = waitTillNextMillisec(timestamp); done = false; } } } sequenceMillisec.set(sequence); lastTimestampMillisec.set(timestamp); BigInteger biSequence = BigInteger.valueOf(sequence & MASK_SEQUENCE_128); BigInteger biResult = BigInteger.valueOf(timestamp); biResult = biResult.shiftLeft((int) SHIFT_TIMESTAMP_128); biResult = biResult.or(template128).or(biSequence); return biResult; }
[ "synchronized", "public", "BigInteger", "generateId128", "(", ")", "{", "long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "sequence", "=", "0", ";", "boolean", "done", "=", "false", ";", "while", "(", "!", "done", ")", ...
Generates a 128-bit id. <p> Format: {@code <64-bit:timestamp><48-bit:node-id><16-bit:sequence-number>}. Where {@code timestamp} is in milliseconds. </p> . @return
[ "Generates", "a", "128", "-", "bit", "id", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java#L636-L663
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.buildPublicKey
public static RSAPublicKey buildPublicKey(String base64KeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyData = Base64.getDecoder().decode(base64KeyData); return buildPublicKey(keyData); }
java
public static RSAPublicKey buildPublicKey(String base64KeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyData = Base64.getDecoder().decode(base64KeyData); return buildPublicKey(keyData); }
[ "public", "static", "RSAPublicKey", "buildPublicKey", "(", "String", "base64KeyData", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", "{", "byte", "[", "]", "keyData", "=", "Base64", ".", "getDecoder", "(", ")", ".", "decode", "(", "base...
Construct the RSA public key from a key string data. @param base64KeyData RSA public key in base64 (base64 of {@link RSAPublicKey#getEncoded()}) @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException
[ "Construct", "the", "RSA", "public", "key", "from", "a", "key", "string", "data", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L92-L96
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.buildPublicKey
public static RSAPublicKey buildPublicKey(byte[] keyData) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyData); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PublicKey generatePublic = keyFactory.generatePublic(publicKeySpec); return (RSAPublicKey) generatePublic; }
java
public static RSAPublicKey buildPublicKey(byte[] keyData) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyData); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PublicKey generatePublic = keyFactory.generatePublic(publicKeySpec); return (RSAPublicKey) generatePublic; }
[ "public", "static", "RSAPublicKey", "buildPublicKey", "(", "byte", "[", "]", "keyData", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", "{", "X509EncodedKeySpec", "publicKeySpec", "=", "new", "X509EncodedKeySpec", "(", "keyData", ")", ";", "...
Construct the RSA public key from a key binary data. @param keyData RSA public key data (value of {@link RSAPublicKey#getEncoded()}) @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException
[ "Construct", "the", "RSA", "public", "key", "from", "a", "key", "binary", "data", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L107-L113
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.buildPrivateKey
public static RSAPrivateKey buildPrivateKey(final byte[] keyData) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyData); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PrivateKey generatePrivate = keyFactory.generatePrivate(privateKeySpec); return (RSAPrivateKey) generatePrivate; }
java
public static RSAPrivateKey buildPrivateKey(final byte[] keyData) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyData); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PrivateKey generatePrivate = keyFactory.generatePrivate(privateKeySpec); return (RSAPrivateKey) generatePrivate; }
[ "public", "static", "RSAPrivateKey", "buildPrivateKey", "(", "final", "byte", "[", "]", "keyData", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", "{", "PKCS8EncodedKeySpec", "privateKeySpec", "=", "new", "PKCS8EncodedKeySpec", "(", "keyData", ...
Construct the RSA private key from a key binary data. @param keyData RSA private key data (value of {@link RSAPrivateKey#getEncoded()}) @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException
[ "Construct", "the", "RSA", "private", "key", "from", "a", "key", "binary", "data", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L124-L130
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.buildPrivateKey
public static RSAPrivateKey buildPrivateKey(final String base64KeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyData = Base64.getDecoder().decode(base64KeyData); return buildPrivateKey(keyData); }
java
public static RSAPrivateKey buildPrivateKey(final String base64KeyData) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyData = Base64.getDecoder().decode(base64KeyData); return buildPrivateKey(keyData); }
[ "public", "static", "RSAPrivateKey", "buildPrivateKey", "(", "final", "String", "base64KeyData", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", "{", "byte", "[", "]", "keyData", "=", "Base64", ".", "getDecoder", "(", ")", ".", "decode", ...
Construct the RSA private key from a key string data. @param base64KeyData RSA private key in base64 (base64 of {@link RSAPrivateKey#getEncoded()}) @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException
[ "Construct", "the", "RSA", "private", "key", "from", "a", "key", "string", "data", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L141-L145
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.generateKeys
public static KeyPair generateKeys(int numBits) throws NoSuchAlgorithmException { int numBitsPow2 = 1; while (numBitsPow2 < numBits) { numBitsPow2 <<= 1; } KeyPairGenerator kpg = KeyPairGenerator.getInstance(CIPHER_ALGORITHM); kpg.initialize(numBitsPow2, SECURE_RNG); KeyPair keyPair = kpg.generateKeyPair(); return keyPair; }
java
public static KeyPair generateKeys(int numBits) throws NoSuchAlgorithmException { int numBitsPow2 = 1; while (numBitsPow2 < numBits) { numBitsPow2 <<= 1; } KeyPairGenerator kpg = KeyPairGenerator.getInstance(CIPHER_ALGORITHM); kpg.initialize(numBitsPow2, SECURE_RNG); KeyPair keyPair = kpg.generateKeyPair(); return keyPair; }
[ "public", "static", "KeyPair", "generateKeys", "(", "int", "numBits", ")", "throws", "NoSuchAlgorithmException", "{", "int", "numBitsPow2", "=", "1", ";", "while", "(", "numBitsPow2", "<", "numBits", ")", "{", "numBitsPow2", "<<=", "1", ";", "}", "KeyPairGener...
Generate a random RSA keypair. @param numBits key's length in bits, should be power of 2) @return @throws NoSuchAlgorithmException
[ "Generate", "a", "random", "RSA", "keypair", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L794-L804
train
GeneralElectric/snowizard
snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java
SnowizardClient.newHttpClient
public static CloseableHttpClient newHttpClient() { final SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(Boolean.TRUE).setTcpNoDelay(Boolean.TRUE) .setSoTimeout(SOCKET_TIMEOUT_MS).build(); final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); manager.setDefaultMaxPerRoute(MAX_HOSTS); manager.setMaxTotal(MAX_HOSTS); manager.setDefaultSocketConfig(socketConfig); final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setStaleConnectionCheckEnabled(Boolean.FALSE) .setSocketTimeout(SOCKET_TIMEOUT_MS).build(); final CloseableHttpClient client = HttpClients .custom() .disableRedirectHandling() .setConnectionManager(manager) .setDefaultRequestConfig(requestConfig) .setConnectionReuseStrategy( new DefaultConnectionReuseStrategy()) .setConnectionBackoffStrategy(new DefaultBackoffStrategy()) .setRetryHandler( new DefaultHttpRequestRetryHandler(MAX_RETRIES, false)) .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) .build(); return client; }
java
public static CloseableHttpClient newHttpClient() { final SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(Boolean.TRUE).setTcpNoDelay(Boolean.TRUE) .setSoTimeout(SOCKET_TIMEOUT_MS).build(); final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); manager.setDefaultMaxPerRoute(MAX_HOSTS); manager.setMaxTotal(MAX_HOSTS); manager.setDefaultSocketConfig(socketConfig); final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setStaleConnectionCheckEnabled(Boolean.FALSE) .setSocketTimeout(SOCKET_TIMEOUT_MS).build(); final CloseableHttpClient client = HttpClients .custom() .disableRedirectHandling() .setConnectionManager(manager) .setDefaultRequestConfig(requestConfig) .setConnectionReuseStrategy( new DefaultConnectionReuseStrategy()) .setConnectionBackoffStrategy(new DefaultBackoffStrategy()) .setRetryHandler( new DefaultHttpRequestRetryHandler(MAX_RETRIES, false)) .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) .build(); return client; }
[ "public", "static", "CloseableHttpClient", "newHttpClient", "(", ")", "{", "final", "SocketConfig", "socketConfig", "=", "SocketConfig", ".", "custom", "(", ")", ".", "setSoKeepAlive", "(", "Boolean", ".", "TRUE", ")", ".", "setTcpNoDelay", "(", "Boolean", ".", ...
Get a new CloseableHttpClient @return CloseableHttpClient
[ "Get", "a", "new", "CloseableHttpClient" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java#L75-L104
train
GeneralElectric/snowizard
snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java
SnowizardClient.executeRequest
@Nullable public SnowizardResponse executeRequest(final String host, final int count) throws IOException { final String uri = String.format("http://%s/?count=%d", host, count); final HttpGet request = new HttpGet(uri); request.addHeader(HttpHeaders.ACCEPT, ProtocolBufferMediaType.APPLICATION_PROTOBUF); request.addHeader(HttpHeaders.USER_AGENT, getUserAgent()); SnowizardResponse snowizard = null; try { final BasicHttpContext context = new BasicHttpContext(); final HttpResponse response = client.execute(request, context); final int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { final HttpEntity entity = response.getEntity(); if (entity != null) { snowizard = SnowizardResponse .parseFrom(entity.getContent()); } EntityUtils.consumeQuietly(entity); } } finally { request.releaseConnection(); } return snowizard; }
java
@Nullable public SnowizardResponse executeRequest(final String host, final int count) throws IOException { final String uri = String.format("http://%s/?count=%d", host, count); final HttpGet request = new HttpGet(uri); request.addHeader(HttpHeaders.ACCEPT, ProtocolBufferMediaType.APPLICATION_PROTOBUF); request.addHeader(HttpHeaders.USER_AGENT, getUserAgent()); SnowizardResponse snowizard = null; try { final BasicHttpContext context = new BasicHttpContext(); final HttpResponse response = client.execute(request, context); final int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { final HttpEntity entity = response.getEntity(); if (entity != null) { snowizard = SnowizardResponse .parseFrom(entity.getContent()); } EntityUtils.consumeQuietly(entity); } } finally { request.releaseConnection(); } return snowizard; }
[ "@", "Nullable", "public", "SnowizardResponse", "executeRequest", "(", "final", "String", "host", ",", "final", "int", "count", ")", "throws", "IOException", "{", "final", "String", "uri", "=", "String", ".", "format", "(", "\"http://%s/?count=%d\"", ",", "host"...
Execute a request to the Snowizard service URL @param host Host:Port pair to connect to @param count Number of IDs to generate @return SnowizardResponse @throws IOException Error in communicating with Snowizard
[ "Execute", "a", "request", "to", "the", "Snowizard", "service", "URL" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java#L141-L166
train
GeneralElectric/snowizard
snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java
SnowizardClient.getId
public long getId() throws SnowizardClientException { for (final String host : hosts) { try { final SnowizardResponse snowizard = executeRequest(host); if (snowizard != null) { return snowizard.getId(0); } } catch (final Exception ex) { LOGGER.warn("Unable to get ID from host ({})", host); } } throw new SnowizardClientException( "Unable to generate ID from Snowizard"); }
java
public long getId() throws SnowizardClientException { for (final String host : hosts) { try { final SnowizardResponse snowizard = executeRequest(host); if (snowizard != null) { return snowizard.getId(0); } } catch (final Exception ex) { LOGGER.warn("Unable to get ID from host ({})", host); } } throw new SnowizardClientException( "Unable to generate ID from Snowizard"); }
[ "public", "long", "getId", "(", ")", "throws", "SnowizardClientException", "{", "for", "(", "final", "String", "host", ":", "hosts", ")", "{", "try", "{", "final", "SnowizardResponse", "snowizard", "=", "executeRequest", "(", "host", ")", ";", "if", "(", "...
Get a new ID from Snowizard @return generated ID @throws SnowizardClientException when unable to get an ID from any host
[ "Get", "a", "new", "ID", "from", "Snowizard" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java#L175-L188
train
GeneralElectric/snowizard
snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java
SnowizardClient.getIds
public List<Long> getIds(final int count) throws SnowizardClientException { for (final String host : hosts) { try { final SnowizardResponse snowizard = executeRequest(host, count); if (snowizard != null) { return snowizard.getIdList(); } } catch (final Exception ex) { LOGGER.warn("Unable to get ID from host ({})", host); } } throw new SnowizardClientException( "Unable to generate batch of IDs from Snowizard"); }
java
public List<Long> getIds(final int count) throws SnowizardClientException { for (final String host : hosts) { try { final SnowizardResponse snowizard = executeRequest(host, count); if (snowizard != null) { return snowizard.getIdList(); } } catch (final Exception ex) { LOGGER.warn("Unable to get ID from host ({})", host); } } throw new SnowizardClientException( "Unable to generate batch of IDs from Snowizard"); }
[ "public", "List", "<", "Long", ">", "getIds", "(", "final", "int", "count", ")", "throws", "SnowizardClientException", "{", "for", "(", "final", "String", "host", ":", "hosts", ")", "{", "try", "{", "final", "SnowizardResponse", "snowizard", "=", "executeReq...
Get multiple IDs from Snowizard @param count Number of IDs to return @return generated IDs @throws SnowizardClientException when unable to get an ID from any host
[ "Get", "multiple", "IDs", "from", "Snowizard" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-client/src/main/java/com/ge/snowizard/client/SnowizardClient.java#L199-L212
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Evaluator.java
Evaluator.resolveAvailable
protected String resolveAvailable(CommonTokenStream tokens, EvaluationContext context) { boolean hasMissing = false; List<Object> outputComponents = new ArrayList<>(); for (int t = 0; t < tokens.size() - 1; t++) { // we can ignore the final EOF token Token token = tokens.get(t); Token nextToken = tokens.get(t + 1); // if token is a NAME not followed by ( then it's a context reference if (token.getType() == ExcellentParser.NAME && nextToken.getType() != ExcellentParser.LPAREN) { try { outputComponents.add(context.resolveVariable(token.getText())); } catch (EvaluationError ex) { hasMissing = true; outputComponents.add(token); } } else { outputComponents.add(token); } } // if we don't have missing context references, perform evaluation as normal if (!hasMissing) { return null; } // re-combine the tokens and context values back into an expression StringBuilder output = new StringBuilder(String.valueOf(m_expressionPrefix)); for (Object outputComponent : outputComponents) { String compVal; if (outputComponent instanceof Token) { compVal = ((Token) outputComponent).getText(); } else { compVal = Conversions.toRepr(outputComponent, context); } output.append(compVal); } return output.toString(); }
java
protected String resolveAvailable(CommonTokenStream tokens, EvaluationContext context) { boolean hasMissing = false; List<Object> outputComponents = new ArrayList<>(); for (int t = 0; t < tokens.size() - 1; t++) { // we can ignore the final EOF token Token token = tokens.get(t); Token nextToken = tokens.get(t + 1); // if token is a NAME not followed by ( then it's a context reference if (token.getType() == ExcellentParser.NAME && nextToken.getType() != ExcellentParser.LPAREN) { try { outputComponents.add(context.resolveVariable(token.getText())); } catch (EvaluationError ex) { hasMissing = true; outputComponents.add(token); } } else { outputComponents.add(token); } } // if we don't have missing context references, perform evaluation as normal if (!hasMissing) { return null; } // re-combine the tokens and context values back into an expression StringBuilder output = new StringBuilder(String.valueOf(m_expressionPrefix)); for (Object outputComponent : outputComponents) { String compVal; if (outputComponent instanceof Token) { compVal = ((Token) outputComponent).getText(); } else { compVal = Conversions.toRepr(outputComponent, context); } output.append(compVal); } return output.toString(); }
[ "protected", "String", "resolveAvailable", "(", "CommonTokenStream", "tokens", ",", "EvaluationContext", "context", ")", "{", "boolean", "hasMissing", "=", "false", ";", "List", "<", "Object", ">", "outputComponents", "=", "new", "ArrayList", "<>", "(", ")", ";"...
Checks the token stream for context references and if there are missing references - substitutes available references and returns a partially evaluated expression. @param tokens the token stream (all tokens fetched) @param context the evaluation context @return the partially evaluated expression or null if expression can be fully evaluated
[ "Checks", "the", "token", "stream", "for", "context", "references", "and", "if", "there", "are", "missing", "references", "-", "substitutes", "available", "references", "and", "returns", "a", "partially", "evaluated", "expression", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Evaluator.java#L291-L330
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java
SpringUtils.getSpringBean
public static Object getSpringBean(ApplicationContext appContext, String id) { try { Object bean = appContext.getBean(id); return bean; } catch (BeansException e) { return null; } }
java
public static Object getSpringBean(ApplicationContext appContext, String id) { try { Object bean = appContext.getBean(id); return bean; } catch (BeansException e) { return null; } }
[ "public", "static", "Object", "getSpringBean", "(", "ApplicationContext", "appContext", ",", "String", "id", ")", "{", "try", "{", "Object", "bean", "=", "appContext", ".", "getBean", "(", "id", ")", ";", "return", "bean", ";", "}", "catch", "(", "BeansExc...
Gets a bean by its id. @param appContext @param name @return
[ "Gets", "a", "bean", "by", "its", "id", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java#L25-L32
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java
SpringUtils.getBean
public static <T> T getBean(ApplicationContext appContext, String id, Class<T> clazz) { try { return appContext.getBean(id, clazz); } catch (BeansException e) { return null; } }
java
public static <T> T getBean(ApplicationContext appContext, String id, Class<T> clazz) { try { return appContext.getBean(id, clazz); } catch (BeansException e) { return null; } }
[ "public", "static", "<", "T", ">", "T", "getBean", "(", "ApplicationContext", "appContext", ",", "String", "id", ",", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "return", "appContext", ".", "getBean", "(", "id", ",", "clazz", ")", ";", "}...
Gets a bean by its id and class. @param appContext @param id @param clazz @return
[ "Gets", "a", "bean", "by", "its", "id", "and", "class", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java#L58-L64
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java
SpringUtils.getBeansOfType
public static <T> Map<String, T> getBeansOfType(ApplicationContext appContext, Class<T> clazz) { try { return appContext.getBeansOfType(clazz); } catch (BeansException e) { return new HashMap<String, T>(); } }
java
public static <T> Map<String, T> getBeansOfType(ApplicationContext appContext, Class<T> clazz) { try { return appContext.getBeansOfType(clazz); } catch (BeansException e) { return new HashMap<String, T>(); } }
[ "public", "static", "<", "T", ">", "Map", "<", "String", ",", "T", ">", "getBeansOfType", "(", "ApplicationContext", "appContext", ",", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "return", "appContext", ".", "getBeansOfType", "(", "clazz", ")...
Gets all beans of a given type. @param appContext @param clazz @return a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values
[ "Gets", "all", "beans", "of", "a", "given", "type", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java#L74-L80
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java
SpringUtils.getBeansWithAnnotation
public static Map<String, Object> getBeansWithAnnotation(ApplicationContext appContext, Class<? extends Annotation> annotationType) { try { return appContext.getBeansWithAnnotation(annotationType); } catch (BeansException e) { return new HashMap<String, Object>(); } }
java
public static Map<String, Object> getBeansWithAnnotation(ApplicationContext appContext, Class<? extends Annotation> annotationType) { try { return appContext.getBeansWithAnnotation(annotationType); } catch (BeansException e) { return new HashMap<String, Object>(); } }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "getBeansWithAnnotation", "(", "ApplicationContext", "appContext", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType", ")", "{", "try", "{", "return", "appContext", ".", "getBeansW...
Gets all beans whose Class has the supplied Annotation type. @param appContext @param annotationType @return a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values
[ "Gets", "all", "beans", "whose", "Class", "has", "the", "supplied", "Annotation", "type", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java#L90-L97
train
RestExpress/PluginExpress
metrics/src/main/java/com/strategicgains/restexpress/plugin/metrics/MetricsPlugin.java
MetricsPlugin.register
@Override public MetricsPlugin register(RestExpress server) { if (isRegistered) return this; server.registerPlugin(this); this.isRegistered = true; server .addMessageObserver(this) .addPreprocessor(this) .addFinallyProcessor(this); return this; }
java
@Override public MetricsPlugin register(RestExpress server) { if (isRegistered) return this; server.registerPlugin(this); this.isRegistered = true; server .addMessageObserver(this) .addPreprocessor(this) .addFinallyProcessor(this); return this; }
[ "@", "Override", "public", "MetricsPlugin", "register", "(", "RestExpress", "server", ")", "{", "if", "(", "isRegistered", ")", "return", "this", ";", "server", ".", "registerPlugin", "(", "this", ")", ";", "this", ".", "isRegistered", "=", "true", ";", "s...
Register the MetricsPlugin with the RestExpress server. @param server a RestExpress server instance. @return MetricsPlugin
[ "Register", "the", "MetricsPlugin", "with", "the", "RestExpress", "server", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/metrics/src/main/java/com/strategicgains/restexpress/plugin/metrics/MetricsPlugin.java#L100-L114
train
RestExpress/PluginExpress
metrics/src/main/java/com/strategicgains/restexpress/plugin/metrics/MetricsPlugin.java
MetricsPlugin.process
@Override public void process(Request request, Response response) { Long duration = computeDurationMillis(START_TIMES_BY_CORRELATION_ID.get(request.getCorrelationId())); if (duration != null && duration.longValue() > 0) { response.addHeader("X-Response-Time", String.valueOf(duration)); } }
java
@Override public void process(Request request, Response response) { Long duration = computeDurationMillis(START_TIMES_BY_CORRELATION_ID.get(request.getCorrelationId())); if (duration != null && duration.longValue() > 0) { response.addHeader("X-Response-Time", String.valueOf(duration)); } }
[ "@", "Override", "public", "void", "process", "(", "Request", "request", ",", "Response", "response", ")", "{", "Long", "duration", "=", "computeDurationMillis", "(", "START_TIMES_BY_CORRELATION_ID", ".", "get", "(", "request", ".", "getCorrelationId", "(", ")", ...
Set the 'X-Response-Time' header to the response time in milliseconds.
[ "Set", "the", "X", "-", "Response", "-", "Time", "header", "to", "the", "response", "time", "in", "milliseconds", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/metrics/src/main/java/com/strategicgains/restexpress/plugin/metrics/MetricsPlugin.java#L235-L244
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java
Ipv4Utils.isValidIp
public static boolean isValidIp(String ip) { if (!IP_PATTERN_FULL.matcher(ip).matches()) { return false; } String[] ipArr = ip.split("\\."); for (String part : ipArr) { int v = Integer.parseInt(part); if (v < 0 || v > 255) { return false; } } return true; }
java
public static boolean isValidIp(String ip) { if (!IP_PATTERN_FULL.matcher(ip).matches()) { return false; } String[] ipArr = ip.split("\\."); for (String part : ipArr) { int v = Integer.parseInt(part); if (v < 0 || v > 255) { return false; } } return true; }
[ "public", "static", "boolean", "isValidIp", "(", "String", "ip", ")", "{", "if", "(", "!", "IP_PATTERN_FULL", ".", "matcher", "(", "ip", ")", ".", "matches", "(", ")", ")", "{", "return", "false", ";", "}", "String", "[", "]", "ipArr", "=", "ip", "...
Check is an IP is valid. @param ip @return @since 0.9.1.1
[ "Check", "is", "an", "IP", "is", "valid", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java#L25-L37
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/VersionUtils.java
VersionUtils.normalisedVersion
public static String normalisedVersion(String version, String sep, int maxWidth) { if (version == null) { return null; } String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version); StringBuilder sb = new StringBuilder(); for (String s : split) { sb.append(String.format("%" + maxWidth + 's', s)); } return sb.toString(); }
java
public static String normalisedVersion(String version, String sep, int maxWidth) { if (version == null) { return null; } String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version); StringBuilder sb = new StringBuilder(); for (String s : split) { sb.append(String.format("%" + maxWidth + 's', s)); } return sb.toString(); }
[ "public", "static", "String", "normalisedVersion", "(", "String", "version", ",", "String", "sep", ",", "int", "maxWidth", ")", "{", "if", "(", "version", "==", "null", ")", "{", "return", "null", ";", "}", "String", "[", "]", "split", "=", "Pattern", ...
Normalizes a version string. @param version @param sep @param maxWidth @return
[ "Normalizes", "a", "version", "string", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/VersionUtils.java#L45-L56
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.getEstimateNumKeys
public long getEstimateNumKeys(String cfName) throws RocksDbException { String prop = getProperty(cfName, "rocksdb.estimate-num-keys"); return prop != null ? Long.parseLong(prop) : 0; }
java
public long getEstimateNumKeys(String cfName) throws RocksDbException { String prop = getProperty(cfName, "rocksdb.estimate-num-keys"); return prop != null ? Long.parseLong(prop) : 0; }
[ "public", "long", "getEstimateNumKeys", "(", "String", "cfName", ")", "throws", "RocksDbException", "{", "String", "prop", "=", "getProperty", "(", "cfName", ",", "\"rocksdb.estimate-num-keys\"", ")", ";", "return", "prop", "!=", "null", "?", "Long", ".", "parse...
Gets estimated number of keys for a column family. @param cfName @return @throws RocksDbException
[ "Gets", "estimated", "number", "of", "keys", "for", "a", "column", "family", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L471-L474
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.getIterator
public RocksIterator getIterator(String cfName) { synchronized (iterators) { RocksIterator it = iterators.get(cfName); if (it == null) { ColumnFamilyHandle cfh = getColumnFamilyHandle(cfName); if (cfh == null) { return null; } it = rocksDb.newIterator(cfh, readOptions); iterators.put(cfName, it); } return it; } }
java
public RocksIterator getIterator(String cfName) { synchronized (iterators) { RocksIterator it = iterators.get(cfName); if (it == null) { ColumnFamilyHandle cfh = getColumnFamilyHandle(cfName); if (cfh == null) { return null; } it = rocksDb.newIterator(cfh, readOptions); iterators.put(cfName, it); } return it; } }
[ "public", "RocksIterator", "getIterator", "(", "String", "cfName", ")", "{", "synchronized", "(", "iterators", ")", "{", "RocksIterator", "it", "=", "iterators", ".", "get", "(", "cfName", ")", ";", "if", "(", "it", "==", "null", ")", "{", "ColumnFamilyHan...
Obtains an iterator for a column family. <p> Iterators will be automatically closed by this wrapper. </p> @param cfName @return
[ "Obtains", "an", "iterator", "for", "a", "column", "family", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L486-L499
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.delete
public void delete(WriteOptions writeOptions, String key) throws RocksDbException { delete(DEFAULT_COLUMN_FAMILY, writeOptions, key); }
java
public void delete(WriteOptions writeOptions, String key) throws RocksDbException { delete(DEFAULT_COLUMN_FAMILY, writeOptions, key); }
[ "public", "void", "delete", "(", "WriteOptions", "writeOptions", ",", "String", "key", ")", "throws", "RocksDbException", "{", "delete", "(", "DEFAULT_COLUMN_FAMILY", ",", "writeOptions", ",", "key", ")", ";", "}" ]
Deletes a key from the default family, specifying write options.F @param writeOptions @param key @throws RocksDBException
[ "Deletes", "a", "key", "from", "the", "default", "family", "specifying", "write", "options", ".", "F" ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L519-L521
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.delete
public void delete(String cfName, String key) throws RocksDbException { delete(cfName, writeOptions, key); }
java
public void delete(String cfName, String key) throws RocksDbException { delete(cfName, writeOptions, key); }
[ "public", "void", "delete", "(", "String", "cfName", ",", "String", "key", ")", "throws", "RocksDbException", "{", "delete", "(", "cfName", ",", "writeOptions", ",", "key", ")", ";", "}" ]
Deletes a key from a column family. @param cfName @param key @throws RocksDBException
[ "Deletes", "a", "key", "from", "a", "column", "family", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L530-L532
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.delete
public void delete(String cfName, WriteOptions writeOptions, String key) throws RocksDbException { if (cfName == null) { cfName = DEFAULT_COLUMN_FAMILY; } try { delete(getColumnFamilyHandle(cfName), writeOptions, key.getBytes(StandardCharsets.UTF_8)); } catch (RocksDbException.ColumnFamilyNotExists e) { throw new RocksDbException.ColumnFamilyNotExists(cfName); } }
java
public void delete(String cfName, WriteOptions writeOptions, String key) throws RocksDbException { if (cfName == null) { cfName = DEFAULT_COLUMN_FAMILY; } try { delete(getColumnFamilyHandle(cfName), writeOptions, key.getBytes(StandardCharsets.UTF_8)); } catch (RocksDbException.ColumnFamilyNotExists e) { throw new RocksDbException.ColumnFamilyNotExists(cfName); } }
[ "public", "void", "delete", "(", "String", "cfName", ",", "WriteOptions", "writeOptions", ",", "String", "key", ")", "throws", "RocksDbException", "{", "if", "(", "cfName", "==", "null", ")", "{", "cfName", "=", "DEFAULT_COLUMN_FAMILY", ";", "}", "try", "{",...
Deletes a key from a column family, specifying write options. @param cfName @param writeOptions @param key @throws RocksDBException
[ "Deletes", "a", "key", "from", "a", "column", "family", "specifying", "write", "options", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L542-L553
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.get
public byte[] get(ReadOptions readOPtions, String key) throws RocksDbException { return get(DEFAULT_COLUMN_FAMILY, readOPtions, key); }
java
public byte[] get(ReadOptions readOPtions, String key) throws RocksDbException { return get(DEFAULT_COLUMN_FAMILY, readOPtions, key); }
[ "public", "byte", "[", "]", "get", "(", "ReadOptions", "readOPtions", ",", "String", "key", ")", "throws", "RocksDbException", "{", "return", "get", "(", "DEFAULT_COLUMN_FAMILY", ",", "readOPtions", ",", "key", ")", ";", "}" ]
Gets a value from the default column family, specifying read options. @param readOPtions @param key @return @throws RocksDbException
[ "Gets", "a", "value", "from", "the", "default", "column", "family", "specifying", "read", "options", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L736-L738
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.get
public byte[] get(String cfName, String key) throws RocksDbException { return get(cfName, readOptions, key); }
java
public byte[] get(String cfName, String key) throws RocksDbException { return get(cfName, readOptions, key); }
[ "public", "byte", "[", "]", "get", "(", "String", "cfName", ",", "String", "key", ")", "throws", "RocksDbException", "{", "return", "get", "(", "cfName", ",", "readOptions", ",", "key", ")", ";", "}" ]
Gets a value from a column family. @param cfName @param key @return @throws RocksDbException
[ "Gets", "a", "value", "from", "a", "column", "family", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L748-L750
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.get
public byte[] get(String cfName, ReadOptions readOptions, String key) throws RocksDbException { if (cfName == null) { cfName = DEFAULT_COLUMN_FAMILY; } ColumnFamilyHandle cfh = columnFamilyHandles.get(cfName); if (cfh == null) { throw new RocksDbException.ColumnFamilyNotExists(cfName); } return get(cfh, readOptions, key.getBytes(StandardCharsets.UTF_8)); }
java
public byte[] get(String cfName, ReadOptions readOptions, String key) throws RocksDbException { if (cfName == null) { cfName = DEFAULT_COLUMN_FAMILY; } ColumnFamilyHandle cfh = columnFamilyHandles.get(cfName); if (cfh == null) { throw new RocksDbException.ColumnFamilyNotExists(cfName); } return get(cfh, readOptions, key.getBytes(StandardCharsets.UTF_8)); }
[ "public", "byte", "[", "]", "get", "(", "String", "cfName", ",", "ReadOptions", "readOptions", ",", "String", "key", ")", "throws", "RocksDbException", "{", "if", "(", "cfName", "==", "null", ")", "{", "cfName", "=", "DEFAULT_COLUMN_FAMILY", ";", "}", "Col...
Gets a value from a column family, specifying read options. @param cfName @param readOptions @param key @return @throws RocksDbException
[ "Gets", "a", "value", "from", "a", "column", "family", "specifying", "read", "options", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L761-L770
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.get
protected byte[] get(ColumnFamilyHandle cfh, ReadOptions readOptions, byte[] key) throws RocksDbException { try { return rocksDb.get(cfh, readOptions != null ? readOptions : this.readOptions, key); } catch (Exception e) { throw e instanceof RocksDbException ? (RocksDbException) e : new RocksDbException(e); } }
java
protected byte[] get(ColumnFamilyHandle cfh, ReadOptions readOptions, byte[] key) throws RocksDbException { try { return rocksDb.get(cfh, readOptions != null ? readOptions : this.readOptions, key); } catch (Exception e) { throw e instanceof RocksDbException ? (RocksDbException) e : new RocksDbException(e); } }
[ "protected", "byte", "[", "]", "get", "(", "ColumnFamilyHandle", "cfh", ",", "ReadOptions", "readOptions", ",", "byte", "[", "]", "key", ")", "throws", "RocksDbException", "{", "try", "{", "return", "rocksDb", ".", "get", "(", "cfh", ",", "readOptions", "!...
Gets a value. @param cfh @param readOptions @param key @return @throws RocksDbException
[ "Gets", "a", "value", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L781-L788
train
RestExpress/PluginExpress
logging/src/main/java/org/restexpress/plugin/logging/LoggingMessageObserver.java
LoggingMessageObserver.createCompleteMessage
protected String createCompleteMessage(Request request, Response response, Timer timer) { StringBuilder sb = new StringBuilder(request.getEffectiveHttpMethod().toString()); sb.append(" "); sb.append(request.getUrl()); if (timer != null) { sb.append(" responded with "); sb.append(response.getResponseStatus().toString()); sb.append(" in "); sb.append(timer.toString()); } else { sb.append(" responded with "); sb.append(response.getResponseStatus().toString()); sb.append(" (no timer found)"); } return sb.toString(); }
java
protected String createCompleteMessage(Request request, Response response, Timer timer) { StringBuilder sb = new StringBuilder(request.getEffectiveHttpMethod().toString()); sb.append(" "); sb.append(request.getUrl()); if (timer != null) { sb.append(" responded with "); sb.append(response.getResponseStatus().toString()); sb.append(" in "); sb.append(timer.toString()); } else { sb.append(" responded with "); sb.append(response.getResponseStatus().toString()); sb.append(" (no timer found)"); } return sb.toString(); }
[ "protected", "String", "createCompleteMessage", "(", "Request", "request", ",", "Response", "response", ",", "Timer", "timer", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "request", ".", "getEffectiveHttpMethod", "(", ")", ".", "toString", ...
Create the message to be logged when a request is completed successfully. Sub-classes can override. @param request @param response @param timer @return a string message.
[ "Create", "the", "message", "to", "be", "logged", "when", "a", "request", "is", "completed", "successfully", ".", "Sub", "-", "classes", "can", "override", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/logging/src/main/java/org/restexpress/plugin/logging/LoggingMessageObserver.java#L88-L109
train
RestExpress/PluginExpress
logging/src/main/java/org/restexpress/plugin/logging/LoggingMessageObserver.java
LoggingMessageObserver.createExceptionMessage
protected String createExceptionMessage(Throwable exception, Request request, Response response) { StringBuilder sb = new StringBuilder(request.getEffectiveHttpMethod().toString()); sb.append(' '); sb.append(request.getUrl()); sb.append(" threw exception: "); sb.append(exception.getClass().getSimpleName()); return sb.toString(); }
java
protected String createExceptionMessage(Throwable exception, Request request, Response response) { StringBuilder sb = new StringBuilder(request.getEffectiveHttpMethod().toString()); sb.append(' '); sb.append(request.getUrl()); sb.append(" threw exception: "); sb.append(exception.getClass().getSimpleName()); return sb.toString(); }
[ "protected", "String", "createExceptionMessage", "(", "Throwable", "exception", ",", "Request", "request", ",", "Response", "response", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "request", ".", "getEffectiveHttpMethod", "(", ")", ".", "toS...
Create the message to be logged when a request results in an exception. Sub-classes can override. @param exception the exception that occurred. @param request the request. @param response the response. @return a string message.
[ "Create", "the", "message", "to", "be", "logged", "when", "a", "request", "results", "in", "an", "exception", ".", "Sub", "-", "classes", "can", "override", "." ]
aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69
https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/logging/src/main/java/org/restexpress/plugin/logging/LoggingMessageObserver.java#L120-L128
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DPathUtils.java
DPathUtils.deleteValue
public static void deleteValue(Object target, String dPath) { if (target instanceof JsonNode) { deleteValue((JsonNode) target, dPath); return; } String[] paths = splitDpath(dPath); Object cursor = target; // "seek"to the correct position for (int i = 0; i < paths.length - 1; i++) { cursor = extractValue(cursor, paths[i]); } if (cursor == null) { return; } String index = paths[paths.length - 1]; Matcher m = PATTERN_INDEX.matcher(index); if (m.matches()) { try { int i = Integer.parseInt(m.group(1)); deleteFieldValue(dPath, cursor, i); } catch (IndexOutOfBoundsException e) { // rethrow for now throw e; } catch (NumberFormatException e) { throw new IllegalArgumentException("Error: Invalid index. Path [" + dPath + "], target [" + cursor.getClass() + "].", e); } } else { deleteFieldValue(dPath, cursor, index); } }
java
public static void deleteValue(Object target, String dPath) { if (target instanceof JsonNode) { deleteValue((JsonNode) target, dPath); return; } String[] paths = splitDpath(dPath); Object cursor = target; // "seek"to the correct position for (int i = 0; i < paths.length - 1; i++) { cursor = extractValue(cursor, paths[i]); } if (cursor == null) { return; } String index = paths[paths.length - 1]; Matcher m = PATTERN_INDEX.matcher(index); if (m.matches()) { try { int i = Integer.parseInt(m.group(1)); deleteFieldValue(dPath, cursor, i); } catch (IndexOutOfBoundsException e) { // rethrow for now throw e; } catch (NumberFormatException e) { throw new IllegalArgumentException("Error: Invalid index. Path [" + dPath + "], target [" + cursor.getClass() + "].", e); } } else { deleteFieldValue(dPath, cursor, index); } }
[ "public", "static", "void", "deleteValue", "(", "Object", "target", ",", "String", "dPath", ")", "{", "if", "(", "target", "instanceof", "JsonNode", ")", "{", "deleteValue", "(", "(", "JsonNode", ")", "target", ",", "dPath", ")", ";", "return", ";", "}",...
Delete a value from the target object specified by DPath expression. <ul> <li>If the specified item's parent is a list or map, the item (specified by {@code dPath}) will be removed (for list, next items will be shifted up one position).</li> <li>If the specified item's parent is an array, the item (specified by {@code dPath}) will be set to {@code null}.</li> </ul> @param target @param dPath @since 0.6.1
[ "Delete", "a", "value", "from", "the", "target", "object", "specified", "by", "DPath", "expression", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DPathUtils.java#L702-L733
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
SerializationUtils.toJsonString
public static String toJsonString(Object obj, ClassLoader classLoader) { if (obj == null) { return "null"; } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { ObjectMapper mapper = poolMapper.borrowObject(); if (mapper != null) { try { return mapper.writeValueAsString(obj); } finally { poolMapper.returnObject(mapper); } } throw new SerializationException("No ObjectMapper instance avaialble!"); } catch (Exception e) { throw e instanceof SerializationException ? (SerializationException) e : new SerializationException(e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
java
public static String toJsonString(Object obj, ClassLoader classLoader) { if (obj == null) { return "null"; } ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { ObjectMapper mapper = poolMapper.borrowObject(); if (mapper != null) { try { return mapper.writeValueAsString(obj); } finally { poolMapper.returnObject(mapper); } } throw new SerializationException("No ObjectMapper instance avaialble!"); } catch (Exception e) { throw e instanceof SerializationException ? (SerializationException) e : new SerializationException(e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
[ "public", "static", "String", "toJsonString", "(", "Object", "obj", ",", "ClassLoader", "classLoader", ")", "{", "if", "(", "obj", "==", "null", ")", "{", "return", "\"null\"", ";", "}", "ClassLoader", "oldClassLoader", "=", "Thread", ".", "currentThread", "...
Serialize an object to JSON string, with a custom class loader. @param obj @param classLoader @return
[ "Serialize", "an", "object", "to", "JSON", "string", "with", "a", "custom", "class", "loader", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L367-L391
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
SerializationUtils.fromJsonString
public static <T> T fromJsonString(String jsonString, Class<T> clazz) { return fromJsonString(jsonString, clazz, null); }
java
public static <T> T fromJsonString(String jsonString, Class<T> clazz) { return fromJsonString(jsonString, clazz, null); }
[ "public", "static", "<", "T", ">", "T", "fromJsonString", "(", "String", "jsonString", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "fromJsonString", "(", "jsonString", ",", "clazz", ",", "null", ")", ";", "}" ]
Deserialize a JSON string. @param jsonString @param clazz @return
[ "Deserialize", "a", "JSON", "string", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L646-L648
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java
FunctionManager.addLibrary
public void addLibrary(Class<?> library) { for (Method method : library.getDeclaredMethods()) { if ((method.getModifiers() & Modifier.PUBLIC) == 0) { continue; // ignore non-public methods } String name = method.getName().toLowerCase(); // strip preceding _ chars used to avoid conflicts with Java keywords if (name.startsWith("_")) { name = name.substring(1); } m_functions.put(name, method); } }
java
public void addLibrary(Class<?> library) { for (Method method : library.getDeclaredMethods()) { if ((method.getModifiers() & Modifier.PUBLIC) == 0) { continue; // ignore non-public methods } String name = method.getName().toLowerCase(); // strip preceding _ chars used to avoid conflicts with Java keywords if (name.startsWith("_")) { name = name.substring(1); } m_functions.put(name, method); } }
[ "public", "void", "addLibrary", "(", "Class", "<", "?", ">", "library", ")", "{", "for", "(", "Method", "method", ":", "library", ".", "getDeclaredMethods", "(", ")", ")", "{", "if", "(", "(", "method", ".", "getModifiers", "(", ")", "&", "Modifier", ...
Adds functions from a library class @param library the library class
[ "Adds", "functions", "from", "a", "library", "class" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java#L28-L43
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java
FunctionManager.invokeFunction
public Object invokeFunction(EvaluationContext ctx, String name, List<Object> args) { // find function with given name Method func = getFunction(name); if (func == null) { throw new EvaluationError("Undefined function: " + name); } List<Object> parameters = new ArrayList<>(); List<Object> remainingArgs = new ArrayList<>(args); for (Parameter param : Parameter.fromMethod(func)) { BooleanDefault defaultBool = param.getAnnotation(BooleanDefault.class); IntegerDefault defaultInt = param.getAnnotation(IntegerDefault.class); StringDefault defaultStr = param.getAnnotation(StringDefault.class); if (param.getType().equals(EvaluationContext.class)) { parameters.add(ctx); } else if (param.getType().isArray()) { // we've reach a varargs param parameters.add(remainingArgs.toArray(new Object[remainingArgs.size()])); remainingArgs.clear(); break; } else if (remainingArgs.size() > 0) { Object arg = remainingArgs.remove(0); parameters.add(arg); } else if (defaultBool != null) { parameters.add(defaultBool.value()); } else if (defaultInt != null) { parameters.add(defaultInt.value()); } else if (defaultStr != null) { parameters.add(defaultStr.value()); } else { throw new EvaluationError("Too few arguments provided for function " + name); } } if (!remainingArgs.isEmpty()) { throw new EvaluationError("Too many arguments provided for function " + name); } try { return func.invoke(null, parameters.toArray(new Object[parameters.size()])); } catch (Exception e) { List<String> prettyArgs = new ArrayList<>(); for (Object arg : args) { String pretty; if (arg instanceof String) { pretty = "\"" + arg + "\""; } else { try { pretty = Conversions.toString(arg, ctx); } catch (EvaluationError ex) { pretty = arg.toString(); } } prettyArgs.add(pretty); } throw new EvaluationError("Error calling function " + name + " with arguments " + StringUtils.join(prettyArgs, ", "), e); } }
java
public Object invokeFunction(EvaluationContext ctx, String name, List<Object> args) { // find function with given name Method func = getFunction(name); if (func == null) { throw new EvaluationError("Undefined function: " + name); } List<Object> parameters = new ArrayList<>(); List<Object> remainingArgs = new ArrayList<>(args); for (Parameter param : Parameter.fromMethod(func)) { BooleanDefault defaultBool = param.getAnnotation(BooleanDefault.class); IntegerDefault defaultInt = param.getAnnotation(IntegerDefault.class); StringDefault defaultStr = param.getAnnotation(StringDefault.class); if (param.getType().equals(EvaluationContext.class)) { parameters.add(ctx); } else if (param.getType().isArray()) { // we've reach a varargs param parameters.add(remainingArgs.toArray(new Object[remainingArgs.size()])); remainingArgs.clear(); break; } else if (remainingArgs.size() > 0) { Object arg = remainingArgs.remove(0); parameters.add(arg); } else if (defaultBool != null) { parameters.add(defaultBool.value()); } else if (defaultInt != null) { parameters.add(defaultInt.value()); } else if (defaultStr != null) { parameters.add(defaultStr.value()); } else { throw new EvaluationError("Too few arguments provided for function " + name); } } if (!remainingArgs.isEmpty()) { throw new EvaluationError("Too many arguments provided for function " + name); } try { return func.invoke(null, parameters.toArray(new Object[parameters.size()])); } catch (Exception e) { List<String> prettyArgs = new ArrayList<>(); for (Object arg : args) { String pretty; if (arg instanceof String) { pretty = "\"" + arg + "\""; } else { try { pretty = Conversions.toString(arg, ctx); } catch (EvaluationError ex) { pretty = arg.toString(); } } prettyArgs.add(pretty); } throw new EvaluationError("Error calling function " + name + " with arguments " + StringUtils.join(prettyArgs, ", "), e); } }
[ "public", "Object", "invokeFunction", "(", "EvaluationContext", "ctx", ",", "String", "name", ",", "List", "<", "Object", ">", "args", ")", "{", "// find function with given name", "Method", "func", "=", "getFunction", "(", "name", ")", ";", "if", "(", "func",...
Invokes a function @param ctx the evaluation context @param name the function name (case insensitive) @param args the arguments to be passed to the function @return the function return value
[ "Invokes", "a", "function" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java#L56-L124
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java
FunctionManager.buildListing
public List<FunctionDescriptor> buildListing() { List<FunctionDescriptor> listing = new ArrayList<>(); for (Map.Entry<String, Method> entry : m_functions.entrySet()) { FunctionDescriptor descriptor = new FunctionDescriptor(entry.getKey().toUpperCase()); listing.add(descriptor); } Collections.sort(listing, new Comparator<FunctionDescriptor>() { @Override public int compare(FunctionDescriptor f1, FunctionDescriptor f2) { return f1.m_name.compareTo(f2.m_name); } }); return listing; }
java
public List<FunctionDescriptor> buildListing() { List<FunctionDescriptor> listing = new ArrayList<>(); for (Map.Entry<String, Method> entry : m_functions.entrySet()) { FunctionDescriptor descriptor = new FunctionDescriptor(entry.getKey().toUpperCase()); listing.add(descriptor); } Collections.sort(listing, new Comparator<FunctionDescriptor>() { @Override public int compare(FunctionDescriptor f1, FunctionDescriptor f2) { return f1.m_name.compareTo(f2.m_name); } }); return listing; }
[ "public", "List", "<", "FunctionDescriptor", ">", "buildListing", "(", ")", "{", "List", "<", "FunctionDescriptor", ">", "listing", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Method", ">", "entry",...
Builds a listing of all functions sorted A-Z. Unlike the Python port, this only returns function names as Java doesn't so easily support reading of docstrings and Java 7 doesn't provide access to parameter names. @return the function listing
[ "Builds", "a", "listing", "of", "all", "functions", "sorted", "A", "-", "Z", ".", "Unlike", "the", "Python", "port", "this", "only", "returns", "function", "names", "as", "Java", "doesn", "t", "so", "easily", "support", "reading", "of", "docstrings", "and"...
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/FunctionManager.java#L131-L147
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java
JsonRpcUtils.buildResponse
public static JsonNode buildResponse(int status, String message, Object data) { return SerializationUtils.toJson(MapUtils.removeNulls(MapUtils.createMap(FIELD_STATUS, status, FIELD_MESSAGE, message, FIELD_DATA, data))); }
java
public static JsonNode buildResponse(int status, String message, Object data) { return SerializationUtils.toJson(MapUtils.removeNulls(MapUtils.createMap(FIELD_STATUS, status, FIELD_MESSAGE, message, FIELD_DATA, data))); }
[ "public", "static", "JsonNode", "buildResponse", "(", "int", "status", ",", "String", "message", ",", "Object", "data", ")", "{", "return", "SerializationUtils", ".", "toJson", "(", "MapUtils", ".", "removeNulls", "(", "MapUtils", ".", "createMap", "(", "FIELD...
Build Json-RPC's response in JSON format. <p> Json-RPC response as the following format: </p> <pre> { "status" : (int) response status/error code, "message": (string) response message, "data" : (object) response data } </pre> @param status @param message @param data @return
[ "Build", "Json", "-", "RPC", "s", "response", "in", "JSON", "format", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java#L42-L45
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java
JsonRpcUtils.callHttpPost
public static RequestResponse callHttpPost(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPost(url, headers, urlParams, requestData); }
java
public static RequestResponse callHttpPost(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPost(url, headers, urlParams, requestData); }
[ "public", "static", "RequestResponse", "callHttpPost", "(", "HttpJsonRpcClient", "client", ",", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ",", "Object", "requestData",...
Perform a HTTP POST request. @param client @param url @param headers @param urlParams @param requestData @return @since 0.9.1.6
[ "Perform", "a", "HTTP", "POST", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java#L135-L138
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java
JsonRpcUtils.callHttpPut
public static RequestResponse callHttpPut(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPut(url, headers, urlParams, requestData); }
java
public static RequestResponse callHttpPut(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPut(url, headers, urlParams, requestData); }
[ "public", "static", "RequestResponse", "callHttpPut", "(", "HttpJsonRpcClient", "client", ",", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ",", "Object", "requestData", ...
Perform a HTTP PUT request. @param client @param url @param headers @param urlParams @param requestData @return @since 0.9.1.6
[ "Perform", "a", "HTTP", "PUT", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java#L165-L168
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java
JsonRpcUtils.callHttpPatch
public static RequestResponse callHttpPatch(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPatch(url, headers, urlParams, requestData); }
java
public static RequestResponse callHttpPatch(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { return client.doPatch(url, headers, urlParams, requestData); }
[ "public", "static", "RequestResponse", "callHttpPatch", "(", "HttpJsonRpcClient", "client", ",", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ",", "Object", "requestData"...
Perform a HTTP PATCH request. @param client @param url @param headers @param urlParams @param requestData @return @since 0.9.1.6
[ "Perform", "a", "HTTP", "PATCH", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java#L195-L198
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java
JsonRpcUtils.callHttpDelete
public static RequestResponse callHttpDelete(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams) { return client.doDelete(url, headers, urlParams); }
java
public static RequestResponse callHttpDelete(HttpJsonRpcClient client, String url, Map<String, Object> headers, Map<String, Object> urlParams) { return client.doDelete(url, headers, urlParams); }
[ "public", "static", "RequestResponse", "callHttpDelete", "(", "HttpJsonRpcClient", "client", ",", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ")", "{", "return", "clie...
Perform a HTTP DELETE request. @param client @param url @param headers @param urlParams @return @since 0.9.1.6
[ "Perform", "a", "HTTP", "DELETE", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/JsonRpcUtils.java#L223-L226
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java
HttpJsonRpcClient.doGet
public RequestResponse doGet(String url, Map<String, Object> headers, Map<String, Object> urlParams) { RequestResponse requestResponse = initRequestResponse("GET", url, headers, urlParams, null); Request.Builder requestBuilder = buildRequest(url, headers, urlParams).get(); return doCall(client, requestBuilder.build(), requestResponse); }
java
public RequestResponse doGet(String url, Map<String, Object> headers, Map<String, Object> urlParams) { RequestResponse requestResponse = initRequestResponse("GET", url, headers, urlParams, null); Request.Builder requestBuilder = buildRequest(url, headers, urlParams).get(); return doCall(client, requestBuilder.build(), requestResponse); }
[ "public", "RequestResponse", "doGet", "(", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ")", "{", "RequestResponse", "requestResponse", "=", "initRequestResponse", "(", ...
Perform a GET request. @param url @param headers @param urlParams @return
[ "Perform", "a", "GET", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java#L198-L203
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java
HttpJsonRpcClient.doPost
public RequestResponse doPost(String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { RequestResponse rr = initRequestResponse("POST", url, headers, urlParams, requestData); Request.Builder requestBuilder = buildRequest(url, headers, urlParams) .post(buildRequestBody(rr)); return doCall(client, requestBuilder.build(), rr); }
java
public RequestResponse doPost(String url, Map<String, Object> headers, Map<String, Object> urlParams, Object requestData) { RequestResponse rr = initRequestResponse("POST", url, headers, urlParams, requestData); Request.Builder requestBuilder = buildRequest(url, headers, urlParams) .post(buildRequestBody(rr)); return doCall(client, requestBuilder.build(), rr); }
[ "public", "RequestResponse", "doPost", "(", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ",", "Object", "requestData", ")", "{", "RequestResponse", "rr", "=", "initRe...
Perform a POST request. @param url @param headers @param urlParams @param requestData @return
[ "Perform", "a", "POST", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java#L214-L220
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java
HttpJsonRpcClient.doDelete
public RequestResponse doDelete(String url, Map<String, Object> headers, Map<String, Object> urlParams) { return doDelete(url, headers, urlParams, null); }
java
public RequestResponse doDelete(String url, Map<String, Object> headers, Map<String, Object> urlParams) { return doDelete(url, headers, urlParams, null); }
[ "public", "RequestResponse", "doDelete", "(", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "Map", "<", "String", ",", "Object", ">", "urlParams", ")", "{", "return", "doDelete", "(", "url", ",", "headers", ",", "urlPara...
Perform a DELETE request. @param url @param headers @param urlParams @return
[ "Perform", "a", "DELETE", "request", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/HttpJsonRpcClient.java#L264-L267
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java
MapUtils.getValue
public static <T> T getValue(Map<String, Object> map, String key, Class<T> clazz) { return map != null ? ValueUtils.convertValue(map.get(key), clazz) : null; }
java
public static <T> T getValue(Map<String, Object> map, String key, Class<T> clazz) { return map != null ? ValueUtils.convertValue(map.get(key), clazz) : null; }
[ "public", "static", "<", "T", ">", "T", "getValue", "(", "Map", "<", "String", ",", "Object", ">", "map", ",", "String", "key", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "map", "!=", "null", "?", "ValueUtils", ".", "convertValue", "...
Extract a value from a map. @param map @param key @param clazz @return
[ "Extract", "a", "value", "from", "a", "map", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java#L40-L42
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java
MapUtils.removeNulls
public static <K, V> Map<K, V> removeNulls(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); map.forEach((k, v) -> { if (v != null) { result.put(k, v); } }); return result; }
java
public static <K, V> Map<K, V> removeNulls(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); map.forEach((k, v) -> { if (v != null) { result.put(k, v); } }); return result; }
[ "public", "static", "<", "K", ",", "V", ">", "Map", "<", "K", ",", "V", ">", "removeNulls", "(", "Map", "<", "K", ",", "V", ">", "map", ")", "{", "Map", "<", "K", ",", "V", ">", "result", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "m...
Remove null values from map. @param map @return @since 0.9.0
[ "Remove", "null", "values", "from", "map", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java#L73-L81
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java
ReflectionUtils.hasSuperClass
public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { if (clazz == null || superClazz == null || clazz == superClazz) { return false; } if (clazz.isInterface()) { return superClazz.isAssignableFrom(clazz); } Class<?> parent = clazz.getSuperclass(); while (parent != null) { if (parent == superClazz) { return true; } parent = parent.getSuperclass(); } return false; }
java
public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { if (clazz == null || superClazz == null || clazz == superClazz) { return false; } if (clazz.isInterface()) { return superClazz.isAssignableFrom(clazz); } Class<?> parent = clazz.getSuperclass(); while (parent != null) { if (parent == superClazz) { return true; } parent = parent.getSuperclass(); } return false; }
[ "public", "static", "boolean", "hasSuperClass", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", ">", "superClazz", ")", "{", "if", "(", "clazz", "==", "null", "||", "superClazz", "==", "null", "||", "clazz", "==", "superClazz", ")", "{", ...
Tells if a class is a sub-class of a super-class. Note: <ul> <li>Sub-class against super-class: this method returns {@code true}.</li> <li>Sub-interface against super-interface: this method returns {@code true}.</li> <li>Class against interface: this method returns {@code false}.</li> </ul> @param clazz class to check @param superClazz the super-class to check @return {@code true} if {@code superClazz} is indeed the super-class of {@code clazz}
[ "Tells", "if", "a", "class", "is", "a", "sub", "-", "class", "of", "a", "super", "-", "class", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java#L111-L128
train
GeneralElectric/snowizard
snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java
IdWorker.getId
public long getId(final String agent) throws InvalidUserAgentError, InvalidSystemClock { if (!isValidUserAgent(agent)) { exceptionsCounter.inc(); throw new InvalidUserAgentError(); } final long id = nextId(); genCounter(agent); return id; }
java
public long getId(final String agent) throws InvalidUserAgentError, InvalidSystemClock { if (!isValidUserAgent(agent)) { exceptionsCounter.inc(); throw new InvalidUserAgentError(); } final long id = nextId(); genCounter(agent); return id; }
[ "public", "long", "getId", "(", "final", "String", "agent", ")", "throws", "InvalidUserAgentError", ",", "InvalidSystemClock", "{", "if", "(", "!", "isValidUserAgent", "(", "agent", ")", ")", "{", "exceptionsCounter", ".", "inc", "(", ")", ";", "throw", "new...
Get the next ID for a given user-agent @param agent User Agent @return Generated ID @throws InvalidUserAgentError When the user agent is invalid @throws InvalidSystemClock When the system clock is moving backward
[ "Get", "the", "next", "ID", "for", "a", "given", "user", "-", "agent" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java#L192-L203
train
GeneralElectric/snowizard
snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java
IdWorker.nextId
public synchronized long nextId() throws InvalidSystemClock { long timestamp = timeGen(); long curSequence = 0L; final long prevTimestamp = lastTimestamp.get(); if (timestamp < prevTimestamp) { exceptionsCounter.inc(); LOGGER.error( "clock is moving backwards. Rejecting requests until {}", prevTimestamp); throw new InvalidSystemClock( String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", (prevTimestamp - timestamp))); } if (prevTimestamp == timestamp) { curSequence = sequence.incrementAndGet() & SEQUENCE_MASK; if (curSequence == 0) { timestamp = tilNextMillis(prevTimestamp); } } else { curSequence = 0L; sequence.set(0L); } lastTimestamp.set(timestamp); final long id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (datacenterId << DATACENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | curSequence; LOGGER.trace( "prevTimestamp = {}, timestamp = {}, sequence = {}, id = {}", prevTimestamp, timestamp, sequence, id); return id; }
java
public synchronized long nextId() throws InvalidSystemClock { long timestamp = timeGen(); long curSequence = 0L; final long prevTimestamp = lastTimestamp.get(); if (timestamp < prevTimestamp) { exceptionsCounter.inc(); LOGGER.error( "clock is moving backwards. Rejecting requests until {}", prevTimestamp); throw new InvalidSystemClock( String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", (prevTimestamp - timestamp))); } if (prevTimestamp == timestamp) { curSequence = sequence.incrementAndGet() & SEQUENCE_MASK; if (curSequence == 0) { timestamp = tilNextMillis(prevTimestamp); } } else { curSequence = 0L; sequence.set(0L); } lastTimestamp.set(timestamp); final long id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (datacenterId << DATACENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | curSequence; LOGGER.trace( "prevTimestamp = {}, timestamp = {}, sequence = {}, id = {}", prevTimestamp, timestamp, sequence, id); return id; }
[ "public", "synchronized", "long", "nextId", "(", ")", "throws", "InvalidSystemClock", "{", "long", "timestamp", "=", "timeGen", "(", ")", ";", "long", "curSequence", "=", "0L", ";", "final", "long", "prevTimestamp", "=", "lastTimestamp", ".", "get", "(", ")"...
Get the next ID @return Next ID @throws InvalidSystemClock When the clock is moving backward
[ "Get", "the", "next", "ID" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java#L258-L295
train
GeneralElectric/snowizard
snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java
IdWorker.isValidUserAgent
public boolean isValidUserAgent(final String agent) { if (!validateUserAgent) { return true; } final Matcher matcher = AGENT_PATTERN.matcher(agent); return matcher.matches(); }
java
public boolean isValidUserAgent(final String agent) { if (!validateUserAgent) { return true; } final Matcher matcher = AGENT_PATTERN.matcher(agent); return matcher.matches(); }
[ "public", "boolean", "isValidUserAgent", "(", "final", "String", "agent", ")", "{", "if", "(", "!", "validateUserAgent", ")", "{", "return", "true", ";", "}", "final", "Matcher", "matcher", "=", "AGENT_PATTERN", ".", "matcher", "(", "agent", ")", ";", "ret...
Check whether the user agent is valid @param agent User-Agent @return True if the user agent is valid
[ "Check", "whether", "the", "user", "agent", "is", "valid" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java#L328-L334
train
GeneralElectric/snowizard
snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java
IdWorker.genCounter
protected void genCounter(final String agent) { idsCounter.inc(); if (!agentCounters.containsKey(agent)) { agentCounters.put(agent, registry.counter(MetricRegistry.name( IdWorker.class, "ids_generated_" + agent))); } agentCounters.get(agent).inc(); }
java
protected void genCounter(final String agent) { idsCounter.inc(); if (!agentCounters.containsKey(agent)) { agentCounters.put(agent, registry.counter(MetricRegistry.name( IdWorker.class, "ids_generated_" + agent))); } agentCounters.get(agent).inc(); }
[ "protected", "void", "genCounter", "(", "final", "String", "agent", ")", "{", "idsCounter", ".", "inc", "(", ")", ";", "if", "(", "!", "agentCounters", ".", "containsKey", "(", "agent", ")", ")", "{", "agentCounters", ".", "put", "(", "agent", ",", "re...
Update the counters for a given user agent @param agent User-Agent
[ "Update", "the", "counters", "for", "a", "given", "user", "agent" ]
307fdf17892275a56bb666aa1f577ca7cab327c6
https://github.com/GeneralElectric/snowizard/blob/307fdf17892275a56bb666aa1f577ca7cab327c6/snowizard-core/src/main/java/com/ge/snowizard/core/IdWorker.java#L342-L349
train
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/authentication/AuthorizationApi.java
AuthorizationApi.createQueryParamsList
public static Map<String, String> createQueryParamsList(String clientId, String redirectUri, String responseType, String hideTenant, String scope) { if (clientId == null) { throw new IllegalArgumentException("Missing the required parameter 'client_id'"); } if (redirectUri == null) { throw new IllegalArgumentException("Missing the required parameter 'redirect_uri'"); } if (responseType == null) { throw new IllegalArgumentException("Missing the required parameter 'response_type'"); } Map<String, String> queryParams = new HashMap<>(); queryParams.put("client_id", clientId); queryParams.put("redirect_uri", redirectUri); queryParams.put("response_type", responseType); if (hideTenant != null) queryParams.put("hideTenant", hideTenant); if (scope != null) queryParams.put("scope", scope); return queryParams; }
java
public static Map<String, String> createQueryParamsList(String clientId, String redirectUri, String responseType, String hideTenant, String scope) { if (clientId == null) { throw new IllegalArgumentException("Missing the required parameter 'client_id'"); } if (redirectUri == null) { throw new IllegalArgumentException("Missing the required parameter 'redirect_uri'"); } if (responseType == null) { throw new IllegalArgumentException("Missing the required parameter 'response_type'"); } Map<String, String> queryParams = new HashMap<>(); queryParams.put("client_id", clientId); queryParams.put("redirect_uri", redirectUri); queryParams.put("response_type", responseType); if (hideTenant != null) queryParams.put("hideTenant", hideTenant); if (scope != null) queryParams.put("scope", scope); return queryParams; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "createQueryParamsList", "(", "String", "clientId", ",", "String", "redirectUri", ",", "String", "responseType", ",", "String", "hideTenant", ",", "String", "scope", ")", "{", "if", "(", "clientId",...
Build query parameters @param clientId The ID of the application or service that is registered as the client. You&#39;ll need to get this value from your PureEngage Cloud representative. @param redirectUri The URI that you want users to be redirected to after entering valid credentials during an Implicit or Authorization Code grant. The Authentication API includes this as part of the URI it returns in the &#39;Location&#39; header. @param responseType The response type to let the Authentication API know which grant flow you&#39;re using. Possible values are &#x60;code&#x60; for Authorization Code Grant or &#x60;token&#x60; for Implicit Grant. For more information about this parameter, see [Response Type](https://tools.ietf.org/html/rfc6749#section-3.1.1). @param hideTenant Hide the **tenant** field in the UI for Authorization Code Grant. (optional, default to false) @param scope The scope of the access request. The Authentication API supports only the &#x60;*&#x60; value. (optional) @throws IllegalArgumentException if required query parameters are missed
[ "Build", "query", "parameters" ]
eb0d58343ee42ebd3c037163c1137f611dfcbb3a
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/authentication/AuthorizationApi.java#L28-L47
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/EvaluationContext.java
EvaluationContext.coerceToSupportedType
protected static Object coerceToSupportedType(Object value) { if (value == null) { return ""; // # empty string rather than null } else if (value instanceof Map) { Map valueAsMap = ((Map) value); if (valueAsMap.containsKey("*")) { return valueAsMap.get("*"); } else if (valueAsMap.containsKey("__default__")) { return valueAsMap.get("__default__"); } else { return s_gson.toJson(valueAsMap); } } else if (value instanceof Float) { return new BigDecimal((float) value); } else if (value instanceof Double) { return new BigDecimal((double) value); } else if (value instanceof Long) { return new BigDecimal((long) value); } else { return value; } }
java
protected static Object coerceToSupportedType(Object value) { if (value == null) { return ""; // # empty string rather than null } else if (value instanceof Map) { Map valueAsMap = ((Map) value); if (valueAsMap.containsKey("*")) { return valueAsMap.get("*"); } else if (valueAsMap.containsKey("__default__")) { return valueAsMap.get("__default__"); } else { return s_gson.toJson(valueAsMap); } } else if (value instanceof Float) { return new BigDecimal((float) value); } else if (value instanceof Double) { return new BigDecimal((double) value); } else if (value instanceof Long) { return new BigDecimal((long) value); } else { return value; } }
[ "protected", "static", "Object", "coerceToSupportedType", "(", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "\"\"", ";", "// # empty string rather than null", "}", "else", "if", "(", "value", "instanceof", "Map", ")", "{",...
Since we let users populate the context with whatever they want, this ensures the resolved value is something which the expression engine understands. @param value the resolved value @return the value converted to a supported data type
[ "Since", "we", "let", "users", "populate", "the", "context", "with", "whatever", "they", "want", "this", "ensures", "the", "resolved", "value", "is", "something", "which", "the", "expression", "engine", "understands", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/EvaluationContext.java#L139-L160
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java
ThriftUtils.toBytes
public static byte[] toBytes(TBase<?, ?> record) throws TException { if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
java
public static byte[] toBytes(TBase<?, ?> record) throws TException { if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "TBase", "<", "?", ",", "?", ">", "record", ")", "throws", "TException", "{", "if", "(", "record", "==", "null", ")", "{", "return", "null", ";", "}", "ByteArrayOutputStream", "baos", "=", "new", ...
Serializes a thrift object to byte array. @param record @return @throws TException
[ "Serializes", "a", "thrift", "object", "to", "byte", "array", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java#L45-L55
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java
ThriftUtils.fromBytes
public static <T extends TBase<?, ?>> T fromBytes(byte[] data, Class<T> clazz) throws TException { if (data == null) { return null; } ByteArrayInputStream bais = new ByteArrayInputStream(data); try { TTransport transport = new TIOStreamTransport(bais, null); TProtocol iProtocol = protocolFactory.getProtocol(transport); T record = clazz.newInstance(); record.read(iProtocol); // bais.close(); return record; } catch (InstantiationException | IllegalAccessException e) { throw new TException(e); } }
java
public static <T extends TBase<?, ?>> T fromBytes(byte[] data, Class<T> clazz) throws TException { if (data == null) { return null; } ByteArrayInputStream bais = new ByteArrayInputStream(data); try { TTransport transport = new TIOStreamTransport(bais, null); TProtocol iProtocol = protocolFactory.getProtocol(transport); T record = clazz.newInstance(); record.read(iProtocol); // bais.close(); return record; } catch (InstantiationException | IllegalAccessException e) { throw new TException(e); } }
[ "public", "static", "<", "T", "extends", "TBase", "<", "?", ",", "?", ">", ">", "T", "fromBytes", "(", "byte", "[", "]", "data", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "TException", "{", "if", "(", "data", "==", "null", ")", "{", ...
Deserializes a thrift object from byte array. @param data @param clazz @return @throws TException
[ "Deserializes", "a", "thrift", "object", "from", "byte", "array", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java#L65-L81
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbUtils.java
RocksDbUtils.closeRocksObjects
public static void closeRocksObjects(RocksObject... rocksObjList) { if (rocksObjList != null) { for (RocksObject obj : rocksObjList) { try { if (obj != null) { obj.close(); } } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } } }
java
public static void closeRocksObjects(RocksObject... rocksObjList) { if (rocksObjList != null) { for (RocksObject obj : rocksObjList) { try { if (obj != null) { obj.close(); } } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } } }
[ "public", "static", "void", "closeRocksObjects", "(", "RocksObject", "...", "rocksObjList", ")", "{", "if", "(", "rocksObjList", "!=", "null", ")", "{", "for", "(", "RocksObject", "obj", ":", "rocksObjList", ")", "{", "try", "{", "if", "(", "obj", "!=", ...
Silently close RocksDb objects. @param rocksObjList
[ "Silently", "close", "RocksDb", "objects", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbUtils.java#L160-L172
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbUtils.java
RocksDbUtils.getColumnFamilyList
public static String[] getColumnFamilyList(String path) throws RocksDBException { List<byte[]> cfList = RocksDB.listColumnFamilies(new Options(), path); if (cfList == null || cfList.size() == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List<String> result = new ArrayList<>(cfList.size()); for (byte[] cf : cfList) { result.add(new String(cf, StandardCharsets.UTF_8)); } return result.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
java
public static String[] getColumnFamilyList(String path) throws RocksDBException { List<byte[]> cfList = RocksDB.listColumnFamilies(new Options(), path); if (cfList == null || cfList.size() == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List<String> result = new ArrayList<>(cfList.size()); for (byte[] cf : cfList) { result.add(new String(cf, StandardCharsets.UTF_8)); } return result.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
[ "public", "static", "String", "[", "]", "getColumnFamilyList", "(", "String", "path", ")", "throws", "RocksDBException", "{", "List", "<", "byte", "[", "]", ">", "cfList", "=", "RocksDB", ".", "listColumnFamilies", "(", "new", "Options", "(", ")", ",", "pa...
Gets all available column family names from a RocksDb data directory. @param path @return @throws RocksDBException
[ "Gets", "all", "available", "column", "family", "names", "from", "a", "RocksDb", "data", "directory", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbUtils.java#L181-L191
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ValueUtils.java
ValueUtils.convertValue
@SuppressWarnings("unchecked") public static <T> T convertValue(Object target, Class<T> clazz) { if (clazz == null) { throw new NullPointerException("Class parameter is null!"); } if (target == null) { return null; } if (target instanceof JsonNode) { return convertValue((JsonNode) target, clazz); } if (Number.class.isAssignableFrom(clazz) || byte.class == clazz || short.class == clazz || int.class == clazz || long.class == clazz || float.class == clazz || double.class == clazz) { return convertNumber(target, clazz); } if (clazz == Boolean.class || clazz == boolean.class) { return (T) convertBoolean(target); } if (clazz == Character.class || clazz == char.class) { return (T) convertChar(target); } if (Date.class.isAssignableFrom(clazz)) { return (T) convertDate(target); } if (Object[].class.isAssignableFrom(clazz) || List.class.isAssignableFrom(clazz)) { return (T) convertArrayOrList(target); } if (clazz.isAssignableFrom(target.getClass())) { return (T) target; } if (clazz == String.class) { return (T) target.toString(); } throw new IllegalArgumentException( "Cannot convert an object of type [" + target.getClass() + "] to [" + clazz + "]!"); }
java
@SuppressWarnings("unchecked") public static <T> T convertValue(Object target, Class<T> clazz) { if (clazz == null) { throw new NullPointerException("Class parameter is null!"); } if (target == null) { return null; } if (target instanceof JsonNode) { return convertValue((JsonNode) target, clazz); } if (Number.class.isAssignableFrom(clazz) || byte.class == clazz || short.class == clazz || int.class == clazz || long.class == clazz || float.class == clazz || double.class == clazz) { return convertNumber(target, clazz); } if (clazz == Boolean.class || clazz == boolean.class) { return (T) convertBoolean(target); } if (clazz == Character.class || clazz == char.class) { return (T) convertChar(target); } if (Date.class.isAssignableFrom(clazz)) { return (T) convertDate(target); } if (Object[].class.isAssignableFrom(clazz) || List.class.isAssignableFrom(clazz)) { return (T) convertArrayOrList(target); } if (clazz.isAssignableFrom(target.getClass())) { return (T) target; } if (clazz == String.class) { return (T) target.toString(); } throw new IllegalArgumentException( "Cannot convert an object of type [" + target.getClass() + "] to [" + clazz + "]!"); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "convertValue", "(", "Object", "target", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "clazz", "==", "null", ")", "{", "throw", "new", "NullPointe...
Convert a target object to a specified value type. @param target @param clazz @return
[ "Convert", "a", "target", "object", "to", "a", "specified", "value", "type", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ValueUtils.java#L212-L248
train
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
TypesafeConfigUtils.loadConfig
public static Config loadConfig(File configFile, boolean useSystemEnvironment) { return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configFile); }
java
public static Config loadConfig(File configFile, boolean useSystemEnvironment) { return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configFile); }
[ "public", "static", "Config", "loadConfig", "(", "File", "configFile", ",", "boolean", "useSystemEnvironment", ")", "{", "return", "loadConfig", "(", "ConfigParseOptions", ".", "defaults", "(", ")", ",", "ConfigResolveOptions", ".", "defaults", "(", ")", ".", "s...
Load, Parse & Resolve configurations from a file, with default parse & resolve options. @param configFile @param useSystemEnvironment {@code true} to resolve substitutions falling back to environment variables @return
[ "Load", "Parse", "&", "Resolve", "configurations", "from", "a", "file", "with", "default", "parse", "&", "resolve", "options", "." ]
734f0e77321d41eeca78a557be9884df9874e46e
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L56-L60
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/dates/DateParser.java
DateParser.parse
protected Temporal parse(String text, Mode mode) { if (StringUtils.isBlank(text)) { return null; } // try to parse the date as an ISO8601 date if (text.length() >= 16) { try { return OffsetDateTime.parse(text).toZonedDateTime(); } catch(Exception e) {} } // split the text into numerical and text tokens Pattern pattern = Pattern.compile("([0-9]+|\\p{L}+)"); Matcher matcher = pattern.matcher(text); List<String> tokens = new ArrayList<>(); while (matcher.find()) { tokens.add(matcher.group(0)); } // get the possibilities for each token List<Map<Component, Integer>> tokenPossibilities = new ArrayList<>(); for (String token : tokens) { Map<Component, Integer> possibilities = getTokenPossibilities(token, mode); if (possibilities.size() > 0) { tokenPossibilities.add(possibilities); } } // see what valid sequences we can make List<Component[]> sequences = getPossibleSequences(mode, tokenPossibilities.size(), m_dateStyle); outer: for (Component[] sequence : sequences) { Map<Component, Integer> match = new LinkedHashMap<>(); for (int c = 0; c < sequence.length; c++) { Component component = sequence[c]; Integer value = tokenPossibilities.get(c).get(component); match.put(component, value); if (value == null) { continue outer; } } // try to make a valid result from this and return if successful Temporal obj = makeResult(match, m_now, m_timezone); if (obj != null) { return obj; } } return null; }
java
protected Temporal parse(String text, Mode mode) { if (StringUtils.isBlank(text)) { return null; } // try to parse the date as an ISO8601 date if (text.length() >= 16) { try { return OffsetDateTime.parse(text).toZonedDateTime(); } catch(Exception e) {} } // split the text into numerical and text tokens Pattern pattern = Pattern.compile("([0-9]+|\\p{L}+)"); Matcher matcher = pattern.matcher(text); List<String> tokens = new ArrayList<>(); while (matcher.find()) { tokens.add(matcher.group(0)); } // get the possibilities for each token List<Map<Component, Integer>> tokenPossibilities = new ArrayList<>(); for (String token : tokens) { Map<Component, Integer> possibilities = getTokenPossibilities(token, mode); if (possibilities.size() > 0) { tokenPossibilities.add(possibilities); } } // see what valid sequences we can make List<Component[]> sequences = getPossibleSequences(mode, tokenPossibilities.size(), m_dateStyle); outer: for (Component[] sequence : sequences) { Map<Component, Integer> match = new LinkedHashMap<>(); for (int c = 0; c < sequence.length; c++) { Component component = sequence[c]; Integer value = tokenPossibilities.get(c).get(component); match.put(component, value); if (value == null) { continue outer; } } // try to make a valid result from this and return if successful Temporal obj = makeResult(match, m_now, m_timezone); if (obj != null) { return obj; } } return null; }
[ "protected", "Temporal", "parse", "(", "String", "text", ",", "Mode", "mode", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "text", ")", ")", "{", "return", "null", ";", "}", "// try to parse the date as an ISO8601 date", "if", "(", "text", ".", ...
Returns a date, datetime or time depending on what information is available
[ "Returns", "a", "date", "datetime", "or", "time", "depending", "on", "what", "information", "is", "available" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/dates/DateParser.java#L121-L175
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/dates/DateParser.java
DateParser.getPossibleSequences
protected static List<Component[]> getPossibleSequences(Mode mode, int length, DateStyle dateStyle) { List<Component[]> sequences = new ArrayList<>(); Component[][] dateSequences = dateStyle.equals(DateStyle.DAY_FIRST) ? DATE_SEQUENCES_DAY_FIRST : DATE_SEQUENCES_MONTH_FIRST; if (mode == Mode.DATE || mode == Mode.AUTO) { for (Component[] seq : dateSequences) { if (seq.length == length) { sequences.add(seq); } } } else if (mode == Mode.TIME) { for (Component[] seq : TIME_SEQUENCES) { if (seq.length == length) { sequences.add(seq); } } } if (mode == Mode.DATETIME || mode == Mode.AUTO) { for (Component[] dateSeq : dateSequences) { for (Component[] timeSeq : TIME_SEQUENCES) { if (dateSeq.length + timeSeq.length == length) { sequences.add(ArrayUtils.addAll(dateSeq, timeSeq)); } } } } return sequences; }
java
protected static List<Component[]> getPossibleSequences(Mode mode, int length, DateStyle dateStyle) { List<Component[]> sequences = new ArrayList<>(); Component[][] dateSequences = dateStyle.equals(DateStyle.DAY_FIRST) ? DATE_SEQUENCES_DAY_FIRST : DATE_SEQUENCES_MONTH_FIRST; if (mode == Mode.DATE || mode == Mode.AUTO) { for (Component[] seq : dateSequences) { if (seq.length == length) { sequences.add(seq); } } } else if (mode == Mode.TIME) { for (Component[] seq : TIME_SEQUENCES) { if (seq.length == length) { sequences.add(seq); } } } if (mode == Mode.DATETIME || mode == Mode.AUTO) { for (Component[] dateSeq : dateSequences) { for (Component[] timeSeq : TIME_SEQUENCES) { if (dateSeq.length + timeSeq.length == length) { sequences.add(ArrayUtils.addAll(dateSeq, timeSeq)); } } } } return sequences; }
[ "protected", "static", "List", "<", "Component", "[", "]", ">", "getPossibleSequences", "(", "Mode", "mode", ",", "int", "length", ",", "DateStyle", "dateStyle", ")", "{", "List", "<", "Component", "[", "]", ">", "sequences", "=", "new", "ArrayList", "<>",...
Gets possible component sequences in the given mode @param mode the mode @param length the length (only returns sequences of this length) @param dateStyle whether dates are usually entered day first or month first @return the list of sequences
[ "Gets", "possible", "component", "sequences", "in", "the", "given", "mode" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/dates/DateParser.java#L184-L214
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/dates/DateParser.java
DateParser.makeResult
protected static Temporal makeResult(Map<Component, Integer> values, LocalDate now, ZoneId timezone) { LocalDate date = null; LocalTime time = null; if (values.containsKey(Component.MONTH)) { int year = yearFrom2Digits(ExpressionUtils.getOrDefault(values, Component.YEAR, now.getYear()), now.getYear()); int month = values.get(Component.MONTH); int day = ExpressionUtils.getOrDefault(values, Component.DAY, 1); try { date = LocalDate.of(year, month, day); } catch (DateTimeException ex) { return null; // not a valid date } } if ((values.containsKey(Component.HOUR) && values.containsKey(Component.MINUTE)) || values.containsKey(Component.HOUR_AND_MINUTE)) { int hour, minute, second, nano; if (values.containsKey(Component.HOUR_AND_MINUTE)) { int combined = values.get(Component.HOUR_AND_MINUTE); hour = combined / 100; minute = combined - (hour * 100); second = 0; nano = 0; } else { hour = values.get(Component.HOUR); minute = values.get(Component.MINUTE); second = ExpressionUtils.getOrDefault(values, Component.SECOND, 0); nano = ExpressionUtils.getOrDefault(values, Component.NANO, 0); if (hour < 12 && ExpressionUtils.getOrDefault(values, Component.AM_PM, AM) == PM) { hour += 12; } else if (hour == 12 && ExpressionUtils.getOrDefault(values, Component.AM_PM, PM) == AM) { hour -= 12; } } try { time = LocalTime.of(hour, minute, second, nano); } catch (DateTimeException ex) { return null; // not a valid time } } if (values.containsKey(Component.OFFSET)) { timezone = ZoneOffset.ofTotalSeconds(values.get(Component.OFFSET)); } if (date != null && time != null) { return ZonedDateTime.of(date, time, timezone); } else if (date != null) { return date; } else if (time != null) { return ZonedDateTime.of(now, time, timezone).toOffsetDateTime().toOffsetTime(); } else { return null; } }
java
protected static Temporal makeResult(Map<Component, Integer> values, LocalDate now, ZoneId timezone) { LocalDate date = null; LocalTime time = null; if (values.containsKey(Component.MONTH)) { int year = yearFrom2Digits(ExpressionUtils.getOrDefault(values, Component.YEAR, now.getYear()), now.getYear()); int month = values.get(Component.MONTH); int day = ExpressionUtils.getOrDefault(values, Component.DAY, 1); try { date = LocalDate.of(year, month, day); } catch (DateTimeException ex) { return null; // not a valid date } } if ((values.containsKey(Component.HOUR) && values.containsKey(Component.MINUTE)) || values.containsKey(Component.HOUR_AND_MINUTE)) { int hour, minute, second, nano; if (values.containsKey(Component.HOUR_AND_MINUTE)) { int combined = values.get(Component.HOUR_AND_MINUTE); hour = combined / 100; minute = combined - (hour * 100); second = 0; nano = 0; } else { hour = values.get(Component.HOUR); minute = values.get(Component.MINUTE); second = ExpressionUtils.getOrDefault(values, Component.SECOND, 0); nano = ExpressionUtils.getOrDefault(values, Component.NANO, 0); if (hour < 12 && ExpressionUtils.getOrDefault(values, Component.AM_PM, AM) == PM) { hour += 12; } else if (hour == 12 && ExpressionUtils.getOrDefault(values, Component.AM_PM, PM) == AM) { hour -= 12; } } try { time = LocalTime.of(hour, minute, second, nano); } catch (DateTimeException ex) { return null; // not a valid time } } if (values.containsKey(Component.OFFSET)) { timezone = ZoneOffset.ofTotalSeconds(values.get(Component.OFFSET)); } if (date != null && time != null) { return ZonedDateTime.of(date, time, timezone); } else if (date != null) { return date; } else if (time != null) { return ZonedDateTime.of(now, time, timezone).toOffsetDateTime().toOffsetTime(); } else { return null; } }
[ "protected", "static", "Temporal", "makeResult", "(", "Map", "<", "Component", ",", "Integer", ">", "values", ",", "LocalDate", "now", ",", "ZoneId", "timezone", ")", "{", "LocalDate", "date", "=", "null", ";", "LocalTime", "time", "=", "null", ";", "if", ...
Makes a date or datetime or time object from a map of component values @param values the component values @param timezone the current timezone @return the date, datetime, time or null if values are invalid
[ "Makes", "a", "date", "or", "datetime", "or", "time", "object", "from", "a", "map", "of", "component", "values" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/dates/DateParser.java#L303-L362
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/dates/DateParser.java
DateParser.yearFrom2Digits
protected static int yearFrom2Digits(int shortYear, int currentYear) { if (shortYear < 100) { shortYear += currentYear - (currentYear % 100); if (Math.abs(shortYear - currentYear) >= 50) { if (shortYear < currentYear) { return shortYear + 100; } else { return shortYear - 100; } } } return shortYear; }
java
protected static int yearFrom2Digits(int shortYear, int currentYear) { if (shortYear < 100) { shortYear += currentYear - (currentYear % 100); if (Math.abs(shortYear - currentYear) >= 50) { if (shortYear < currentYear) { return shortYear + 100; } else { return shortYear - 100; } } } return shortYear; }
[ "protected", "static", "int", "yearFrom2Digits", "(", "int", "shortYear", ",", "int", "currentYear", ")", "{", "if", "(", "shortYear", "<", "100", ")", "{", "shortYear", "+=", "currentYear", "-", "(", "currentYear", "%", "100", ")", ";", "if", "(", "Math...
Converts a relative 2-digit year to an absolute 4-digit year @param shortYear the relative year @return the absolute year
[ "Converts", "a", "relative", "2", "-", "digit", "year", "to", "an", "absolute", "4", "-", "digit", "year" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/dates/DateParser.java#L369-L381
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/dates/DateParser.java
DateParser.loadMonthAliases
protected static Map<String, Integer> loadMonthAliases(String file) throws IOException { InputStream in = DateParser.class.getClassLoader().getResourceAsStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Map<String, Integer> map = new HashMap<>(); String line; int month = 1; while ((line = reader.readLine()) != null) { for (String alias : line.split(",")) { map.put(alias, month); } month++; } reader.close(); return map; }
java
protected static Map<String, Integer> loadMonthAliases(String file) throws IOException { InputStream in = DateParser.class.getClassLoader().getResourceAsStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Map<String, Integer> map = new HashMap<>(); String line; int month = 1; while ((line = reader.readLine()) != null) { for (String alias : line.split(",")) { map.put(alias, month); } month++; } reader.close(); return map; }
[ "protected", "static", "Map", "<", "String", ",", "Integer", ">", "loadMonthAliases", "(", "String", "file", ")", "throws", "IOException", "{", "InputStream", "in", "=", "DateParser", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "...
Loads month aliases from the given resource file
[ "Loads", "month", "aliases", "from", "the", "given", "resource", "file" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/dates/DateParser.java#L386-L400
train
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/authentication/AuthenticationApi.java
AuthenticationApi.createFormParamSignIn
public static Map<String, Object> createFormParamSignIn(String username, String password, Boolean isSaml) { if (username == null) { throw new IllegalArgumentException("Missing the required parameter 'username'"); } if (password == null) { throw new IllegalArgumentException("Missing the required parameter 'password'"); } Map<String, Object> formParams = new HashMap<>(); formParams.put("username", username); formParams.put("password", password); if (isSaml != null) { formParams.put("saml", isSaml); } return formParams; }
java
public static Map<String, Object> createFormParamSignIn(String username, String password, Boolean isSaml) { if (username == null) { throw new IllegalArgumentException("Missing the required parameter 'username'"); } if (password == null) { throw new IllegalArgumentException("Missing the required parameter 'password'"); } Map<String, Object> formParams = new HashMap<>(); formParams.put("username", username); formParams.put("password", password); if (isSaml != null) { formParams.put("saml", isSaml); } return formParams; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "createFormParamSignIn", "(", "String", "username", ",", "String", "password", ",", "Boolean", "isSaml", ")", "{", "if", "(", "username", "==", "null", ")", "{", "throw", "new", "IllegalArgumentEx...
Build form parameters to sign in @param username The agent&#39;s username, formatted as &#39;tenant\\username&#39;. (required) @param password The agent&#39;s password. (required) @param isSaml Specifies whether to login using [Security Assertion Markup Language](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) (SAML). (optional) @return a map of form parameters @throws IllegalArgumentException if required form parameter is missed
[ "Build", "form", "parameters", "to", "sign", "in" ]
eb0d58343ee42ebd3c037163c1137f611dfcbb3a
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/authentication/AuthenticationApi.java#L204-L218
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java
Conversions.toInteger
public static int toInteger(Object value, EvaluationContext ctx) { if (value instanceof Boolean) { return ((Boolean) value) ? 1 : 0; } else if (value instanceof Integer) { return (Integer) value; } else if (value instanceof BigDecimal) { try { return ((BigDecimal) value).setScale(0, RoundingMode.HALF_UP).intValueExact(); } catch (ArithmeticException ex) {} } else if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException e) {} } throw new EvaluationError("Can't convert '" + value + "' to an integer"); }
java
public static int toInteger(Object value, EvaluationContext ctx) { if (value instanceof Boolean) { return ((Boolean) value) ? 1 : 0; } else if (value instanceof Integer) { return (Integer) value; } else if (value instanceof BigDecimal) { try { return ((BigDecimal) value).setScale(0, RoundingMode.HALF_UP).intValueExact(); } catch (ArithmeticException ex) {} } else if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException e) {} } throw new EvaluationError("Can't convert '" + value + "' to an integer"); }
[ "public", "static", "int", "toInteger", "(", "Object", "value", ",", "EvaluationContext", "ctx", ")", "{", "if", "(", "value", "instanceof", "Boolean", ")", "{", "return", "(", "(", "Boolean", ")", "value", ")", "?", "1", ":", "0", ";", "}", "else", ...
Tries conversion of any value to an integer
[ "Tries", "conversion", "of", "any", "value", "to", "an", "integer" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java#L54-L75
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java
Conversions.toDecimal
public static BigDecimal toDecimal(Object value, EvaluationContext ctx) { if (value instanceof Boolean) { return ((Boolean) value) ? BigDecimal.ONE : BigDecimal.ZERO; } else if (value instanceof Integer) { return new BigDecimal((Integer) value); } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof String) { try { return new BigDecimal((String) value); } catch (NumberFormatException e) {} } throw new EvaluationError("Can't convert '" + value + "' to a decimal"); }
java
public static BigDecimal toDecimal(Object value, EvaluationContext ctx) { if (value instanceof Boolean) { return ((Boolean) value) ? BigDecimal.ONE : BigDecimal.ZERO; } else if (value instanceof Integer) { return new BigDecimal((Integer) value); } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof String) { try { return new BigDecimal((String) value); } catch (NumberFormatException e) {} } throw new EvaluationError("Can't convert '" + value + "' to a decimal"); }
[ "public", "static", "BigDecimal", "toDecimal", "(", "Object", "value", ",", "EvaluationContext", "ctx", ")", "{", "if", "(", "value", "instanceof", "Boolean", ")", "{", "return", "(", "(", "Boolean", ")", "value", ")", "?", "BigDecimal", ".", "ONE", ":", ...
Tries conversion of any value to a decimal
[ "Tries", "conversion", "of", "any", "value", "to", "a", "decimal" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java#L80-L98
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java
Conversions.toDateTime
public static ZonedDateTime toDateTime(Object value, EvaluationContext ctx) { if (value instanceof String) { Temporal temporal = ctx.getDateParser().auto((String) value); if (temporal != null) { return toDateTime(temporal, ctx); } } else if (value instanceof LocalDate) { return ((LocalDate) value).atStartOfDay(ctx.getTimezone()); } else if (value instanceof ZonedDateTime) { return ((ZonedDateTime) value).withZoneSameInstant(ctx.getTimezone()); } throw new EvaluationError("Can't convert '" + value + "' to a datetime"); }
java
public static ZonedDateTime toDateTime(Object value, EvaluationContext ctx) { if (value instanceof String) { Temporal temporal = ctx.getDateParser().auto((String) value); if (temporal != null) { return toDateTime(temporal, ctx); } } else if (value instanceof LocalDate) { return ((LocalDate) value).atStartOfDay(ctx.getTimezone()); } else if (value instanceof ZonedDateTime) { return ((ZonedDateTime) value).withZoneSameInstant(ctx.getTimezone()); } throw new EvaluationError("Can't convert '" + value + "' to a datetime"); }
[ "public", "static", "ZonedDateTime", "toDateTime", "(", "Object", "value", ",", "EvaluationContext", "ctx", ")", "{", "if", "(", "value", "instanceof", "String", ")", "{", "Temporal", "temporal", "=", "ctx", ".", "getDateParser", "(", ")", ".", "auto", "(", ...
Tries conversion of any value to a date
[ "Tries", "conversion", "of", "any", "value", "to", "a", "date" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java#L155-L170
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java
Conversions.toTime
public static OffsetTime toTime(Object value, EvaluationContext ctx) { if (value instanceof String) { OffsetTime time = ctx.getDateParser().time((String) value); if (time != null) { return time; } } else if (value instanceof OffsetTime) { return (OffsetTime) value; } else if (value instanceof ZonedDateTime) { return ((ZonedDateTime) value).toOffsetDateTime().toOffsetTime(); } throw new EvaluationError("Can't convert '" + value + "' to a time"); }
java
public static OffsetTime toTime(Object value, EvaluationContext ctx) { if (value instanceof String) { OffsetTime time = ctx.getDateParser().time((String) value); if (time != null) { return time; } } else if (value instanceof OffsetTime) { return (OffsetTime) value; } else if (value instanceof ZonedDateTime) { return ((ZonedDateTime) value).toOffsetDateTime().toOffsetTime(); } throw new EvaluationError("Can't convert '" + value + "' to a time"); }
[ "public", "static", "OffsetTime", "toTime", "(", "Object", "value", ",", "EvaluationContext", "ctx", ")", "{", "if", "(", "value", "instanceof", "String", ")", "{", "OffsetTime", "time", "=", "ctx", ".", "getDateParser", "(", ")", ".", "time", "(", "(", ...
Tries conversion of any value to a time
[ "Tries", "conversion", "of", "any", "value", "to", "a", "time" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java#L195-L210
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java
Conversions.toSame
public static Pair<Object, Object> toSame(Object value1, Object value2, EvaluationContext ctx) { if (value1.getClass().equals(value2.getClass())) { return new ImmutablePair<>(value1, value2); } try { // try converting to two decimals return new ImmutablePair<Object, Object>(toDecimal(value1, ctx), toDecimal(value2, ctx)); } catch (EvaluationError ex) {} try { // try converting to two dates Temporal d1 = toDateOrDateTime(value1, ctx); Temporal d2 = toDateOrDateTime(value2, ctx); if (!value1.getClass().equals(value2.getClass())) { d1 = toDateTime(d1, ctx); d2 = toDateTime(d2, ctx); } return new ImmutablePair<Object, Object>(d1, d2); } catch (EvaluationError ex) {} // try converting to two strings return new ImmutablePair<Object, Object>(toString(value1, ctx), toString(value2, ctx)); }
java
public static Pair<Object, Object> toSame(Object value1, Object value2, EvaluationContext ctx) { if (value1.getClass().equals(value2.getClass())) { return new ImmutablePair<>(value1, value2); } try { // try converting to two decimals return new ImmutablePair<Object, Object>(toDecimal(value1, ctx), toDecimal(value2, ctx)); } catch (EvaluationError ex) {} try { // try converting to two dates Temporal d1 = toDateOrDateTime(value1, ctx); Temporal d2 = toDateOrDateTime(value2, ctx); if (!value1.getClass().equals(value2.getClass())) { d1 = toDateTime(d1, ctx); d2 = toDateTime(d2, ctx); } return new ImmutablePair<Object, Object>(d1, d2); } catch (EvaluationError ex) {} // try converting to two strings return new ImmutablePair<Object, Object>(toString(value1, ctx), toString(value2, ctx)); }
[ "public", "static", "Pair", "<", "Object", ",", "Object", ">", "toSame", "(", "Object", "value1", ",", "Object", "value2", ",", "EvaluationContext", "ctx", ")", "{", "if", "(", "value1", ".", "getClass", "(", ")", ".", "equals", "(", "value2", ".", "ge...
Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values but is necessary for us to intuitively handle contact fields which don't use the correct value type
[ "Converts", "a", "pair", "of", "arguments", "to", "their", "most", "-", "likely", "types", ".", "This", "deviates", "from", "Excel", "which", "doesn", "t", "auto", "convert", "values", "but", "is", "necessary", "for", "us", "to", "intuitively", "handle", "...
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Conversions.java#L216-L242
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/Parameter.java
Parameter.fromMethod
public static Parameter[] fromMethod(Method method) { Class<?>[] types = method.getParameterTypes(); Annotation[][] annotations = method.getParameterAnnotations(); int numParams = types.length; Parameter[] params = new Parameter[numParams]; for (int p = 0; p < numParams; p++) { params[p] = new Parameter(types[p], annotations[p]); } return params; }
java
public static Parameter[] fromMethod(Method method) { Class<?>[] types = method.getParameterTypes(); Annotation[][] annotations = method.getParameterAnnotations(); int numParams = types.length; Parameter[] params = new Parameter[numParams]; for (int p = 0; p < numParams; p++) { params[p] = new Parameter(types[p], annotations[p]); } return params; }
[ "public", "static", "Parameter", "[", "]", "fromMethod", "(", "Method", "method", ")", "{", "Class", "<", "?", ">", "[", "]", "types", "=", "method", ".", "getParameterTypes", "(", ")", ";", "Annotation", "[", "]", "[", "]", "annotations", "=", "method...
Returns an array of Parameter objects that represent all the parameters to the underlying method
[ "Returns", "an", "array", "of", "Parameter", "objects", "that", "represent", "all", "the", "parameters", "to", "the", "underlying", "method" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/Parameter.java#L23-L33
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/Parameter.java
Parameter.getAnnotation
public <T> T getAnnotation(Class<T> annotationClass) { for (Annotation annotation : m_annotations) { if (annotation.annotationType().equals(annotationClass)){ return (T) annotation; } } return null; }
java
public <T> T getAnnotation(Class<T> annotationClass) { for (Annotation annotation : m_annotations) { if (annotation.annotationType().equals(annotationClass)){ return (T) annotation; } } return null; }
[ "public", "<", "T", ">", "T", "getAnnotation", "(", "Class", "<", "T", ">", "annotationClass", ")", "{", "for", "(", "Annotation", "annotation", ":", "m_annotations", ")", "{", "if", "(", "annotation", ".", "annotationType", "(", ")", ".", "equals", "(",...
Returns this element's annotation for the specified type if such an annotation is present, else null
[ "Returns", "this", "element", "s", "annotation", "for", "the", "specified", "type", "if", "such", "an", "annotation", "is", "present", "else", "null" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/Parameter.java#L38-L45
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.slice
public static <T> List<T> slice(List<T> list, Integer start, Integer stop) { int size = list.size(); if (start == null) { start = 0; } else if (start < 0) { start = size + start; } if (stop == null) { stop = size; } else if (stop < 0) { stop = size + stop; } if (start >= size || stop <= 0 || start >= stop) { return Collections.emptyList(); } start = Math.max(0, start); stop = Math.min(size, stop); return list.subList(start, stop); }
java
public static <T> List<T> slice(List<T> list, Integer start, Integer stop) { int size = list.size(); if (start == null) { start = 0; } else if (start < 0) { start = size + start; } if (stop == null) { stop = size; } else if (stop < 0) { stop = size + stop; } if (start >= size || stop <= 0 || start >= stop) { return Collections.emptyList(); } start = Math.max(0, start); stop = Math.min(size, stop); return list.subList(start, stop); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "slice", "(", "List", "<", "T", ">", "list", ",", "Integer", "start", ",", "Integer", "stop", ")", "{", "int", "size", "=", "list", ".", "size", "(", ")", ";", "if", "(", "start", "==", ...
Slices a list, Python style @param list the list @param start the start index (null means the beginning of the list) @param stop the stop index (null means the end of the list) @return the slice
[ "Slices", "a", "list", "Python", "style" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L41-L64
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.decimalPow
public static BigDecimal decimalPow(BigDecimal number, BigDecimal power) { return new BigDecimal(Math.pow(number.doubleValue(), power.doubleValue()), MATH); }
java
public static BigDecimal decimalPow(BigDecimal number, BigDecimal power) { return new BigDecimal(Math.pow(number.doubleValue(), power.doubleValue()), MATH); }
[ "public", "static", "BigDecimal", "decimalPow", "(", "BigDecimal", "number", ",", "BigDecimal", "power", ")", "{", "return", "new", "BigDecimal", "(", "Math", ".", "pow", "(", "number", ".", "doubleValue", "(", ")", ",", "power", ".", "doubleValue", "(", "...
Pow for two decimals
[ "Pow", "for", "two", "decimals" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L69-L71
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.decimalRound
public static BigDecimal decimalRound(BigDecimal number, int numDigits, RoundingMode rounding) { BigDecimal rounded = number.setScale(numDigits, rounding); if (numDigits < 0) { rounded = rounded.setScale(0, BigDecimal.ROUND_UNNECESSARY); } return rounded; }
java
public static BigDecimal decimalRound(BigDecimal number, int numDigits, RoundingMode rounding) { BigDecimal rounded = number.setScale(numDigits, rounding); if (numDigits < 0) { rounded = rounded.setScale(0, BigDecimal.ROUND_UNNECESSARY); } return rounded; }
[ "public", "static", "BigDecimal", "decimalRound", "(", "BigDecimal", "number", ",", "int", "numDigits", ",", "RoundingMode", "rounding", ")", "{", "BigDecimal", "rounded", "=", "number", ".", "setScale", "(", "numDigits", ",", "rounding", ")", ";", "if", "(", ...
Rounding for decimals with support for negative digits
[ "Rounding", "for", "decimals", "with", "support", "for", "negative", "digits" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L76-L84
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.urlquote
public static String urlquote(String text) { try { return URLEncoder.encode(text, "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
java
public static String urlquote(String text) { try { return URLEncoder.encode(text, "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
[ "public", "static", "String", "urlquote", "(", "String", "text", ")", "{", "try", "{", "return", "URLEncoder", ".", "encode", "(", "text", ",", "\"UTF-8\"", ")", ".", "replace", "(", "\"+\"", ",", "\"%20\"", ")", ";", "}", "catch", "(", "UnsupportedEncod...
Encodes text for inclusion in a URL query string. Should be equivalent to Django's urlquote function. @param text the text to encode @return the encoded text
[ "Encodes", "text", "for", "inclusion", "in", "a", "URL", "query", "string", ".", "Should", "be", "equivalent", "to", "Django", "s", "urlquote", "function", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L91-L97
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.getDateFormatter
public static DateTimeFormatter getDateFormatter(DateStyle dateStyle, boolean incTime) { String format = dateStyle.equals(DateStyle.DAY_FIRST) ? "dd-MM-yyyy" : "MM-dd-yyyy"; return DateTimeFormatter.ofPattern(incTime ? format + " HH:mm" : format); }
java
public static DateTimeFormatter getDateFormatter(DateStyle dateStyle, boolean incTime) { String format = dateStyle.equals(DateStyle.DAY_FIRST) ? "dd-MM-yyyy" : "MM-dd-yyyy"; return DateTimeFormatter.ofPattern(incTime ? format + " HH:mm" : format); }
[ "public", "static", "DateTimeFormatter", "getDateFormatter", "(", "DateStyle", "dateStyle", ",", "boolean", "incTime", ")", "{", "String", "format", "=", "dateStyle", ".", "equals", "(", "DateStyle", ".", "DAY_FIRST", ")", "?", "\"dd-MM-yyyy\"", ":", "\"MM-dd-yyyy...
Gets a formatter for dates or datetimes @param dateStyle whether parsing should be day-first or month-first @param incTime whether to include time @return the formatter
[ "Gets", "a", "formatter", "for", "dates", "or", "datetimes" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L105-L108
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.tokenize
public static String[] tokenize(String text) { final int len = text.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } final List<String> list = new ArrayList<>(); int i = 0; while (i < len) { char ch = text.charAt(i); int ch32 = text.codePointAt(i); if (isSymbolChar(ch32)) { list.add(new String(Character.toChars(ch32))); i += Character.isHighSurrogate(ch) ? 2 : 1; continue; } if (isWordChar(ch)) { int wordStart = i; while (i < len && isWordChar(text.codePointAt(i))) { i++; } list.add(text.substring(wordStart, i)); continue; } i++; } return list.toArray(new String[list.size()]); }
java
public static String[] tokenize(String text) { final int len = text.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } final List<String> list = new ArrayList<>(); int i = 0; while (i < len) { char ch = text.charAt(i); int ch32 = text.codePointAt(i); if (isSymbolChar(ch32)) { list.add(new String(Character.toChars(ch32))); i += Character.isHighSurrogate(ch) ? 2 : 1; continue; } if (isWordChar(ch)) { int wordStart = i; while (i < len && isWordChar(text.codePointAt(i))) { i++; } list.add(text.substring(wordStart, i)); continue; } i++; } return list.toArray(new String[list.size()]); }
[ "public", "static", "String", "[", "]", "tokenize", "(", "String", "text", ")", "{", "final", "int", "len", "=", "text", ".", "length", "(", ")", ";", "if", "(", "len", "==", "0", ")", "{", "return", "ArrayUtils", ".", "EMPTY_STRING_ARRAY", ";", "}",...
Tokenizes a string by splitting on non-word characters. This should be equivalent to splitting on \W+ in Python. The meaning of \W is different in Android, Java 7, Java 8 hence the non-use of regular expressions. @param text the input text @return the string tokens
[ "Tokenizes", "a", "string", "by", "splitting", "on", "non", "-", "word", "characters", ".", "This", "should", "be", "equivalent", "to", "splitting", "on", "\\", "W", "+", "in", "Python", ".", "The", "meaning", "of", "\\", "W", "is", "different", "in", ...
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L123-L154
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.parseJsonDate
public static Instant parseJsonDate(String value) { if (value == null) { return null; } return LocalDateTime.parse(value, JSON_DATETIME_FORMAT).atOffset(ZoneOffset.UTC).toInstant(); }
java
public static Instant parseJsonDate(String value) { if (value == null) { return null; } return LocalDateTime.parse(value, JSON_DATETIME_FORMAT).atOffset(ZoneOffset.UTC).toInstant(); }
[ "public", "static", "Instant", "parseJsonDate", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "return", "LocalDateTime", ".", "parse", "(", "value", ",", "JSON_DATETIME_FORMAT", ")", ".", "atOffse...
Parses an ISO8601 formatted time instant from a string value
[ "Parses", "an", "ISO8601", "formatted", "time", "instant", "from", "a", "string", "value" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L185-L190
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.toLowerCaseKeys
public static <T> Map<String, T> toLowerCaseKeys(Map<String, T> map) { Map<String, T> res = new HashMap<>(); for (Map.Entry<String, T> entry : map.entrySet()) { res.put(entry.getKey().toLowerCase(), entry.getValue()); } return res; }
java
public static <T> Map<String, T> toLowerCaseKeys(Map<String, T> map) { Map<String, T> res = new HashMap<>(); for (Map.Entry<String, T> entry : map.entrySet()) { res.put(entry.getKey().toLowerCase(), entry.getValue()); } return res; }
[ "public", "static", "<", "T", ">", "Map", "<", "String", ",", "T", ">", "toLowerCaseKeys", "(", "Map", "<", "String", ",", "T", ">", "map", ")", "{", "Map", "<", "String", ",", "T", ">", "res", "=", "new", "HashMap", "<>", "(", ")", ";", "for",...
Returns a copy of the given map with lowercase keys @param map the map to convert @return copy of map with lowercase keys
[ "Returns", "a", "copy", "of", "the", "given", "map", "with", "lowercase", "keys" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L197-L203
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java
ExpressionUtils.isSymbolChar
static boolean isSymbolChar(int ch) { int t = Character.getType(ch); return t == Character.MATH_SYMBOL || t == Character.CURRENCY_SYMBOL || t == Character.MODIFIER_SYMBOL || t == Character.OTHER_SYMBOL; }
java
static boolean isSymbolChar(int ch) { int t = Character.getType(ch); return t == Character.MATH_SYMBOL || t == Character.CURRENCY_SYMBOL || t == Character.MODIFIER_SYMBOL || t == Character.OTHER_SYMBOL; }
[ "static", "boolean", "isSymbolChar", "(", "int", "ch", ")", "{", "int", "t", "=", "Character", ".", "getType", "(", "ch", ")", ";", "return", "t", "==", "Character", ".", "MATH_SYMBOL", "||", "t", "==", "Character", ".", "CURRENCY_SYMBOL", "||", "t", "...
Returns whether the given character is a Unicode symbol
[ "Returns", "whether", "the", "given", "character", "is", "a", "Unicode", "symbol" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/utils/ExpressionUtils.java#L215-L218
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions._char
public static String _char(EvaluationContext ctx, Object number) { return "" + (char) Conversions.toInteger(number, ctx); }
java
public static String _char(EvaluationContext ctx, Object number) { return "" + (char) Conversions.toInteger(number, ctx); }
[ "public", "static", "String", "_char", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "return", "\"\"", "+", "(", "char", ")", "Conversions", ".", "toInteger", "(", "number", ",", "ctx", ")", ";", "}" ]
Returns the character specified by a number
[ "Returns", "the", "character", "specified", "by", "a", "number" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L34-L36
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.clean
public static String clean(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).replaceAll("\\p{C}", ""); }
java
public static String clean(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).replaceAll("\\p{C}", ""); }
[ "public", "static", "String", "clean", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "replaceAll", "(", "\"\\\\p{C}\"", ",", "\"\"", ")", ";", "}" ]
Removes all non-printable characters from a text string
[ "Removes", "all", "non", "-", "printable", "characters", "from", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L41-L43
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.concatenate
public static String concatenate(EvaluationContext ctx, Object... args) { StringBuilder sb = new StringBuilder(); for (Object arg : args) { sb.append(Conversions.toString(arg, ctx)); } return sb.toString(); }
java
public static String concatenate(EvaluationContext ctx, Object... args) { StringBuilder sb = new StringBuilder(); for (Object arg : args) { sb.append(Conversions.toString(arg, ctx)); } return sb.toString(); }
[ "public", "static", "String", "concatenate", "(", "EvaluationContext", "ctx", ",", "Object", "...", "args", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Object", "arg", ":", "args", ")", "{", "sb", ".", "appen...
Joins text strings into one text string
[ "Joins", "text", "strings", "into", "one", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L55-L61
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.fixed
public static String fixed(EvaluationContext ctx, Object number, @IntegerDefault(2) Object decimals, @BooleanDefault(false) Object noCommas) { BigDecimal _number = Conversions.toDecimal(number, ctx); _number = _number.setScale(Conversions.toInteger(decimals, ctx), RoundingMode.HALF_UP); DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(9); format.setGroupingUsed(!Conversions.toBoolean(noCommas, ctx)); return format.format(_number); }
java
public static String fixed(EvaluationContext ctx, Object number, @IntegerDefault(2) Object decimals, @BooleanDefault(false) Object noCommas) { BigDecimal _number = Conversions.toDecimal(number, ctx); _number = _number.setScale(Conversions.toInteger(decimals, ctx), RoundingMode.HALF_UP); DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(9); format.setGroupingUsed(!Conversions.toBoolean(noCommas, ctx)); return format.format(_number); }
[ "public", "static", "String", "fixed", "(", "EvaluationContext", "ctx", ",", "Object", "number", ",", "@", "IntegerDefault", "(", "2", ")", "Object", "decimals", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "noCommas", ")", "{", "BigDecimal", "_n...
Formats the given number in decimal format using a period and commas
[ "Formats", "the", "given", "number", "in", "decimal", "format", "using", "a", "period", "and", "commas" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L66-L74
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.left
public static String left(EvaluationContext ctx, Object text, Object numChars) { int _numChars = Conversions.toInteger(numChars, ctx); if (_numChars < 0) { throw new RuntimeException("Number of chars can't be negative"); } return StringUtils.left(Conversions.toString(text, ctx), _numChars); }
java
public static String left(EvaluationContext ctx, Object text, Object numChars) { int _numChars = Conversions.toInteger(numChars, ctx); if (_numChars < 0) { throw new RuntimeException("Number of chars can't be negative"); } return StringUtils.left(Conversions.toString(text, ctx), _numChars); }
[ "public", "static", "String", "left", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "numChars", ")", "{", "int", "_numChars", "=", "Conversions", ".", "toInteger", "(", "numChars", ",", "ctx", ")", ";", "if", "(", "_numChars", "<",...
Returns the first characters in a text string
[ "Returns", "the", "first", "characters", "in", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L79-L86
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.len
public static int len(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).length(); }
java
public static int len(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).length(); }
[ "public", "static", "int", "len", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "length", "(", ")", ";", "}" ]
Returns the number of characters in a text string
[ "Returns", "the", "number", "of", "characters", "in", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L91-L93
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.lower
public static String lower(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).toLowerCase(); }
java
public static String lower(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).toLowerCase(); }
[ "public", "static", "String", "lower", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Converts a text string to lowercase
[ "Converts", "a", "text", "string", "to", "lowercase" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L98-L100
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.proper
public static String proper(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx).toLowerCase(); if (!StringUtils.isEmpty(_text)) { char[] buffer = _text.toCharArray(); boolean capitalizeNext = true; for (int i = 0; i < buffer.length; ++i) { char ch = buffer[i]; if (!Character.isAlphabetic(ch)) { capitalizeNext = true; } else if (capitalizeNext) { buffer[i] = Character.toTitleCase(ch); capitalizeNext = false; } } return new String(buffer); } else { return _text; } }
java
public static String proper(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx).toLowerCase(); if (!StringUtils.isEmpty(_text)) { char[] buffer = _text.toCharArray(); boolean capitalizeNext = true; for (int i = 0; i < buffer.length; ++i) { char ch = buffer[i]; if (!Character.isAlphabetic(ch)) { capitalizeNext = true; } else if (capitalizeNext) { buffer[i] = Character.toTitleCase(ch); capitalizeNext = false; } } return new String(buffer); } else { return _text; } }
[ "public", "static", "String", "proper", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "StringUtil...
Capitalizes the first letter of every word in a text string
[ "Capitalizes", "the", "first", "letter", "of", "every", "word", "in", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L105-L125
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.rept
public static String rept(EvaluationContext ctx, Object text, Object numberTimes) { int _numberTimes = Conversions.toInteger(numberTimes, ctx); if (_numberTimes < 0) { throw new RuntimeException("Number of times can't be negative"); } return StringUtils.repeat(Conversions.toString(text, ctx), _numberTimes); }
java
public static String rept(EvaluationContext ctx, Object text, Object numberTimes) { int _numberTimes = Conversions.toInteger(numberTimes, ctx); if (_numberTimes < 0) { throw new RuntimeException("Number of times can't be negative"); } return StringUtils.repeat(Conversions.toString(text, ctx), _numberTimes); }
[ "public", "static", "String", "rept", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "numberTimes", ")", "{", "int", "_numberTimes", "=", "Conversions", ".", "toInteger", "(", "numberTimes", ",", "ctx", ")", ";", "if", "(", "_numberTi...
Repeats text a given number of times
[ "Repeats", "text", "a", "given", "number", "of", "times" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L130-L137
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.substitute
public static String substitute(EvaluationContext ctx, Object text, Object oldText, Object newText, @IntegerDefault(-1) Object instanceNum) { String _text = Conversions.toString(text, ctx); String _oldText = Conversions.toString(oldText, ctx); String _newText = Conversions.toString(newText, ctx); int _instanceNum = Conversions.toInteger(instanceNum, ctx); if (_instanceNum < 0) { return _text.replace(_oldText, _newText); } else { String[] splits = _text.split(_oldText); StringBuilder output = new StringBuilder(splits[0]); for (int s = 1; s < splits.length; s++) { String sep = s == _instanceNum ? _newText : _oldText; output.append(sep); output.append(splits[s]); } return output.toString(); } }
java
public static String substitute(EvaluationContext ctx, Object text, Object oldText, Object newText, @IntegerDefault(-1) Object instanceNum) { String _text = Conversions.toString(text, ctx); String _oldText = Conversions.toString(oldText, ctx); String _newText = Conversions.toString(newText, ctx); int _instanceNum = Conversions.toInteger(instanceNum, ctx); if (_instanceNum < 0) { return _text.replace(_oldText, _newText); } else { String[] splits = _text.split(_oldText); StringBuilder output = new StringBuilder(splits[0]); for (int s = 1; s < splits.length; s++) { String sep = s == _instanceNum ? _newText : _oldText; output.append(sep); output.append(splits[s]); } return output.toString(); } }
[ "public", "static", "String", "substitute", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "oldText", ",", "Object", "newText", ",", "@", "IntegerDefault", "(", "-", "1", ")", "Object", "instanceNum", ")", "{", "String", "_text", "=",...
Substitutes new_text for old_text in a text string
[ "Substitutes", "new_text", "for", "old_text", "in", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L154-L173
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.unichar
public static String unichar(EvaluationContext ctx, Object number) { return "" + (char) Conversions.toInteger(number, ctx); }
java
public static String unichar(EvaluationContext ctx, Object number) { return "" + (char) Conversions.toInteger(number, ctx); }
[ "public", "static", "String", "unichar", "(", "EvaluationContext", "ctx", ",", "Object", "number", ")", "{", "return", "\"\"", "+", "(", "char", ")", "Conversions", ".", "toInteger", "(", "number", ",", "ctx", ")", ";", "}" ]
Returns the unicode character specified by a number
[ "Returns", "the", "unicode", "character", "specified", "by", "a", "number" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L178-L180
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.unicode
public static int unicode(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx); if (_text.length() == 0) { throw new RuntimeException("Text can't be empty"); } return (int) _text.charAt(0); }
java
public static int unicode(EvaluationContext ctx, Object text) { String _text = Conversions.toString(text, ctx); if (_text.length() == 0) { throw new RuntimeException("Text can't be empty"); } return (int) _text.charAt(0); }
[ "public", "static", "int", "unicode", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "if", "(", "_text", ".", "length", "(", ")", "==", "0", ...
Returns a numeric code for the first character in a text string
[ "Returns", "a", "numeric", "code", "for", "the", "first", "character", "in", "a", "text", "string" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L185-L191
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.upper
public static String upper(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).toUpperCase(); }
java
public static String upper(EvaluationContext ctx, Object text) { return Conversions.toString(text, ctx).toUpperCase(); }
[ "public", "static", "String", "upper", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ".", "toUpperCase", "(", ")", ";", "}" ]
Converts a text string to uppercase
[ "Converts", "a", "text", "string", "to", "uppercase" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L196-L198
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.date
public static LocalDate date(EvaluationContext ctx, Object year, Object month, Object day) { return LocalDate.of(Conversions.toInteger(year, ctx), Conversions.toInteger(month, ctx), Conversions.toInteger(day, ctx)); }
java
public static LocalDate date(EvaluationContext ctx, Object year, Object month, Object day) { return LocalDate.of(Conversions.toInteger(year, ctx), Conversions.toInteger(month, ctx), Conversions.toInteger(day, ctx)); }
[ "public", "static", "LocalDate", "date", "(", "EvaluationContext", "ctx", ",", "Object", "year", ",", "Object", "month", ",", "Object", "day", ")", "{", "return", "LocalDate", ".", "of", "(", "Conversions", ".", "toInteger", "(", "year", ",", "ctx", ")", ...
Defines a date value
[ "Defines", "a", "date", "value" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L207-L209
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.datedif
public static int datedif(EvaluationContext ctx, Object startDate, Object endDate, Object unit) { LocalDate _startDate = Conversions.toDate(startDate, ctx); LocalDate _endDate = Conversions.toDate(endDate, ctx); String _unit = Conversions.toString(unit, ctx).toLowerCase(); if (_startDate.isAfter(_endDate)) { throw new RuntimeException("Start date cannot be after end date"); } switch (_unit) { case "y": return (int) ChronoUnit.YEARS.between(_startDate, _endDate); case "m": return (int) ChronoUnit.MONTHS.between(_startDate, _endDate); case "d": return (int) ChronoUnit.DAYS.between(_startDate, _endDate); case "md": return Period.between(_startDate, _endDate).getDays(); case "ym": return Period.between(_startDate, _endDate).getMonths(); case "yd": return (int) ChronoUnit.DAYS.between(_startDate.withYear(_endDate.getYear()), _endDate); } throw new RuntimeException("Invalid unit value: " + _unit); }
java
public static int datedif(EvaluationContext ctx, Object startDate, Object endDate, Object unit) { LocalDate _startDate = Conversions.toDate(startDate, ctx); LocalDate _endDate = Conversions.toDate(endDate, ctx); String _unit = Conversions.toString(unit, ctx).toLowerCase(); if (_startDate.isAfter(_endDate)) { throw new RuntimeException("Start date cannot be after end date"); } switch (_unit) { case "y": return (int) ChronoUnit.YEARS.between(_startDate, _endDate); case "m": return (int) ChronoUnit.MONTHS.between(_startDate, _endDate); case "d": return (int) ChronoUnit.DAYS.between(_startDate, _endDate); case "md": return Period.between(_startDate, _endDate).getDays(); case "ym": return Period.between(_startDate, _endDate).getMonths(); case "yd": return (int) ChronoUnit.DAYS.between(_startDate.withYear(_endDate.getYear()), _endDate); } throw new RuntimeException("Invalid unit value: " + _unit); }
[ "public", "static", "int", "datedif", "(", "EvaluationContext", "ctx", ",", "Object", "startDate", ",", "Object", "endDate", ",", "Object", "unit", ")", "{", "LocalDate", "_startDate", "=", "Conversions", ".", "toDate", "(", "startDate", ",", "ctx", ")", ";"...
Calculates the number of days, months, or years between two dates.
[ "Calculates", "the", "number", "of", "days", "months", "or", "years", "between", "two", "dates", "." ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L214-L239
train
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java
ExcelFunctions.datevalue
public static LocalDate datevalue(EvaluationContext ctx, Object text) { return Conversions.toDate(text, ctx); }
java
public static LocalDate datevalue(EvaluationContext ctx, Object text) { return Conversions.toDate(text, ctx); }
[ "public", "static", "LocalDate", "datevalue", "(", "EvaluationContext", "ctx", ",", "Object", "text", ")", "{", "return", "Conversions", ".", "toDate", "(", "text", ",", "ctx", ")", ";", "}" ]
Converts date stored in text to an actual date
[ "Converts", "date", "stored", "in", "text", "to", "an", "actual", "date" ]
b03d91ec58fc328960bce90ecb5fa49dcf467627
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L244-L246
train