repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
RedisInner.importData
public void importData(String resourceGroupName, String name, ImportRDBParameters parameters) { """ Import data into Redis cache. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @param parameters Parameters for Redis import operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ importDataWithServiceResponseAsync(resourceGroupName, name, parameters).toBlocking().last().body(); }
java
public void importData(String resourceGroupName, String name, ImportRDBParameters parameters) { importDataWithServiceResponseAsync(resourceGroupName, name, parameters).toBlocking().last().body(); }
[ "public", "void", "importData", "(", "String", "resourceGroupName", ",", "String", "name", ",", "ImportRDBParameters", "parameters", ")", "{", "importDataWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Import data into Redis cache. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @param parameters Parameters for Redis import operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Import", "data", "into", "Redis", "cache", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1337-L1339
sundrio/sundrio
maven-plugin/src/main/java/io/sundr/maven/Reflections.java
Reflections.readAnyField
static String readAnyField(Object obj, String ... names) { """ Read any field that matches the specified name. @param obj The obj to read from. @param names The var-arg of names. @return The value of the first field that matches or null if no match is found. """ try { for (String name : names) { try { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); return (String) field.get(obj); } catch (NoSuchFieldException e) { //ignore and try next field... } } return null; } catch (IllegalAccessException e) { return null; } }
java
static String readAnyField(Object obj, String ... names) { try { for (String name : names) { try { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); return (String) field.get(obj); } catch (NoSuchFieldException e) { //ignore and try next field... } } return null; } catch (IllegalAccessException e) { return null; } }
[ "static", "String", "readAnyField", "(", "Object", "obj", ",", "String", "...", "names", ")", "{", "try", "{", "for", "(", "String", "name", ":", "names", ")", "{", "try", "{", "Field", "field", "=", "obj", ".", "getClass", "(", ")", ".", "getDeclaredField", "(", "name", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "return", "(", "String", ")", "field", ".", "get", "(", "obj", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "//ignore and try next field...", "}", "}", "return", "null", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Read any field that matches the specified name. @param obj The obj to read from. @param names The var-arg of names. @return The value of the first field that matches or null if no match is found.
[ "Read", "any", "field", "that", "matches", "the", "specified", "name", "." ]
train
https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/maven-plugin/src/main/java/io/sundr/maven/Reflections.java#L54-L69
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/GammaDistribution.java
GammaDistribution.logpdf
public static double logpdf(double x, double k, double theta) { """ Gamma distribution PDF (with 0.0 for x &lt; 0) @param x query value @param k Alpha @param theta Theta = 1 / Beta @return probability density """ if(x < 0) { return Double.NEGATIVE_INFINITY; } if(x == 0) { return (k == 1.0) ? FastMath.log(theta) : Double.NEGATIVE_INFINITY; } if(k == 1.0) { return FastMath.log(theta) - x * theta; } final double xt = x * theta; return (xt == Double.POSITIVE_INFINITY) ? Double.NEGATIVE_INFINITY : // FastMath.log(theta) + (k - 1.0) * FastMath.log(xt) - xt - logGamma(k); }
java
public static double logpdf(double x, double k, double theta) { if(x < 0) { return Double.NEGATIVE_INFINITY; } if(x == 0) { return (k == 1.0) ? FastMath.log(theta) : Double.NEGATIVE_INFINITY; } if(k == 1.0) { return FastMath.log(theta) - x * theta; } final double xt = x * theta; return (xt == Double.POSITIVE_INFINITY) ? Double.NEGATIVE_INFINITY : // FastMath.log(theta) + (k - 1.0) * FastMath.log(xt) - xt - logGamma(k); }
[ "public", "static", "double", "logpdf", "(", "double", "x", ",", "double", "k", ",", "double", "theta", ")", "{", "if", "(", "x", "<", "0", ")", "{", "return", "Double", ".", "NEGATIVE_INFINITY", ";", "}", "if", "(", "x", "==", "0", ")", "{", "return", "(", "k", "==", "1.0", ")", "?", "FastMath", ".", "log", "(", "theta", ")", ":", "Double", ".", "NEGATIVE_INFINITY", ";", "}", "if", "(", "k", "==", "1.0", ")", "{", "return", "FastMath", ".", "log", "(", "theta", ")", "-", "x", "*", "theta", ";", "}", "final", "double", "xt", "=", "x", "*", "theta", ";", "return", "(", "xt", "==", "Double", ".", "POSITIVE_INFINITY", ")", "?", "Double", ".", "NEGATIVE_INFINITY", ":", "//", "FastMath", ".", "log", "(", "theta", ")", "+", "(", "k", "-", "1.0", ")", "*", "FastMath", ".", "log", "(", "xt", ")", "-", "xt", "-", "logGamma", "(", "k", ")", ";", "}" ]
Gamma distribution PDF (with 0.0 for x &lt; 0) @param x query value @param k Alpha @param theta Theta = 1 / Beta @return probability density
[ "Gamma", "distribution", "PDF", "(", "with", "0", ".", "0", "for", "x", "&lt", ";", "0", ")" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/GammaDistribution.java#L240-L253
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/ConnectionParams.java
ConnectionParams.addPiece
private void addPiece(String pc, String prefix, StringBuilder sb) { """ Used to build a connection string for display. @param pc A connection string field. @param prefix The prefix to include if the field is not empty. @param sb String builder instance. """ if (!pc.isEmpty()) { if (sb.length() > 0) { sb.append(prefix); } sb.append(pc); } }
java
private void addPiece(String pc, String prefix, StringBuilder sb) { if (!pc.isEmpty()) { if (sb.length() > 0) { sb.append(prefix); } sb.append(pc); } }
[ "private", "void", "addPiece", "(", "String", "pc", ",", "String", "prefix", ",", "StringBuilder", "sb", ")", "{", "if", "(", "!", "pc", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "prefix", ")", ";", "}", "sb", ".", "append", "(", "pc", ")", ";", "}", "}" ]
Used to build a connection string for display. @param pc A connection string field. @param prefix The prefix to include if the field is not empty. @param sb String builder instance.
[ "Used", "to", "build", "a", "connection", "string", "for", "display", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/ConnectionParams.java#L153-L161
moparisthebest/beehive
beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java
DefaultObjectResultSetMapper.arrayFromResultSet
protected Object arrayFromResultSet(ResultSet rs, int maxRows, Class arrayClass, Calendar cal) throws SQLException { """ Invoked when the return type of the method is an array type. @param rs ResultSet to process. @param maxRows The maximum size of array to create, a value of 0 indicates that the array size will be the same as the result set size (no limit). @param arrayClass The class of object contained within the array @param cal A calendar instance to use for date/time values @return An array of the specified class type @throws SQLException On error. """ ArrayList<Object> list = new ArrayList<Object>(); Class componentType = arrayClass.getComponentType(); RowMapper rowMapper = RowMapperFactory.getRowMapper(rs, componentType, cal); // a value of zero indicates that all rows from the resultset should be included. if (maxRows == 0) { maxRows = -1; } int numRows; boolean hasMoreRows = rs.next(); for (numRows = 0; numRows != maxRows && hasMoreRows; numRows++) { list.add(rowMapper.mapRowToReturnType()); hasMoreRows = rs.next(); } Object array = Array.newInstance(componentType, numRows); try { for (int i = 0; i < numRows; i++) { Array.set(array, i, list.get(i)); } } catch (IllegalArgumentException iae) { ResultSetMetaData md = rs.getMetaData(); // assuming no errors in resultSetObject() this can only happen // for single column result sets. throw new ControlException("The declared Java type for array " + componentType.getName() + "is incompatible with the SQL format of column " + md.getColumnName(1) + md.getColumnTypeName(1) + "which returns objects of type + " + list.get(0).getClass().getName()); } return array; }
java
protected Object arrayFromResultSet(ResultSet rs, int maxRows, Class arrayClass, Calendar cal) throws SQLException { ArrayList<Object> list = new ArrayList<Object>(); Class componentType = arrayClass.getComponentType(); RowMapper rowMapper = RowMapperFactory.getRowMapper(rs, componentType, cal); // a value of zero indicates that all rows from the resultset should be included. if (maxRows == 0) { maxRows = -1; } int numRows; boolean hasMoreRows = rs.next(); for (numRows = 0; numRows != maxRows && hasMoreRows; numRows++) { list.add(rowMapper.mapRowToReturnType()); hasMoreRows = rs.next(); } Object array = Array.newInstance(componentType, numRows); try { for (int i = 0; i < numRows; i++) { Array.set(array, i, list.get(i)); } } catch (IllegalArgumentException iae) { ResultSetMetaData md = rs.getMetaData(); // assuming no errors in resultSetObject() this can only happen // for single column result sets. throw new ControlException("The declared Java type for array " + componentType.getName() + "is incompatible with the SQL format of column " + md.getColumnName(1) + md.getColumnTypeName(1) + "which returns objects of type + " + list.get(0).getClass().getName()); } return array; }
[ "protected", "Object", "arrayFromResultSet", "(", "ResultSet", "rs", ",", "int", "maxRows", ",", "Class", "arrayClass", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "ArrayList", "<", "Object", ">", "list", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "Class", "componentType", "=", "arrayClass", ".", "getComponentType", "(", ")", ";", "RowMapper", "rowMapper", "=", "RowMapperFactory", ".", "getRowMapper", "(", "rs", ",", "componentType", ",", "cal", ")", ";", "// a value of zero indicates that all rows from the resultset should be included.", "if", "(", "maxRows", "==", "0", ")", "{", "maxRows", "=", "-", "1", ";", "}", "int", "numRows", ";", "boolean", "hasMoreRows", "=", "rs", ".", "next", "(", ")", ";", "for", "(", "numRows", "=", "0", ";", "numRows", "!=", "maxRows", "&&", "hasMoreRows", ";", "numRows", "++", ")", "{", "list", ".", "add", "(", "rowMapper", ".", "mapRowToReturnType", "(", ")", ")", ";", "hasMoreRows", "=", "rs", ".", "next", "(", ")", ";", "}", "Object", "array", "=", "Array", ".", "newInstance", "(", "componentType", ",", "numRows", ")", ";", "try", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numRows", ";", "i", "++", ")", "{", "Array", ".", "set", "(", "array", ",", "i", ",", "list", ".", "get", "(", "i", ")", ")", ";", "}", "}", "catch", "(", "IllegalArgumentException", "iae", ")", "{", "ResultSetMetaData", "md", "=", "rs", ".", "getMetaData", "(", ")", ";", "// assuming no errors in resultSetObject() this can only happen", "// for single column result sets.", "throw", "new", "ControlException", "(", "\"The declared Java type for array \"", "+", "componentType", ".", "getName", "(", ")", "+", "\"is incompatible with the SQL format of column \"", "+", "md", ".", "getColumnName", "(", "1", ")", "+", "md", ".", "getColumnTypeName", "(", "1", ")", "+", "\"which returns objects of type + \"", "+", "list", ".", "get", "(", "0", ")", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "return", "array", ";", "}" ]
Invoked when the return type of the method is an array type. @param rs ResultSet to process. @param maxRows The maximum size of array to create, a value of 0 indicates that the array size will be the same as the result set size (no limit). @param arrayClass The class of object contained within the array @param cal A calendar instance to use for date/time values @return An array of the specified class type @throws SQLException On error.
[ "Invoked", "when", "the", "return", "type", "of", "the", "method", "is", "an", "array", "type", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java#L88-L122
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.checkDeletedParentFolder
private boolean checkDeletedParentFolder(CmsDbContext dbc, List<CmsResource> deletedFolders, CmsResource res) { """ Checks the parent of a resource during publishing.<p> @param dbc the current database context @param deletedFolders a list of deleted folders @param res a resource to check the parent for @return <code>true</code> if the parent resource will be deleted during publishing """ String parentPath = CmsResource.getParentFolder(res.getRootPath()); if (parentPath == null) { // resource has no parent return false; } CmsResource parent; try { parent = readResource(dbc, parentPath, CmsResourceFilter.ALL); } catch (Exception e) { // failure: if we cannot read the parent, we should not publish the resource return false; } if (!parent.getState().isDeleted()) { // parent is not deleted return false; } for (int j = 0; j < deletedFolders.size(); j++) { if ((deletedFolders.get(j)).getStructureId().equals(parent.getStructureId())) { // parent is deleted, and it will get published return true; } } // parent is new, but it will not get published return false; }
java
private boolean checkDeletedParentFolder(CmsDbContext dbc, List<CmsResource> deletedFolders, CmsResource res) { String parentPath = CmsResource.getParentFolder(res.getRootPath()); if (parentPath == null) { // resource has no parent return false; } CmsResource parent; try { parent = readResource(dbc, parentPath, CmsResourceFilter.ALL); } catch (Exception e) { // failure: if we cannot read the parent, we should not publish the resource return false; } if (!parent.getState().isDeleted()) { // parent is not deleted return false; } for (int j = 0; j < deletedFolders.size(); j++) { if ((deletedFolders.get(j)).getStructureId().equals(parent.getStructureId())) { // parent is deleted, and it will get published return true; } } // parent is new, but it will not get published return false; }
[ "private", "boolean", "checkDeletedParentFolder", "(", "CmsDbContext", "dbc", ",", "List", "<", "CmsResource", ">", "deletedFolders", ",", "CmsResource", "res", ")", "{", "String", "parentPath", "=", "CmsResource", ".", "getParentFolder", "(", "res", ".", "getRootPath", "(", ")", ")", ";", "if", "(", "parentPath", "==", "null", ")", "{", "// resource has no parent", "return", "false", ";", "}", "CmsResource", "parent", ";", "try", "{", "parent", "=", "readResource", "(", "dbc", ",", "parentPath", ",", "CmsResourceFilter", ".", "ALL", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// failure: if we cannot read the parent, we should not publish the resource", "return", "false", ";", "}", "if", "(", "!", "parent", ".", "getState", "(", ")", ".", "isDeleted", "(", ")", ")", "{", "// parent is not deleted", "return", "false", ";", "}", "for", "(", "int", "j", "=", "0", ";", "j", "<", "deletedFolders", ".", "size", "(", ")", ";", "j", "++", ")", "{", "if", "(", "(", "deletedFolders", ".", "get", "(", "j", ")", ")", ".", "getStructureId", "(", ")", ".", "equals", "(", "parent", ".", "getStructureId", "(", ")", ")", ")", "{", "// parent is deleted, and it will get published", "return", "true", ";", "}", "}", "// parent is new, but it will not get published", "return", "false", ";", "}" ]
Checks the parent of a resource during publishing.<p> @param dbc the current database context @param deletedFolders a list of deleted folders @param res a resource to check the parent for @return <code>true</code> if the parent resource will be deleted during publishing
[ "Checks", "the", "parent", "of", "a", "resource", "during", "publishing", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L10730-L10761
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java
GenericGenerators.loadStaticField
public static InsnList loadStaticField(Field field) { """ Load a static field on to the stack. If the static field is of a primitive type, that primitive value will be directly loaded on to the stack (the field won't be referenced). If the static field is an object type, the actual field will be loaded onto the stack. @param field reflection reference to a static field @return instructions to grab the object stored in the static field {@code field} @throws NullPointerException if any argument is {@code null} @throws IllegalArgumentException if {@code field} is not static """ Validate.notNull(field); Validate.isTrue((field.getModifiers() & Modifier.STATIC) != 0); String owner = Type.getInternalName(field.getDeclaringClass()); String name = field.getName(); Type type = Type.getType(field.getType()); field.setAccessible(true); InsnList ret = new InsnList(); switch (type.getSort()) { case Type.BOOLEAN: case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: try { ret.add(new LdcInsnNode(field.getInt(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.LONG: try { ret.add(new LdcInsnNode(field.getLong(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.FLOAT: try { ret.add(new LdcInsnNode(field.getFloat(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.DOUBLE: try { ret.add(new LdcInsnNode(field.getDouble(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.OBJECT: case Type.ARRAY: ret.add(new FieldInsnNode(Opcodes.GETSTATIC, owner, name, type.getDescriptor())); break; default: throw new IllegalStateException(); // should never happen, there is code in Variable/VariableTable to make sure invalid // types aren't set } return ret; }
java
public static InsnList loadStaticField(Field field) { Validate.notNull(field); Validate.isTrue((field.getModifiers() & Modifier.STATIC) != 0); String owner = Type.getInternalName(field.getDeclaringClass()); String name = field.getName(); Type type = Type.getType(field.getType()); field.setAccessible(true); InsnList ret = new InsnList(); switch (type.getSort()) { case Type.BOOLEAN: case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: try { ret.add(new LdcInsnNode(field.getInt(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.LONG: try { ret.add(new LdcInsnNode(field.getLong(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.FLOAT: try { ret.add(new LdcInsnNode(field.getFloat(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.DOUBLE: try { ret.add(new LdcInsnNode(field.getDouble(null))); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); // should never happen } break; case Type.OBJECT: case Type.ARRAY: ret.add(new FieldInsnNode(Opcodes.GETSTATIC, owner, name, type.getDescriptor())); break; default: throw new IllegalStateException(); // should never happen, there is code in Variable/VariableTable to make sure invalid // types aren't set } return ret; }
[ "public", "static", "InsnList", "loadStaticField", "(", "Field", "field", ")", "{", "Validate", ".", "notNull", "(", "field", ")", ";", "Validate", ".", "isTrue", "(", "(", "field", ".", "getModifiers", "(", ")", "&", "Modifier", ".", "STATIC", ")", "!=", "0", ")", ";", "String", "owner", "=", "Type", ".", "getInternalName", "(", "field", ".", "getDeclaringClass", "(", ")", ")", ";", "String", "name", "=", "field", ".", "getName", "(", ")", ";", "Type", "type", "=", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "InsnList", "ret", "=", "new", "InsnList", "(", ")", ";", "switch", "(", "type", ".", "getSort", "(", ")", ")", "{", "case", "Type", ".", "BOOLEAN", ":", "case", "Type", ".", "BYTE", ":", "case", "Type", ".", "CHAR", ":", "case", "Type", ".", "SHORT", ":", "case", "Type", ".", "INT", ":", "try", "{", "ret", ".", "add", "(", "new", "LdcInsnNode", "(", "field", ".", "getInt", "(", "null", ")", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "throw", "new", "IllegalStateException", "(", "iae", ")", ";", "// should never happen", "}", "break", ";", "case", "Type", ".", "LONG", ":", "try", "{", "ret", ".", "add", "(", "new", "LdcInsnNode", "(", "field", ".", "getLong", "(", "null", ")", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "throw", "new", "IllegalStateException", "(", "iae", ")", ";", "// should never happen", "}", "break", ";", "case", "Type", ".", "FLOAT", ":", "try", "{", "ret", ".", "add", "(", "new", "LdcInsnNode", "(", "field", ".", "getFloat", "(", "null", ")", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "throw", "new", "IllegalStateException", "(", "iae", ")", ";", "// should never happen", "}", "break", ";", "case", "Type", ".", "DOUBLE", ":", "try", "{", "ret", ".", "add", "(", "new", "LdcInsnNode", "(", "field", ".", "getDouble", "(", "null", ")", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "throw", "new", "IllegalStateException", "(", "iae", ")", ";", "// should never happen", "}", "break", ";", "case", "Type", ".", "OBJECT", ":", "case", "Type", ".", "ARRAY", ":", "ret", ".", "add", "(", "new", "FieldInsnNode", "(", "Opcodes", ".", "GETSTATIC", ",", "owner", ",", "name", ",", "type", ".", "getDescriptor", "(", ")", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", ")", ";", "// should never happen, there is code in Variable/VariableTable to make sure invalid", "// types aren't set", "}", "return", "ret", ";", "}" ]
Load a static field on to the stack. If the static field is of a primitive type, that primitive value will be directly loaded on to the stack (the field won't be referenced). If the static field is an object type, the actual field will be loaded onto the stack. @param field reflection reference to a static field @return instructions to grab the object stored in the static field {@code field} @throws NullPointerException if any argument is {@code null} @throws IllegalArgumentException if {@code field} is not static
[ "Load", "a", "static", "field", "on", "to", "the", "stack", ".", "If", "the", "static", "field", "is", "of", "a", "primitive", "type", "that", "primitive", "value", "will", "be", "directly", "loaded", "on", "to", "the", "stack", "(", "the", "field", "won", "t", "be", "referenced", ")", ".", "If", "the", "static", "field", "is", "an", "object", "type", "the", "actual", "field", "will", "be", "loaded", "onto", "the", "stack", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java#L472-L526
sd4324530/fastweixin
src/main/java/com/github/sd4324530/fastweixin/util/JsApiUtil.java
JsApiUtil.sign
public static String sign(String jsApiTicket, String nonceStr, long timestame, String url) throws Exception { """ 计算 wx.config() 中需要使用的签名。每个页面都需要进行计算 @param jsApiTicket 微信 js-sdk提供的ticket @param nonceStr 随机字符串 @param timestame 时间戳 @param url 当前网页的URL,不包含#及其后面部分 @return 合法的签名 @throws Exception 获取签名异常 """ Map<String, String> paramMap = new TreeMap<String, String>(); paramMap.put("jsapi_ticket", jsApiTicket); paramMap.put("noncestr", nonceStr); paramMap.put("timestamp", Long.toString(timestame)); paramMap.put("url", url); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : paramMap.entrySet()) { sb.append("&").append(entry.toString()); } return SHA1.getSHA1HexString(sb.substring(1)); }
java
public static String sign(String jsApiTicket, String nonceStr, long timestame, String url) throws Exception { Map<String, String> paramMap = new TreeMap<String, String>(); paramMap.put("jsapi_ticket", jsApiTicket); paramMap.put("noncestr", nonceStr); paramMap.put("timestamp", Long.toString(timestame)); paramMap.put("url", url); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : paramMap.entrySet()) { sb.append("&").append(entry.toString()); } return SHA1.getSHA1HexString(sb.substring(1)); }
[ "public", "static", "String", "sign", "(", "String", "jsApiTicket", ",", "String", "nonceStr", ",", "long", "timestame", ",", "String", "url", ")", "throws", "Exception", "{", "Map", "<", "String", ",", "String", ">", "paramMap", "=", "new", "TreeMap", "<", "String", ",", "String", ">", "(", ")", ";", "paramMap", ".", "put", "(", "\"jsapi_ticket\"", ",", "jsApiTicket", ")", ";", "paramMap", ".", "put", "(", "\"noncestr\"", ",", "nonceStr", ")", ";", "paramMap", ".", "put", "(", "\"timestamp\"", ",", "Long", ".", "toString", "(", "timestame", ")", ")", ";", "paramMap", ".", "put", "(", "\"url\"", ",", "url", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "paramMap", ".", "entrySet", "(", ")", ")", "{", "sb", ".", "append", "(", "\"&\"", ")", ".", "append", "(", "entry", ".", "toString", "(", ")", ")", ";", "}", "return", "SHA1", ".", "getSHA1HexString", "(", "sb", ".", "substring", "(", "1", ")", ")", ";", "}" ]
计算 wx.config() 中需要使用的签名。每个页面都需要进行计算 @param jsApiTicket 微信 js-sdk提供的ticket @param nonceStr 随机字符串 @param timestame 时间戳 @param url 当前网页的URL,不包含#及其后面部分 @return 合法的签名 @throws Exception 获取签名异常
[ "计算", "wx", ".", "config", "()", "中需要使用的签名。每个页面都需要进行计算" ]
train
https://github.com/sd4324530/fastweixin/blob/6bc0a7abfa23aad0dbad4c3123a47a7fb53f3447/src/main/java/com/github/sd4324530/fastweixin/util/JsApiUtil.java#L22-L34
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateTriggerRequest.java
CreateTriggerRequest.withTags
public CreateTriggerRequest withTags(java.util.Map<String, String> tags) { """ <p> The tags to use with this trigger. You may use tags to limit access to the trigger. For more information about tags in AWS Glue, see <a href="http://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">AWS Tags in AWS Glue</a> in the developer guide. </p> @param tags The tags to use with this trigger. You may use tags to limit access to the trigger. For more information about tags in AWS Glue, see <a href="http://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">AWS Tags in AWS Glue</a> in the developer guide. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public CreateTriggerRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateTriggerRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> The tags to use with this trigger. You may use tags to limit access to the trigger. For more information about tags in AWS Glue, see <a href="http://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">AWS Tags in AWS Glue</a> in the developer guide. </p> @param tags The tags to use with this trigger. You may use tags to limit access to the trigger. For more information about tags in AWS Glue, see <a href="http://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">AWS Tags in AWS Glue</a> in the developer guide. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "tags", "to", "use", "with", "this", "trigger", ".", "You", "may", "use", "tags", "to", "limit", "access", "to", "the", "trigger", ".", "For", "more", "information", "about", "tags", "in", "AWS", "Glue", "see", "<a", "href", "=", "http", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "glue", "/", "latest", "/", "dg", "/", "monitor", "-", "tags", ".", "html", ">", "AWS", "Tags", "in", "AWS", "Glue<", "/", "a", ">", "in", "the", "developer", "guide", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateTriggerRequest.java#L528-L531
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuMemPrefetchAsync
public static int cuMemPrefetchAsync(CUdeviceptr devPtr, long count, CUdevice dstDevice, CUstream hStream) { """ Prefetches memory to the specified destination device<br> <br> Prefetches memory to the specified destination device. devPtr is the base device pointer of the memory to be prefetched and dstDevice is the destination device. count specifies the number of bytes to copy. hStream is the stream in which the operation is enqueued.<br> <br> Passing in CU_DEVICE_CPU for dstDevice will prefetch the data to CPU memory.<br> <br> If no physical memory has been allocated for this region, then this memory region will be populated and mapped on the destination device. If there's insufficient memory to prefetch the desired region, the Unified Memory driver may evict pages belonging to other memory regions to make room. If there's no memory that can be evicted, then the Unified Memory driver will prefetch less than what was requested. <br> <br> In the normal case, any mappings to the previous location of the migrated pages are removed and mappings for the new location are only setup on the dstDevice. The application can exercise finer control on these mappings using ::cudaMemAdvise.<br> <br> Note that this function is asynchronous with respect to the host and all work on other devices.<br> @param devPtr Pointer to be prefetched @param count Size in bytes @param dstDevice Destination device to prefetch to @param hStream Stream to enqueue prefetch operation @return CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE @see JCudaDriver#cuMemcpy @see JCudaDriver#cuMemcpyPeer @see JCudaDriver#cuMemcpyAsync @see JCudaDriver#cuMemcpy3DPeerAsync @see JCudaDriver#cuMemAdvise """ return checkResult(cuMemPrefetchAsyncNative(devPtr, count, dstDevice, hStream)); }
java
public static int cuMemPrefetchAsync(CUdeviceptr devPtr, long count, CUdevice dstDevice, CUstream hStream) { return checkResult(cuMemPrefetchAsyncNative(devPtr, count, dstDevice, hStream)); }
[ "public", "static", "int", "cuMemPrefetchAsync", "(", "CUdeviceptr", "devPtr", ",", "long", "count", ",", "CUdevice", "dstDevice", ",", "CUstream", "hStream", ")", "{", "return", "checkResult", "(", "cuMemPrefetchAsyncNative", "(", "devPtr", ",", "count", ",", "dstDevice", ",", "hStream", ")", ")", ";", "}" ]
Prefetches memory to the specified destination device<br> <br> Prefetches memory to the specified destination device. devPtr is the base device pointer of the memory to be prefetched and dstDevice is the destination device. count specifies the number of bytes to copy. hStream is the stream in which the operation is enqueued.<br> <br> Passing in CU_DEVICE_CPU for dstDevice will prefetch the data to CPU memory.<br> <br> If no physical memory has been allocated for this region, then this memory region will be populated and mapped on the destination device. If there's insufficient memory to prefetch the desired region, the Unified Memory driver may evict pages belonging to other memory regions to make room. If there's no memory that can be evicted, then the Unified Memory driver will prefetch less than what was requested. <br> <br> In the normal case, any mappings to the previous location of the migrated pages are removed and mappings for the new location are only setup on the dstDevice. The application can exercise finer control on these mappings using ::cudaMemAdvise.<br> <br> Note that this function is asynchronous with respect to the host and all work on other devices.<br> @param devPtr Pointer to be prefetched @param count Size in bytes @param dstDevice Destination device to prefetch to @param hStream Stream to enqueue prefetch operation @return CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE @see JCudaDriver#cuMemcpy @see JCudaDriver#cuMemcpyPeer @see JCudaDriver#cuMemcpyAsync @see JCudaDriver#cuMemcpy3DPeerAsync @see JCudaDriver#cuMemAdvise
[ "Prefetches", "memory", "to", "the", "specified", "destination", "device<br", ">", "<br", ">", "Prefetches", "memory", "to", "the", "specified", "destination", "device", ".", "devPtr", "is", "the", "base", "device", "pointer", "of", "the", "memory", "to", "be", "prefetched", "and", "dstDevice", "is", "the", "destination", "device", ".", "count", "specifies", "the", "number", "of", "bytes", "to", "copy", ".", "hStream", "is", "the", "stream", "in", "which", "the", "operation", "is", "enqueued", ".", "<br", ">", "<br", ">", "Passing", "in", "CU_DEVICE_CPU", "for", "dstDevice", "will", "prefetch", "the", "data", "to", "CPU", "memory", ".", "<br", ">", "<br", ">", "If", "no", "physical", "memory", "has", "been", "allocated", "for", "this", "region", "then", "this", "memory", "region", "will", "be", "populated", "and", "mapped", "on", "the", "destination", "device", ".", "If", "there", "s", "insufficient", "memory", "to", "prefetch", "the", "desired", "region", "the", "Unified", "Memory", "driver", "may", "evict", "pages", "belonging", "to", "other", "memory", "regions", "to", "make", "room", ".", "If", "there", "s", "no", "memory", "that", "can", "be", "evicted", "then", "the", "Unified", "Memory", "driver", "will", "prefetch", "less", "than", "what", "was", "requested", ".", "<br", ">", "<br", ">", "In", "the", "normal", "case", "any", "mappings", "to", "the", "previous", "location", "of", "the", "migrated", "pages", "are", "removed", "and", "mappings", "for", "the", "new", "location", "are", "only", "setup", "on", "the", "dstDevice", ".", "The", "application", "can", "exercise", "finer", "control", "on", "these", "mappings", "using", "::", "cudaMemAdvise", ".", "<br", ">", "<br", ">", "Note", "that", "this", "function", "is", "asynchronous", "with", "respect", "to", "the", "host", "and", "all", "work", "on", "other", "devices", ".", "<br", ">" ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L14056-L14059
aspectran/aspectran
web/src/main/java/com/aspectran/web/support/multipart/inmemory/MemoryFileItem.java
MemoryFileItem.getString
public String getString() { """ Returns the contents of the file as a String, using the default character encoding. This method uses {@link #get()} to retrieve the contents of the file. @return the contents of the file, as a string """ byte[] rawdata = get(); String charset = getCharSet(); if (charset == null) { charset = DEFAULT_CHARSET; } try { return new String(rawdata, charset); } catch (UnsupportedEncodingException e) { return new String(rawdata); } }
java
public String getString() { byte[] rawdata = get(); String charset = getCharSet(); if (charset == null) { charset = DEFAULT_CHARSET; } try { return new String(rawdata, charset); } catch (UnsupportedEncodingException e) { return new String(rawdata); } }
[ "public", "String", "getString", "(", ")", "{", "byte", "[", "]", "rawdata", "=", "get", "(", ")", ";", "String", "charset", "=", "getCharSet", "(", ")", ";", "if", "(", "charset", "==", "null", ")", "{", "charset", "=", "DEFAULT_CHARSET", ";", "}", "try", "{", "return", "new", "String", "(", "rawdata", ",", "charset", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "return", "new", "String", "(", "rawdata", ")", ";", "}", "}" ]
Returns the contents of the file as a String, using the default character encoding. This method uses {@link #get()} to retrieve the contents of the file. @return the contents of the file, as a string
[ "Returns", "the", "contents", "of", "the", "file", "as", "a", "String", "using", "the", "default", "character", "encoding", ".", "This", "method", "uses", "{", "@link", "#get", "()", "}", "to", "retrieve", "the", "contents", "of", "the", "file", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/web/src/main/java/com/aspectran/web/support/multipart/inmemory/MemoryFileItem.java#L203-L214
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Reflector.java
Reflector.getSetter
public static MethodInstance getSetter(Object obj, String prop, Object value) throws NoSuchMethodException { """ to invoke a setter Method of a Object @param obj Object to invoke method from @param prop Name of the Method without get @param value Value to set to the Method @return MethodInstance @throws NoSuchMethodException @throws PageException """ prop = "set" + StringUtil.ucFirst(prop); MethodInstance mi = getMethodInstance(obj, obj.getClass(), prop, new Object[] { value }); Method m = mi.getMethod(); if (m.getReturnType() != void.class) throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] must have return type void, now [" + m.getReturnType().getName() + "]"); return mi; }
java
public static MethodInstance getSetter(Object obj, String prop, Object value) throws NoSuchMethodException { prop = "set" + StringUtil.ucFirst(prop); MethodInstance mi = getMethodInstance(obj, obj.getClass(), prop, new Object[] { value }); Method m = mi.getMethod(); if (m.getReturnType() != void.class) throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] must have return type void, now [" + m.getReturnType().getName() + "]"); return mi; }
[ "public", "static", "MethodInstance", "getSetter", "(", "Object", "obj", ",", "String", "prop", ",", "Object", "value", ")", "throws", "NoSuchMethodException", "{", "prop", "=", "\"set\"", "+", "StringUtil", ".", "ucFirst", "(", "prop", ")", ";", "MethodInstance", "mi", "=", "getMethodInstance", "(", "obj", ",", "obj", ".", "getClass", "(", ")", ",", "prop", ",", "new", "Object", "[", "]", "{", "value", "}", ")", ";", "Method", "m", "=", "mi", ".", "getMethod", "(", ")", ";", "if", "(", "m", ".", "getReturnType", "(", ")", "!=", "void", ".", "class", ")", "throw", "new", "NoSuchMethodException", "(", "\"invalid return Type, method [\"", "+", "m", ".", "getName", "(", ")", "+", "\"] must have return type void, now [\"", "+", "m", ".", "getReturnType", "(", ")", ".", "getName", "(", ")", "+", "\"]\"", ")", ";", "return", "mi", ";", "}" ]
to invoke a setter Method of a Object @param obj Object to invoke method from @param prop Name of the Method without get @param value Value to set to the Method @return MethodInstance @throws NoSuchMethodException @throws PageException
[ "to", "invoke", "a", "setter", "Method", "of", "a", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Reflector.java#L1016-L1024
twitter/scalding
scalding-core/src/main/java/com/twitter/scalding/tap/GlobHfs.java
GlobHfs.getSize
public static long getSize(Path path, JobConf conf) throws IOException { """ Get the total size of the file(s) specified by the Hfs, which may contain a glob pattern in its path, so we must be ready to handle that case. """ FileSystem fs = path.getFileSystem(conf); FileStatus[] statuses = fs.globStatus(path); if (statuses == null) { throw new FileNotFoundException(String.format("File not found: %s", path)); } long size = 0; for (FileStatus status : statuses) { size += fs.getContentSummary(status.getPath()).getLength(); } return size; }
java
public static long getSize(Path path, JobConf conf) throws IOException { FileSystem fs = path.getFileSystem(conf); FileStatus[] statuses = fs.globStatus(path); if (statuses == null) { throw new FileNotFoundException(String.format("File not found: %s", path)); } long size = 0; for (FileStatus status : statuses) { size += fs.getContentSummary(status.getPath()).getLength(); } return size; }
[ "public", "static", "long", "getSize", "(", "Path", "path", ",", "JobConf", "conf", ")", "throws", "IOException", "{", "FileSystem", "fs", "=", "path", ".", "getFileSystem", "(", "conf", ")", ";", "FileStatus", "[", "]", "statuses", "=", "fs", ".", "globStatus", "(", "path", ")", ";", "if", "(", "statuses", "==", "null", ")", "{", "throw", "new", "FileNotFoundException", "(", "String", ".", "format", "(", "\"File not found: %s\"", ",", "path", ")", ")", ";", "}", "long", "size", "=", "0", ";", "for", "(", "FileStatus", "status", ":", "statuses", ")", "{", "size", "+=", "fs", ".", "getContentSummary", "(", "status", ".", "getPath", "(", ")", ")", ".", "getLength", "(", ")", ";", "}", "return", "size", ";", "}" ]
Get the total size of the file(s) specified by the Hfs, which may contain a glob pattern in its path, so we must be ready to handle that case.
[ "Get", "the", "total", "size", "of", "the", "file", "(", "s", ")", "specified", "by", "the", "Hfs", "which", "may", "contain", "a", "glob", "pattern", "in", "its", "path", "so", "we", "must", "be", "ready", "to", "handle", "that", "case", "." ]
train
https://github.com/twitter/scalding/blob/428b5507279655676e507d52c669c3cbc7812dc0/scalding-core/src/main/java/com/twitter/scalding/tap/GlobHfs.java#L37-L50
apache/flink
flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java
ExceptionUtils.rethrowException
public static void rethrowException(Throwable t, String parentMessage) throws Exception { """ Throws the given {@code Throwable} in scenarios where the signatures do allow to throw a Exception. Errors and Exceptions are thrown directly, other "exotic" subclasses of Throwable are wrapped in an Exception. @param t The throwable to be thrown. @param parentMessage The message for the parent Exception, if one is needed. """ if (t instanceof Error) { throw (Error) t; } else if (t instanceof Exception) { throw (Exception) t; } else { throw new Exception(parentMessage, t); } }
java
public static void rethrowException(Throwable t, String parentMessage) throws Exception { if (t instanceof Error) { throw (Error) t; } else if (t instanceof Exception) { throw (Exception) t; } else { throw new Exception(parentMessage, t); } }
[ "public", "static", "void", "rethrowException", "(", "Throwable", "t", ",", "String", "parentMessage", ")", "throws", "Exception", "{", "if", "(", "t", "instanceof", "Error", ")", "{", "throw", "(", "Error", ")", "t", ";", "}", "else", "if", "(", "t", "instanceof", "Exception", ")", "{", "throw", "(", "Exception", ")", "t", ";", "}", "else", "{", "throw", "new", "Exception", "(", "parentMessage", ",", "t", ")", ";", "}", "}" ]
Throws the given {@code Throwable} in scenarios where the signatures do allow to throw a Exception. Errors and Exceptions are thrown directly, other "exotic" subclasses of Throwable are wrapped in an Exception. @param t The throwable to be thrown. @param parentMessage The message for the parent Exception, if one is needed.
[ "Throws", "the", "given", "{", "@code", "Throwable", "}", "in", "scenarios", "where", "the", "signatures", "do", "allow", "to", "throw", "a", "Exception", ".", "Errors", "and", "Exceptions", "are", "thrown", "directly", "other", "exotic", "subclasses", "of", "Throwable", "are", "wrapped", "in", "an", "Exception", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java#L231-L241
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/base/CPOptionLocalServiceBaseImpl.java
CPOptionLocalServiceBaseImpl.fetchCPOptionByUuidAndGroupId
@Override public CPOption fetchCPOptionByUuidAndGroupId(String uuid, long groupId) { """ Returns the cp option matching the UUID and group. @param uuid the cp option's UUID @param groupId the primary key of the group @return the matching cp option, or <code>null</code> if a matching cp option could not be found """ return cpOptionPersistence.fetchByUUID_G(uuid, groupId); }
java
@Override public CPOption fetchCPOptionByUuidAndGroupId(String uuid, long groupId) { return cpOptionPersistence.fetchByUUID_G(uuid, groupId); }
[ "@", "Override", "public", "CPOption", "fetchCPOptionByUuidAndGroupId", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "cpOptionPersistence", ".", "fetchByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "}" ]
Returns the cp option matching the UUID and group. @param uuid the cp option's UUID @param groupId the primary key of the group @return the matching cp option, or <code>null</code> if a matching cp option could not be found
[ "Returns", "the", "cp", "option", "matching", "the", "UUID", "and", "group", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/base/CPOptionLocalServiceBaseImpl.java#L253-L256
VoltDB/voltdb
src/frontend/org/voltdb/importclient/kinesis/KinesisStreamImporterConfig.java
KinesisStreamImporterConfig.discoverShards
public static List<Shard> discoverShards(String regionName, String streamName, String accessKey, String secretKey, String appName) { """ connect to kinesis stream to discover the shards on the stream @param regionName The region name where the stream resides @param streamName The kinesis stream name @param accessKey The user access key @param secretKey The user secret key @param appName The name of stream application @return a list of shards """ try { Region region = RegionUtils.getRegion(regionName); if (region != null) { final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonKinesis kinesisClient = new AmazonKinesisClient(credentials, getClientConfigWithUserAgent(appName)); kinesisClient.setRegion(region); DescribeStreamResult result = kinesisClient.describeStream(streamName); if (!"ACTIVE".equals(result.getStreamDescription().getStreamStatus())) { throw new IllegalArgumentException("Kinesis stream " + streamName + " is not active."); } return result.getStreamDescription().getShards(); } } catch (ResourceNotFoundException e) { LOGGER.warn("Kinesis stream " + streamName + " does not exist.", e); } catch (Exception e) { LOGGER.warn("Error found while describing the kinesis stream " + streamName, e); } return null; }
java
public static List<Shard> discoverShards(String regionName, String streamName, String accessKey, String secretKey, String appName) { try { Region region = RegionUtils.getRegion(regionName); if (region != null) { final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonKinesis kinesisClient = new AmazonKinesisClient(credentials, getClientConfigWithUserAgent(appName)); kinesisClient.setRegion(region); DescribeStreamResult result = kinesisClient.describeStream(streamName); if (!"ACTIVE".equals(result.getStreamDescription().getStreamStatus())) { throw new IllegalArgumentException("Kinesis stream " + streamName + " is not active."); } return result.getStreamDescription().getShards(); } } catch (ResourceNotFoundException e) { LOGGER.warn("Kinesis stream " + streamName + " does not exist.", e); } catch (Exception e) { LOGGER.warn("Error found while describing the kinesis stream " + streamName, e); } return null; }
[ "public", "static", "List", "<", "Shard", ">", "discoverShards", "(", "String", "regionName", ",", "String", "streamName", ",", "String", "accessKey", ",", "String", "secretKey", ",", "String", "appName", ")", "{", "try", "{", "Region", "region", "=", "RegionUtils", ".", "getRegion", "(", "regionName", ")", ";", "if", "(", "region", "!=", "null", ")", "{", "final", "AWSCredentials", "credentials", "=", "new", "BasicAWSCredentials", "(", "accessKey", ",", "secretKey", ")", ";", "AmazonKinesis", "kinesisClient", "=", "new", "AmazonKinesisClient", "(", "credentials", ",", "getClientConfigWithUserAgent", "(", "appName", ")", ")", ";", "kinesisClient", ".", "setRegion", "(", "region", ")", ";", "DescribeStreamResult", "result", "=", "kinesisClient", ".", "describeStream", "(", "streamName", ")", ";", "if", "(", "!", "\"ACTIVE\"", ".", "equals", "(", "result", ".", "getStreamDescription", "(", ")", ".", "getStreamStatus", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Kinesis stream \"", "+", "streamName", "+", "\" is not active.\"", ")", ";", "}", "return", "result", ".", "getStreamDescription", "(", ")", ".", "getShards", "(", ")", ";", "}", "}", "catch", "(", "ResourceNotFoundException", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"Kinesis stream \"", "+", "streamName", "+", "\" does not exist.\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"Error found while describing the kinesis stream \"", "+", "streamName", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
connect to kinesis stream to discover the shards on the stream @param regionName The region name where the stream resides @param streamName The kinesis stream name @param accessKey The user access key @param secretKey The user secret key @param appName The name of stream application @return a list of shards
[ "connect", "to", "kinesis", "stream", "to", "discover", "the", "shards", "on", "the", "stream" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/importclient/kinesis/KinesisStreamImporterConfig.java#L185-L207
landawn/AbacusUtil
src/com/landawn/abacus/util/Fn.java
Fn.sf
@Beta public static <T, U, R> BiFunction<T, U, R> sf(final Object mutex, final BiFunction<T, U, R> biFunction) { """ Synchronized {@code BiFunction} @param mutex to synchronized on @param biFunction @return """ N.checkArgNotNull(mutex, "mutex"); N.checkArgNotNull(biFunction, "biFunction"); return new BiFunction<T, U, R>() { @Override public R apply(T t, U u) { synchronized (mutex) { return biFunction.apply(t, u); } } }; }
java
@Beta public static <T, U, R> BiFunction<T, U, R> sf(final Object mutex, final BiFunction<T, U, R> biFunction) { N.checkArgNotNull(mutex, "mutex"); N.checkArgNotNull(biFunction, "biFunction"); return new BiFunction<T, U, R>() { @Override public R apply(T t, U u) { synchronized (mutex) { return biFunction.apply(t, u); } } }; }
[ "@", "Beta", "public", "static", "<", "T", ",", "U", ",", "R", ">", "BiFunction", "<", "T", ",", "U", ",", "R", ">", "sf", "(", "final", "Object", "mutex", ",", "final", "BiFunction", "<", "T", ",", "U", ",", "R", ">", "biFunction", ")", "{", "N", ".", "checkArgNotNull", "(", "mutex", ",", "\"mutex\"", ")", ";", "N", ".", "checkArgNotNull", "(", "biFunction", ",", "\"biFunction\"", ")", ";", "return", "new", "BiFunction", "<", "T", ",", "U", ",", "R", ">", "(", ")", "{", "@", "Override", "public", "R", "apply", "(", "T", "t", ",", "U", "u", ")", "{", "synchronized", "(", "mutex", ")", "{", "return", "biFunction", ".", "apply", "(", "t", ",", "u", ")", ";", "}", "}", "}", ";", "}" ]
Synchronized {@code BiFunction} @param mutex to synchronized on @param biFunction @return
[ "Synchronized", "{", "@code", "BiFunction", "}" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Fn.java#L2953-L2966
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java
CPDefinitionPersistenceImpl.removeByUUID_G
@Override public CPDefinition removeByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionException { """ Removes the cp definition where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp definition that was removed """ CPDefinition cpDefinition = findByUUID_G(uuid, groupId); return remove(cpDefinition); }
java
@Override public CPDefinition removeByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionException { CPDefinition cpDefinition = findByUUID_G(uuid, groupId); return remove(cpDefinition); }
[ "@", "Override", "public", "CPDefinition", "removeByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPDefinitionException", "{", "CPDefinition", "cpDefinition", "=", "findByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "return", "remove", "(", "cpDefinition", ")", ";", "}" ]
Removes the cp definition where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp definition that was removed
[ "Removes", "the", "cp", "definition", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java#L809-L815
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/selector/impl/ParseUtil.java
ParseUtil.convertRange
static Selector convertRange(Selector expr, Selector bound1, Selector bound2) { """ Convert a partially parsed BETWEEN expression into its more primitive form as a conjunction of inequalities. @param expr the expression whose range is being tested @param bound1 the lower bound @param bound2 the upper bound @return a Selector representing the BETWEEN expression its more primitive form """ return new OperatorImpl(Operator.AND, new OperatorImpl(Operator.GE, (Selector) expr.clone(), bound1), new OperatorImpl(Operator.LE, (Selector) expr.clone(), bound2)); }
java
static Selector convertRange(Selector expr, Selector bound1, Selector bound2) { return new OperatorImpl(Operator.AND, new OperatorImpl(Operator.GE, (Selector) expr.clone(), bound1), new OperatorImpl(Operator.LE, (Selector) expr.clone(), bound2)); }
[ "static", "Selector", "convertRange", "(", "Selector", "expr", ",", "Selector", "bound1", ",", "Selector", "bound2", ")", "{", "return", "new", "OperatorImpl", "(", "Operator", ".", "AND", ",", "new", "OperatorImpl", "(", "Operator", ".", "GE", ",", "(", "Selector", ")", "expr", ".", "clone", "(", ")", ",", "bound1", ")", ",", "new", "OperatorImpl", "(", "Operator", ".", "LE", ",", "(", "Selector", ")", "expr", ".", "clone", "(", ")", ",", "bound2", ")", ")", ";", "}" ]
Convert a partially parsed BETWEEN expression into its more primitive form as a conjunction of inequalities. @param expr the expression whose range is being tested @param bound1 the lower bound @param bound2 the upper bound @return a Selector representing the BETWEEN expression its more primitive form
[ "Convert", "a", "partially", "parsed", "BETWEEN", "expression", "into", "its", "more", "primitive", "form", "as", "a", "conjunction", "of", "inequalities", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/selector/impl/ParseUtil.java#L124-L128
Metatavu/edelphi
rest/src/main/java/fi/metatavu/edelphi/permissions/PermissionController.java
PermissionController.hasPanelAccess
public boolean hasPanelAccess(Panel panel, User user, DelfoiActionName actionName) { """ Returns whether user has required panel action access @param panel panel @param user user @param actionName action @return whether user role required action access """ if (panel == null) { logger.warn("Panel was null when checking panel access"); return false; } if (user == null) { logger.warn("User was null when checking panel access"); return false; } if (isSuperUser(user)) { return true; } UserRole userRole = getPanelRole(user, panel); if (userRole == null) { return false; } DelfoiAction action = delfoiActionDAO.findByActionName(actionName.toString()); if (action == null) { logger.info(String.format("ActionUtils.hasDelfoiAccess - undefined action: '%s'", actionName)); return false; } return hasPanelAccess(panel, action, userRole); }
java
public boolean hasPanelAccess(Panel panel, User user, DelfoiActionName actionName) { if (panel == null) { logger.warn("Panel was null when checking panel access"); return false; } if (user == null) { logger.warn("User was null when checking panel access"); return false; } if (isSuperUser(user)) { return true; } UserRole userRole = getPanelRole(user, panel); if (userRole == null) { return false; } DelfoiAction action = delfoiActionDAO.findByActionName(actionName.toString()); if (action == null) { logger.info(String.format("ActionUtils.hasDelfoiAccess - undefined action: '%s'", actionName)); return false; } return hasPanelAccess(panel, action, userRole); }
[ "public", "boolean", "hasPanelAccess", "(", "Panel", "panel", ",", "User", "user", ",", "DelfoiActionName", "actionName", ")", "{", "if", "(", "panel", "==", "null", ")", "{", "logger", ".", "warn", "(", "\"Panel was null when checking panel access\"", ")", ";", "return", "false", ";", "}", "if", "(", "user", "==", "null", ")", "{", "logger", ".", "warn", "(", "\"User was null when checking panel access\"", ")", ";", "return", "false", ";", "}", "if", "(", "isSuperUser", "(", "user", ")", ")", "{", "return", "true", ";", "}", "UserRole", "userRole", "=", "getPanelRole", "(", "user", ",", "panel", ")", ";", "if", "(", "userRole", "==", "null", ")", "{", "return", "false", ";", "}", "DelfoiAction", "action", "=", "delfoiActionDAO", ".", "findByActionName", "(", "actionName", ".", "toString", "(", ")", ")", ";", "if", "(", "action", "==", "null", ")", "{", "logger", ".", "info", "(", "String", ".", "format", "(", "\"ActionUtils.hasDelfoiAccess - undefined action: '%s'\"", ",", "actionName", ")", ")", ";", "return", "false", ";", "}", "return", "hasPanelAccess", "(", "panel", ",", "action", ",", "userRole", ")", ";", "}" ]
Returns whether user has required panel action access @param panel panel @param user user @param actionName action @return whether user role required action access
[ "Returns", "whether", "user", "has", "required", "panel", "action", "access" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/rest/src/main/java/fi/metatavu/edelphi/permissions/PermissionController.java#L85-L113
goldmansachs/reladomo
reladomo/src/main/java/com/gs/fw/common/mithra/connectionmanager/MithraPoolableConnectionFactory.java
MithraPoolableConnectionFactory.makeObject
@Override public Connection makeObject(ObjectPoolWithThreadAffinity<Connection> pool) throws Exception { """ overriding to remove synchronized. We never mutate any state that affects this method """ Connection conn = connectionFactory.createConnection(); return new PooledConnection(conn, pool, this.statementsToPool); }
java
@Override public Connection makeObject(ObjectPoolWithThreadAffinity<Connection> pool) throws Exception { Connection conn = connectionFactory.createConnection(); return new PooledConnection(conn, pool, this.statementsToPool); }
[ "@", "Override", "public", "Connection", "makeObject", "(", "ObjectPoolWithThreadAffinity", "<", "Connection", ">", "pool", ")", "throws", "Exception", "{", "Connection", "conn", "=", "connectionFactory", ".", "createConnection", "(", ")", ";", "return", "new", "PooledConnection", "(", "conn", ",", "pool", ",", "this", ".", "statementsToPool", ")", ";", "}" ]
overriding to remove synchronized. We never mutate any state that affects this method
[ "overriding", "to", "remove", "synchronized", ".", "We", "never", "mutate", "any", "state", "that", "affects", "this", "method" ]
train
https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/connectionmanager/MithraPoolableConnectionFactory.java#L41-L46
infinispan/infinispan
lucene/lucene-directory/src/main/java/org/infinispan/lucene/impl/TransactionalSharedLuceneLock.java
TransactionalSharedLuceneLock.startTransaction
private void startTransaction() throws IOException { """ Starts a new transaction. Used to batch changes in LuceneDirectory: a transaction is created at lock acquire, and closed on release. It's also committed and started again at each IndexWriter.commit(); @throws IOException wraps Infinispan exceptions to adapt to Lucene's API """ try { tm.begin(); } catch (Exception e) { log.unableToStartTransaction(e); throw new IOException("SharedLuceneLock could not start a transaction after having acquired the lock", e); } if (trace) { log.tracef("Batch transaction started for index: %s", indexName); } }
java
private void startTransaction() throws IOException { try { tm.begin(); } catch (Exception e) { log.unableToStartTransaction(e); throw new IOException("SharedLuceneLock could not start a transaction after having acquired the lock", e); } if (trace) { log.tracef("Batch transaction started for index: %s", indexName); } }
[ "private", "void", "startTransaction", "(", ")", "throws", "IOException", "{", "try", "{", "tm", ".", "begin", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "unableToStartTransaction", "(", "e", ")", ";", "throw", "new", "IOException", "(", "\"SharedLuceneLock could not start a transaction after having acquired the lock\"", ",", "e", ")", ";", "}", "if", "(", "trace", ")", "{", "log", ".", "tracef", "(", "\"Batch transaction started for index: %s\"", ",", "indexName", ")", ";", "}", "}" ]
Starts a new transaction. Used to batch changes in LuceneDirectory: a transaction is created at lock acquire, and closed on release. It's also committed and started again at each IndexWriter.commit(); @throws IOException wraps Infinispan exceptions to adapt to Lucene's API
[ "Starts", "a", "new", "transaction", ".", "Used", "to", "batch", "changes", "in", "LuceneDirectory", ":", "a", "transaction", "is", "created", "at", "lock", "acquire", "and", "closed", "on", "release", ".", "It", "s", "also", "committed", "and", "started", "again", "at", "each", "IndexWriter", ".", "commit", "()", ";" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lucene/lucene-directory/src/main/java/org/infinispan/lucene/impl/TransactionalSharedLuceneLock.java#L109-L120
OpenLiberty/open-liberty
dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixUtils.java
IFixUtils.getExistingMatchingIfixID
private static String getExistingMatchingIfixID(BundleFile bundleFile, Set<String> existingIDs, Map<String, BundleFile> bundleFiles) { """ This method takes a ifix ID finds any existing IFix IDs that refer to the same base bundle. Because the ifix jars will have different qualifiers, we need to be able to work out which ids are related. @param bundleFile - The bundleFile that maps to the current jar file we're processing. @param existingIDs - A Set of Strings that represent the existing updateIds. @param bundleFiles - All the known bundleFile objects. @return - The existing key that maps to the same base bundle. """ String existingIfixKey = null; // Iterate over the known ids. for (String existingID : existingIDs) { // If we have a corresponding BundleFile for the existing ID, we need to check it matches the currently processed file. if (bundleFiles.containsKey(existingID)) { BundleFile existingBundleFile = bundleFiles.get(existingID); // If our symbolic name match the supplied BundleFile then move on to the version checking. if (bundleFile.getSymbolicName().equals(existingBundleFile.getSymbolicName())) { //Get the versions of both the checking bundle and the existing bundle. Check that the version, excluding the qualifier match // and if they do, we have a match. Version existingBundleVersion = new Version(existingBundleFile.getVersion()); Version bundleVersion = new Version(bundleFile.getVersion()); if (bundleVersion.getMajor() == existingBundleVersion.getMajor() && bundleVersion.getMinor() == existingBundleVersion.getMinor() && bundleVersion.getMicro() == existingBundleVersion.getMicro()) existingIfixKey = existingID; } } } return existingIfixKey; }
java
private static String getExistingMatchingIfixID(BundleFile bundleFile, Set<String> existingIDs, Map<String, BundleFile> bundleFiles) { String existingIfixKey = null; // Iterate over the known ids. for (String existingID : existingIDs) { // If we have a corresponding BundleFile for the existing ID, we need to check it matches the currently processed file. if (bundleFiles.containsKey(existingID)) { BundleFile existingBundleFile = bundleFiles.get(existingID); // If our symbolic name match the supplied BundleFile then move on to the version checking. if (bundleFile.getSymbolicName().equals(existingBundleFile.getSymbolicName())) { //Get the versions of both the checking bundle and the existing bundle. Check that the version, excluding the qualifier match // and if they do, we have a match. Version existingBundleVersion = new Version(existingBundleFile.getVersion()); Version bundleVersion = new Version(bundleFile.getVersion()); if (bundleVersion.getMajor() == existingBundleVersion.getMajor() && bundleVersion.getMinor() == existingBundleVersion.getMinor() && bundleVersion.getMicro() == existingBundleVersion.getMicro()) existingIfixKey = existingID; } } } return existingIfixKey; }
[ "private", "static", "String", "getExistingMatchingIfixID", "(", "BundleFile", "bundleFile", ",", "Set", "<", "String", ">", "existingIDs", ",", "Map", "<", "String", ",", "BundleFile", ">", "bundleFiles", ")", "{", "String", "existingIfixKey", "=", "null", ";", "// Iterate over the known ids.", "for", "(", "String", "existingID", ":", "existingIDs", ")", "{", "// If we have a corresponding BundleFile for the existing ID, we need to check it matches the currently processed file.", "if", "(", "bundleFiles", ".", "containsKey", "(", "existingID", ")", ")", "{", "BundleFile", "existingBundleFile", "=", "bundleFiles", ".", "get", "(", "existingID", ")", ";", "// If our symbolic name match the supplied BundleFile then move on to the version checking.", "if", "(", "bundleFile", ".", "getSymbolicName", "(", ")", ".", "equals", "(", "existingBundleFile", ".", "getSymbolicName", "(", ")", ")", ")", "{", "//Get the versions of both the checking bundle and the existing bundle. Check that the version, excluding the qualifier match", "// and if they do, we have a match.", "Version", "existingBundleVersion", "=", "new", "Version", "(", "existingBundleFile", ".", "getVersion", "(", ")", ")", ";", "Version", "bundleVersion", "=", "new", "Version", "(", "bundleFile", ".", "getVersion", "(", ")", ")", ";", "if", "(", "bundleVersion", ".", "getMajor", "(", ")", "==", "existingBundleVersion", ".", "getMajor", "(", ")", "&&", "bundleVersion", ".", "getMinor", "(", ")", "==", "existingBundleVersion", ".", "getMinor", "(", ")", "&&", "bundleVersion", ".", "getMicro", "(", ")", "==", "existingBundleVersion", ".", "getMicro", "(", ")", ")", "existingIfixKey", "=", "existingID", ";", "}", "}", "}", "return", "existingIfixKey", ";", "}" ]
This method takes a ifix ID finds any existing IFix IDs that refer to the same base bundle. Because the ifix jars will have different qualifiers, we need to be able to work out which ids are related. @param bundleFile - The bundleFile that maps to the current jar file we're processing. @param existingIDs - A Set of Strings that represent the existing updateIds. @param bundleFiles - All the known bundleFile objects. @return - The existing key that maps to the same base bundle.
[ "This", "method", "takes", "a", "ifix", "ID", "finds", "any", "existing", "IFix", "IDs", "that", "refer", "to", "the", "same", "base", "bundle", ".", "Because", "the", "ifix", "jars", "will", "have", "different", "qualifiers", "we", "need", "to", "be", "able", "to", "work", "out", "which", "ids", "are", "related", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixUtils.java#L489-L510
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/Checks.java
Checks.ensure
public static void ensure(boolean condition, String errorMessageFormat, Object... errorMessageArgs) { """ Throws a GrammarException if the given condition is not met. @param condition the condition @param errorMessageFormat the error message format @param errorMessageArgs the error message arguments """ if (!condition) { throw new GrammarException(errorMessageFormat, errorMessageArgs); } }
java
public static void ensure(boolean condition, String errorMessageFormat, Object... errorMessageArgs) { if (!condition) { throw new GrammarException(errorMessageFormat, errorMessageArgs); } }
[ "public", "static", "void", "ensure", "(", "boolean", "condition", ",", "String", "errorMessageFormat", ",", "Object", "...", "errorMessageArgs", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "GrammarException", "(", "errorMessageFormat", ",", "errorMessageArgs", ")", ";", "}", "}" ]
Throws a GrammarException if the given condition is not met. @param condition the condition @param errorMessageFormat the error message format @param errorMessageArgs the error message arguments
[ "Throws", "a", "GrammarException", "if", "the", "given", "condition", "is", "not", "met", "." ]
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/Checks.java#L35-L39
trellis-ldp/trellis
components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResource.java
TriplestoreResource.fetchIndirectMemberQuads
private Stream<Quad> fetchIndirectMemberQuads() { """ This code is equivalent to the SPARQL query below. <p><pre><code> SELECT ?subject ?predicate ?object WHERE { GRAPH trellis:PreferServerManaged { ?s ldp:member IDENTIFIER ?s ldp:membershipResource ?subject AND ?s rdf:type ldp:IndirectContainer AND ?s ldp:membershipRelation ?predicate AND ?s ldp:insertedContentRelation ?o AND ?res dc:isPartOf ?s . } GRAPH ?res { ?res ?o ?object } } </code></pre> """ final Var s = Var.alloc("s"); final Var o = Var.alloc("o"); final Var res = Var.alloc("res"); final Query q = new Query(); q.setQuerySelectType(); q.addResultVar(SUBJECT); q.addResultVar(PREDICATE); q.addResultVar(OBJECT); final ElementPathBlock epb1 = new ElementPathBlock(); epb1.addTriple(create(s, rdf.asJenaNode(LDP.member), rdf.asJenaNode(identifier))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.membershipResource), SUBJECT)); epb1.addTriple(create(s, rdf.asJenaNode(RDF.type), rdf.asJenaNode(LDP.IndirectContainer))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.hasMemberRelation), PREDICATE)); epb1.addTriple(create(s, rdf.asJenaNode(LDP.insertedContentRelation), o)); epb1.addTriple(create(res, rdf.asJenaNode(DC.isPartOf), s)); final ElementPathBlock epb2 = new ElementPathBlock(); epb2.addTriple(create(res, o, OBJECT)); final ElementGroup elg = new ElementGroup(); elg.addElement(new ElementNamedGraph(rdf.asJenaNode(Trellis.PreferServerManaged), epb1)); elg.addElement(new ElementNamedGraph(res, epb2)); q.setQueryPattern(elg); final Stream.Builder<Quad> builder = builder(); rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(LDP.PreferMembership, getSubject(qs), getPredicate(qs), getObject(qs)))); return builder.build(); }
java
private Stream<Quad> fetchIndirectMemberQuads() { final Var s = Var.alloc("s"); final Var o = Var.alloc("o"); final Var res = Var.alloc("res"); final Query q = new Query(); q.setQuerySelectType(); q.addResultVar(SUBJECT); q.addResultVar(PREDICATE); q.addResultVar(OBJECT); final ElementPathBlock epb1 = new ElementPathBlock(); epb1.addTriple(create(s, rdf.asJenaNode(LDP.member), rdf.asJenaNode(identifier))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.membershipResource), SUBJECT)); epb1.addTriple(create(s, rdf.asJenaNode(RDF.type), rdf.asJenaNode(LDP.IndirectContainer))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.hasMemberRelation), PREDICATE)); epb1.addTriple(create(s, rdf.asJenaNode(LDP.insertedContentRelation), o)); epb1.addTriple(create(res, rdf.asJenaNode(DC.isPartOf), s)); final ElementPathBlock epb2 = new ElementPathBlock(); epb2.addTriple(create(res, o, OBJECT)); final ElementGroup elg = new ElementGroup(); elg.addElement(new ElementNamedGraph(rdf.asJenaNode(Trellis.PreferServerManaged), epb1)); elg.addElement(new ElementNamedGraph(res, epb2)); q.setQueryPattern(elg); final Stream.Builder<Quad> builder = builder(); rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(LDP.PreferMembership, getSubject(qs), getPredicate(qs), getObject(qs)))); return builder.build(); }
[ "private", "Stream", "<", "Quad", ">", "fetchIndirectMemberQuads", "(", ")", "{", "final", "Var", "s", "=", "Var", ".", "alloc", "(", "\"s\"", ")", ";", "final", "Var", "o", "=", "Var", ".", "alloc", "(", "\"o\"", ")", ";", "final", "Var", "res", "=", "Var", ".", "alloc", "(", "\"res\"", ")", ";", "final", "Query", "q", "=", "new", "Query", "(", ")", ";", "q", ".", "setQuerySelectType", "(", ")", ";", "q", ".", "addResultVar", "(", "SUBJECT", ")", ";", "q", ".", "addResultVar", "(", "PREDICATE", ")", ";", "q", ".", "addResultVar", "(", "OBJECT", ")", ";", "final", "ElementPathBlock", "epb1", "=", "new", "ElementPathBlock", "(", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "s", ",", "rdf", ".", "asJenaNode", "(", "LDP", ".", "member", ")", ",", "rdf", ".", "asJenaNode", "(", "identifier", ")", ")", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "s", ",", "rdf", ".", "asJenaNode", "(", "LDP", ".", "membershipResource", ")", ",", "SUBJECT", ")", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "s", ",", "rdf", ".", "asJenaNode", "(", "RDF", ".", "type", ")", ",", "rdf", ".", "asJenaNode", "(", "LDP", ".", "IndirectContainer", ")", ")", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "s", ",", "rdf", ".", "asJenaNode", "(", "LDP", ".", "hasMemberRelation", ")", ",", "PREDICATE", ")", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "s", ",", "rdf", ".", "asJenaNode", "(", "LDP", ".", "insertedContentRelation", ")", ",", "o", ")", ")", ";", "epb1", ".", "addTriple", "(", "create", "(", "res", ",", "rdf", ".", "asJenaNode", "(", "DC", ".", "isPartOf", ")", ",", "s", ")", ")", ";", "final", "ElementPathBlock", "epb2", "=", "new", "ElementPathBlock", "(", ")", ";", "epb2", ".", "addTriple", "(", "create", "(", "res", ",", "o", ",", "OBJECT", ")", ")", ";", "final", "ElementGroup", "elg", "=", "new", "ElementGroup", "(", ")", ";", "elg", ".", "addElement", "(", "new", "ElementNamedGraph", "(", "rdf", ".", "asJenaNode", "(", "Trellis", ".", "PreferServerManaged", ")", ",", "epb1", ")", ")", ";", "elg", ".", "addElement", "(", "new", "ElementNamedGraph", "(", "res", ",", "epb2", ")", ")", ";", "q", ".", "setQueryPattern", "(", "elg", ")", ";", "final", "Stream", ".", "Builder", "<", "Quad", ">", "builder", "=", "builder", "(", ")", ";", "rdfConnection", ".", "querySelect", "(", "q", ",", "qs", "->", "builder", ".", "accept", "(", "rdf", ".", "createQuad", "(", "LDP", ".", "PreferMembership", ",", "getSubject", "(", "qs", ")", ",", "getPredicate", "(", "qs", ")", ",", "getObject", "(", "qs", ")", ")", ")", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
This code is equivalent to the SPARQL query below. <p><pre><code> SELECT ?subject ?predicate ?object WHERE { GRAPH trellis:PreferServerManaged { ?s ldp:member IDENTIFIER ?s ldp:membershipResource ?subject AND ?s rdf:type ldp:IndirectContainer AND ?s ldp:membershipRelation ?predicate AND ?s ldp:insertedContentRelation ?o AND ?res dc:isPartOf ?s . } GRAPH ?res { ?res ?o ?object } } </code></pre>
[ "This", "code", "is", "equivalent", "to", "the", "SPARQL", "query", "below", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResource.java#L319-L351
jhalterman/failsafe
src/main/java/net/jodah/failsafe/RetryPolicy.java
RetryPolicy.canApplyDelayFn
public boolean canApplyDelayFn(R result, Throwable failure) { """ Returns whether any configured delay function can be applied for an execution result. @see #withDelay(DelayFunction) @see #withDelayOn(DelayFunction, Class) @see #withDelayWhen(DelayFunction, Object) """ return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null && delayFailure.isAssignableFrom(failure.getClass()))); }
java
public boolean canApplyDelayFn(R result, Throwable failure) { return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null && delayFailure.isAssignableFrom(failure.getClass()))); }
[ "public", "boolean", "canApplyDelayFn", "(", "R", "result", ",", "Throwable", "failure", ")", "{", "return", "(", "delayResult", "==", "null", "||", "delayResult", ".", "equals", "(", "result", ")", ")", "&&", "(", "delayFailure", "==", "null", "||", "(", "failure", "!=", "null", "&&", "delayFailure", ".", "isAssignableFrom", "(", "failure", ".", "getClass", "(", ")", ")", ")", ")", ";", "}" ]
Returns whether any configured delay function can be applied for an execution result. @see #withDelay(DelayFunction) @see #withDelayOn(DelayFunction, Class) @see #withDelayWhen(DelayFunction, Object)
[ "Returns", "whether", "any", "configured", "delay", "function", "can", "be", "applied", "for", "an", "execution", "result", "." ]
train
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/RetryPolicy.java#L296-L299
googleads/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java
DateTimesHelper.toCalendar
public Calendar toCalendar(T dateTime, Locale locale) { """ Gets a calendar for a {@code DateTime} in the supplied locale. """ return toDateTime(dateTime).toCalendar(locale); }
java
public Calendar toCalendar(T dateTime, Locale locale) { return toDateTime(dateTime).toCalendar(locale); }
[ "public", "Calendar", "toCalendar", "(", "T", "dateTime", ",", "Locale", "locale", ")", "{", "return", "toDateTime", "(", "dateTime", ")", ".", "toCalendar", "(", "locale", ")", ";", "}" ]
Gets a calendar for a {@code DateTime} in the supplied locale.
[ "Gets", "a", "calendar", "for", "a", "{" ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java#L184-L186
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/util/BranchEvent.java
BranchEvent.addCustomDataProperty
public BranchEvent addCustomDataProperty(String propertyName, String propertyValue) { """ Adds a custom data property associated with this Branch Event @param propertyName {@link String} Name of the custom property @param propertyValue {@link String} Value of the custom property @return This object for chaining builder methods """ try { this.customProperties.put(propertyName, propertyValue); } catch (JSONException e) { e.printStackTrace(); } return this; }
java
public BranchEvent addCustomDataProperty(String propertyName, String propertyValue) { try { this.customProperties.put(propertyName, propertyValue); } catch (JSONException e) { e.printStackTrace(); } return this; }
[ "public", "BranchEvent", "addCustomDataProperty", "(", "String", "propertyName", ",", "String", "propertyValue", ")", "{", "try", "{", "this", ".", "customProperties", ".", "put", "(", "propertyName", ",", "propertyValue", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "this", ";", "}" ]
Adds a custom data property associated with this Branch Event @param propertyName {@link String} Name of the custom property @param propertyValue {@link String} Value of the custom property @return This object for chaining builder methods
[ "Adds", "a", "custom", "data", "property", "associated", "with", "this", "Branch", "Event" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/util/BranchEvent.java#L183-L190
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/model/Interval.java
Interval.withZoneId
public Interval withZoneId(ZoneId zone) { """ Returns a new interval based on this interval but with a different time zone id. @param zone the new time zone @return a new interval """ requireNonNull(zone); return new Interval(startDate, startTime, endDate, endTime, zone); }
java
public Interval withZoneId(ZoneId zone) { requireNonNull(zone); return new Interval(startDate, startTime, endDate, endTime, zone); }
[ "public", "Interval", "withZoneId", "(", "ZoneId", "zone", ")", "{", "requireNonNull", "(", "zone", ")", ";", "return", "new", "Interval", "(", "startDate", ",", "startTime", ",", "endDate", ",", "endTime", ",", "zone", ")", ";", "}" ]
Returns a new interval based on this interval but with a different time zone id. @param zone the new time zone @return a new interval
[ "Returns", "a", "new", "interval", "based", "on", "this", "interval", "but", "with", "a", "different", "time", "zone", "id", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Interval.java#L391-L394
tango-controls/JTango
dao/src/main/java/fr/esrf/TangoDs/TemplCommand.java
TemplCommand.is_allowed
public boolean is_allowed(DeviceImpl dev,Any data_in) { """ Invoke the command allowed method given at object creation time. This method is automtically called by the TANGO core classes when the associated command is requested by a client to check if the command is allowed in the actual device state. If the user give a command allowed method at object creation time, this method will be invoked. @param dev The device on which the command must be executed @param data_in The incoming data still packed in a CORBA Any object. For command created with this TemplCommand class, this Any object does not contain data @return A boolean set to true is the command is allowed. Otherwise, the return value is false. This return value is always set to true if the user does not supply a method to be excuted. If a method has been supplied, the return value is the value returned by the user supplied mehod. """ if (state_method == null) return true; else { // // If the Method reference is not null, execute the method with the invoke // method // try { java.lang.Object[] meth_param = new java.lang.Object[1]; meth_param[0] = data_in; java.lang.Object obj = state_method.invoke(dev,meth_param); return (Boolean) obj; } catch(InvocationTargetException e) { return false; } catch(IllegalArgumentException e) { return false; } catch (IllegalAccessException e) { return false; } } }
java
public boolean is_allowed(DeviceImpl dev,Any data_in) { if (state_method == null) return true; else { // // If the Method reference is not null, execute the method with the invoke // method // try { java.lang.Object[] meth_param = new java.lang.Object[1]; meth_param[0] = data_in; java.lang.Object obj = state_method.invoke(dev,meth_param); return (Boolean) obj; } catch(InvocationTargetException e) { return false; } catch(IllegalArgumentException e) { return false; } catch (IllegalAccessException e) { return false; } } }
[ "public", "boolean", "is_allowed", "(", "DeviceImpl", "dev", ",", "Any", "data_in", ")", "{", "if", "(", "state_method", "==", "null", ")", "return", "true", ";", "else", "{", "//", "// If the Method reference is not null, execute the method with the invoke", "// method", "//", "try", "{", "java", ".", "lang", ".", "Object", "[", "]", "meth_param", "=", "new", "java", ".", "lang", ".", "Object", "[", "1", "]", ";", "meth_param", "[", "0", "]", "=", "data_in", ";", "java", ".", "lang", ".", "Object", "obj", "=", "state_method", ".", "invoke", "(", "dev", ",", "meth_param", ")", ";", "return", "(", "Boolean", ")", "obj", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "return", "false", ";", "}", "}", "}" ]
Invoke the command allowed method given at object creation time. This method is automtically called by the TANGO core classes when the associated command is requested by a client to check if the command is allowed in the actual device state. If the user give a command allowed method at object creation time, this method will be invoked. @param dev The device on which the command must be executed @param data_in The incoming data still packed in a CORBA Any object. For command created with this TemplCommand class, this Any object does not contain data @return A boolean set to true is the command is allowed. Otherwise, the return value is false. This return value is always set to true if the user does not supply a method to be excuted. If a method has been supplied, the return value is the value returned by the user supplied mehod.
[ "Invoke", "the", "command", "allowed", "method", "given", "at", "object", "creation", "time", "." ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/dao/src/main/java/fr/esrf/TangoDs/TemplCommand.java#L889-L921
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisUtil.java
CmsCmisUtil.addPropertyId
public static void addPropertyId( CmsCmisTypeManager typeManager, PropertiesImpl props, String typeId, Set<String> filter, String id, String value) { """ Helper method for adding an id-valued property.<p> @param typeManager the type manager @param props the properties to add to @param typeId the type id @param filter the property filter @param id the property id @param value the property value """ if (!checkAddProperty(typeManager, props, typeId, filter, id)) { return; } PropertyIdImpl result = new PropertyIdImpl(id, value); result.setQueryName(id); props.addProperty(result); }
java
public static void addPropertyId( CmsCmisTypeManager typeManager, PropertiesImpl props, String typeId, Set<String> filter, String id, String value) { if (!checkAddProperty(typeManager, props, typeId, filter, id)) { return; } PropertyIdImpl result = new PropertyIdImpl(id, value); result.setQueryName(id); props.addProperty(result); }
[ "public", "static", "void", "addPropertyId", "(", "CmsCmisTypeManager", "typeManager", ",", "PropertiesImpl", "props", ",", "String", "typeId", ",", "Set", "<", "String", ">", "filter", ",", "String", "id", ",", "String", "value", ")", "{", "if", "(", "!", "checkAddProperty", "(", "typeManager", ",", "props", ",", "typeId", ",", "filter", ",", "id", ")", ")", "{", "return", ";", "}", "PropertyIdImpl", "result", "=", "new", "PropertyIdImpl", "(", "id", ",", "value", ")", ";", "result", ".", "setQueryName", "(", "id", ")", ";", "props", ".", "addProperty", "(", "result", ")", ";", "}" ]
Helper method for adding an id-valued property.<p> @param typeManager the type manager @param props the properties to add to @param typeId the type id @param filter the property filter @param id the property id @param value the property value
[ "Helper", "method", "for", "adding", "an", "id", "-", "valued", "property", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisUtil.java#L273-L288
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java
EntrySerializer.serializeUpdate
void serializeUpdate(@NonNull Collection<TableEntry> entries, byte[] target) { """ Serializes the given {@link TableEntry} collection into the given byte array, without explicitly recording the versions for each entry. @param entries A Collection of {@link TableEntry} to serialize. @param target The byte array to serialize into. """ int offset = 0; for (TableEntry e : entries) { offset = serializeUpdate(e, target, offset, TableKey.NO_VERSION); } }
java
void serializeUpdate(@NonNull Collection<TableEntry> entries, byte[] target) { int offset = 0; for (TableEntry e : entries) { offset = serializeUpdate(e, target, offset, TableKey.NO_VERSION); } }
[ "void", "serializeUpdate", "(", "@", "NonNull", "Collection", "<", "TableEntry", ">", "entries", ",", "byte", "[", "]", "target", ")", "{", "int", "offset", "=", "0", ";", "for", "(", "TableEntry", "e", ":", "entries", ")", "{", "offset", "=", "serializeUpdate", "(", "e", ",", "target", ",", "offset", ",", "TableKey", ".", "NO_VERSION", ")", ";", "}", "}" ]
Serializes the given {@link TableEntry} collection into the given byte array, without explicitly recording the versions for each entry. @param entries A Collection of {@link TableEntry} to serialize. @param target The byte array to serialize into.
[ "Serializes", "the", "given", "{", "@link", "TableEntry", "}", "collection", "into", "the", "given", "byte", "array", "without", "explicitly", "recording", "the", "versions", "for", "each", "entry", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java#L68-L73
Azure/azure-sdk-for-java
common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java
FluxUtil.byteBufStreamFromFile
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel) { """ Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads the entire file. @param fileChannel The file channel. @return The AsyncInputStream. """ try { long size = fileChannel.size(); return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, 0, size); } catch (IOException e) { return Flux.error(e); } }
java
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel) { try { long size = fileChannel.size(); return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, 0, size); } catch (IOException e) { return Flux.error(e); } }
[ "public", "static", "Flux", "<", "ByteBuf", ">", "byteBufStreamFromFile", "(", "AsynchronousFileChannel", "fileChannel", ")", "{", "try", "{", "long", "size", "=", "fileChannel", ".", "size", "(", ")", ";", "return", "byteBufStreamFromFile", "(", "fileChannel", ",", "DEFAULT_CHUNK_SIZE", ",", "0", ",", "size", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "Flux", ".", "error", "(", "e", ")", ";", "}", "}" ]
Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads the entire file. @param fileChannel The file channel. @return The AsyncInputStream.
[ "Creates", "a", "{", "@link", "Flux", "}", "from", "an", "{", "@link", "AsynchronousFileChannel", "}", "which", "reads", "the", "entire", "file", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java#L188-L195
apache/reef
lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/resourcemanager/ResourceManagerStatus.java
ResourceManagerStatus.getIdleStatus
@Override public synchronized IdleMessage getIdleStatus() { """ Driver is idle if, regardless of status, it has no evaluators allocated and no pending container requests. This method is used in the DriverIdleManager. If all DriverIdlenessSource components are idle, DriverIdleManager will initiate Driver shutdown. @return idle, if there are no outstanding requests or allocations. Not idle otherwise. """ if (this.isIdle()) { return IDLE_MESSAGE; } final String message = String.format( "There are %d outstanding container requests and %d allocated containers", this.outstandingContainerRequests, this.containerAllocationCount); return new IdleMessage(COMPONENT_NAME, message, false); }
java
@Override public synchronized IdleMessage getIdleStatus() { if (this.isIdle()) { return IDLE_MESSAGE; } final String message = String.format( "There are %d outstanding container requests and %d allocated containers", this.outstandingContainerRequests, this.containerAllocationCount); return new IdleMessage(COMPONENT_NAME, message, false); }
[ "@", "Override", "public", "synchronized", "IdleMessage", "getIdleStatus", "(", ")", "{", "if", "(", "this", ".", "isIdle", "(", ")", ")", "{", "return", "IDLE_MESSAGE", ";", "}", "final", "String", "message", "=", "String", ".", "format", "(", "\"There are %d outstanding container requests and %d allocated containers\"", ",", "this", ".", "outstandingContainerRequests", ",", "this", ".", "containerAllocationCount", ")", ";", "return", "new", "IdleMessage", "(", "COMPONENT_NAME", ",", "message", ",", "false", ")", ";", "}" ]
Driver is idle if, regardless of status, it has no evaluators allocated and no pending container requests. This method is used in the DriverIdleManager. If all DriverIdlenessSource components are idle, DriverIdleManager will initiate Driver shutdown. @return idle, if there are no outstanding requests or allocations. Not idle otherwise.
[ "Driver", "is", "idle", "if", "regardless", "of", "status", "it", "has", "no", "evaluators", "allocated", "and", "no", "pending", "container", "requests", ".", "This", "method", "is", "used", "in", "the", "DriverIdleManager", ".", "If", "all", "DriverIdlenessSource", "components", "are", "idle", "DriverIdleManager", "will", "initiate", "Driver", "shutdown", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/resourcemanager/ResourceManagerStatus.java#L127-L139
janus-project/guava.janusproject.io
guava/src/com/google/common/base/Joiner.java
Joiner.appendTo
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { """ Appends the string representation of each of {@code parts}, using the previously configured separator between each, to {@code appendable}. """ return appendTo(appendable, parts.iterator()); }
java
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); }
[ "public", "<", "A", "extends", "Appendable", ">", "A", "appendTo", "(", "A", "appendable", ",", "Iterable", "<", "?", ">", "parts", ")", "throws", "IOException", "{", "return", "appendTo", "(", "appendable", ",", "parts", ".", "iterator", "(", ")", ")", ";", "}" ]
Appends the string representation of each of {@code parts}, using the previously configured separator between each, to {@code appendable}.
[ "Appends", "the", "string", "representation", "of", "each", "of", "{" ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/base/Joiner.java#L95-L97
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/Toothpick.java
Toothpick.openScopes
public static Scope openScopes(Object... names) { """ Opens multiple scopes in a row. Opened scopes will be children of each other in left to right order (e.g. {@code openScopes(a,b)} opens scopes {@code a} and {@code b} and {@code b} is a child of {@code a}. @param names of the scopes to open hierarchically. @return the last opened scope, leaf node of the created subtree of scopes. """ if (names == null) { throw new IllegalArgumentException("null scope names are not allowed."); } if (names.length == 0) { throw new IllegalArgumentException("Minimally, one scope name is required."); } ScopeNode lastScope = null; ScopeNode previousScope = (ScopeNode) openScope(names[0], true); for (int i = 1; i < names.length; i++) { lastScope = (ScopeNode) openScope(names[i], false); lastScope = previousScope.addChild(lastScope); previousScope = lastScope; } return previousScope; }
java
public static Scope openScopes(Object... names) { if (names == null) { throw new IllegalArgumentException("null scope names are not allowed."); } if (names.length == 0) { throw new IllegalArgumentException("Minimally, one scope name is required."); } ScopeNode lastScope = null; ScopeNode previousScope = (ScopeNode) openScope(names[0], true); for (int i = 1; i < names.length; i++) { lastScope = (ScopeNode) openScope(names[i], false); lastScope = previousScope.addChild(lastScope); previousScope = lastScope; } return previousScope; }
[ "public", "static", "Scope", "openScopes", "(", "Object", "...", "names", ")", "{", "if", "(", "names", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"null scope names are not allowed.\"", ")", ";", "}", "if", "(", "names", ".", "length", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Minimally, one scope name is required.\"", ")", ";", "}", "ScopeNode", "lastScope", "=", "null", ";", "ScopeNode", "previousScope", "=", "(", "ScopeNode", ")", "openScope", "(", "names", "[", "0", "]", ",", "true", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "lastScope", "=", "(", "ScopeNode", ")", "openScope", "(", "names", "[", "i", "]", ",", "false", ")", ";", "lastScope", "=", "previousScope", ".", "addChild", "(", "lastScope", ")", ";", "previousScope", "=", "lastScope", ";", "}", "return", "previousScope", ";", "}" ]
Opens multiple scopes in a row. Opened scopes will be children of each other in left to right order (e.g. {@code openScopes(a,b)} opens scopes {@code a} and {@code b} and {@code b} is a child of {@code a}. @param names of the scopes to open hierarchically. @return the last opened scope, leaf node of the created subtree of scopes.
[ "Opens", "multiple", "scopes", "in", "a", "row", ".", "Opened", "scopes", "will", "be", "children", "of", "each", "other", "in", "left", "to", "right", "order", "(", "e", ".", "g", ".", "{", "@code", "openScopes", "(", "a", "b", ")", "}", "opens", "scopes", "{", "@code", "a", "}", "and", "{", "@code", "b", "}", "and", "{", "@code", "b", "}", "is", "a", "child", "of", "{", "@code", "a", "}", "." ]
train
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/Toothpick.java#L54-L73
OpenLiberty/open-liberty
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/ServerSecurityInterceptor.java
ServerSecurityInterceptor.buildPolicyErrorMessage
private void buildPolicyErrorMessage(String msgKey, String defaultMessage, Object... arg1) { """ Receives the message key like "CSIv2_COMMON_AUTH_LAYER_DISABLED" from this key we extract the message from the NLS message bundle which contains the message along with the CWWKS message code. Example: CSIv2_CLIENT_POLICY_DOESNT_EXIST_FAILED=CWWKS9568E: The client security policy does not exist. @param msgCode """ /* The message need to be logged only for level below 'Warning' */ if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) { String messageFromBundle = Tr.formatMessage(tc, msgKey, arg1); Tr.error(tc, messageFromBundle); } }
java
private void buildPolicyErrorMessage(String msgKey, String defaultMessage, Object... arg1) { /* The message need to be logged only for level below 'Warning' */ if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) { String messageFromBundle = Tr.formatMessage(tc, msgKey, arg1); Tr.error(tc, messageFromBundle); } }
[ "private", "void", "buildPolicyErrorMessage", "(", "String", "msgKey", ",", "String", "defaultMessage", ",", "Object", "...", "arg1", ")", "{", "/* The message need to be logged only for level below 'Warning' */", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isWarningEnabled", "(", ")", ")", "{", "String", "messageFromBundle", "=", "Tr", ".", "formatMessage", "(", "tc", ",", "msgKey", ",", "arg1", ")", ";", "Tr", ".", "error", "(", "tc", ",", "messageFromBundle", ")", ";", "}", "}" ]
Receives the message key like "CSIv2_COMMON_AUTH_LAYER_DISABLED" from this key we extract the message from the NLS message bundle which contains the message along with the CWWKS message code. Example: CSIv2_CLIENT_POLICY_DOESNT_EXIST_FAILED=CWWKS9568E: The client security policy does not exist. @param msgCode
[ "Receives", "the", "message", "key", "like", "CSIv2_COMMON_AUTH_LAYER_DISABLED", "from", "this", "key", "we", "extract", "the", "message", "from", "the", "NLS", "message", "bundle", "which", "contains", "the", "message", "along", "with", "the", "CWWKS", "message", "code", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/ServerSecurityInterceptor.java#L340-L346
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/Configuration.java
Configuration.getFloat
@PublicEvolving public float getFloat(ConfigOption<Float> configOption) { """ Returns the value associated with the given config option as a float. @param configOption The configuration option @return the (default) value associated with the given config option """ Object o = getValueOrDefaultFromOption(configOption); return convertToFloat(o, configOption.defaultValue()); }
java
@PublicEvolving public float getFloat(ConfigOption<Float> configOption) { Object o = getValueOrDefaultFromOption(configOption); return convertToFloat(o, configOption.defaultValue()); }
[ "@", "PublicEvolving", "public", "float", "getFloat", "(", "ConfigOption", "<", "Float", ">", "configOption", ")", "{", "Object", "o", "=", "getValueOrDefaultFromOption", "(", "configOption", ")", ";", "return", "convertToFloat", "(", "o", ",", "configOption", ".", "defaultValue", "(", ")", ")", ";", "}" ]
Returns the value associated with the given config option as a float. @param configOption The configuration option @return the (default) value associated with the given config option
[ "Returns", "the", "value", "associated", "with", "the", "given", "config", "option", "as", "a", "float", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L441-L445
seedstack/i18n-addon
rest/src/main/java/org/seedstack/i18n/rest/internal/key/KeysResource.java
KeysResource.deleteKeys
@DELETE @Produces("text/plain") @RequiresPermissions(I18nPermissions.KEY_DELETE) public Response deleteKeys(@QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox, @QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) { """ Deletes all the filtered keys. @param isMissing filter on missing default translation @param isApprox filter on approximate default translation @param isOutdated filter on outdated key @param searchName filter on key name @return http status code 200 (ok) with the number of deleted keys """ KeySearchCriteria keySearchCriteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName); long numberOfDeletedKeys; if (shouldDeleteWithoutFilter(keySearchCriteria)) { numberOfDeletedKeys = keyRepository.size(); keyRepository.clear(); // If no filter are precised use the "deleteAll()" method which is more optimized } else { numberOfDeletedKeys = deleteFilteredKeys(keySearchCriteria); } return Response.ok(String.format("%d deleted keys", numberOfDeletedKeys)).build(); }
java
@DELETE @Produces("text/plain") @RequiresPermissions(I18nPermissions.KEY_DELETE) public Response deleteKeys(@QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox, @QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) { KeySearchCriteria keySearchCriteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName); long numberOfDeletedKeys; if (shouldDeleteWithoutFilter(keySearchCriteria)) { numberOfDeletedKeys = keyRepository.size(); keyRepository.clear(); // If no filter are precised use the "deleteAll()" method which is more optimized } else { numberOfDeletedKeys = deleteFilteredKeys(keySearchCriteria); } return Response.ok(String.format("%d deleted keys", numberOfDeletedKeys)).build(); }
[ "@", "DELETE", "@", "Produces", "(", "\"text/plain\"", ")", "@", "RequiresPermissions", "(", "I18nPermissions", ".", "KEY_DELETE", ")", "public", "Response", "deleteKeys", "(", "@", "QueryParam", "(", "IS_MISSING", ")", "Boolean", "isMissing", ",", "@", "QueryParam", "(", "IS_APPROX", ")", "Boolean", "isApprox", ",", "@", "QueryParam", "(", "IS_OUTDATED", ")", "Boolean", "isOutdated", ",", "@", "QueryParam", "(", "SEARCH_NAME", ")", "String", "searchName", ")", "{", "KeySearchCriteria", "keySearchCriteria", "=", "new", "KeySearchCriteria", "(", "isMissing", ",", "isApprox", ",", "isOutdated", ",", "searchName", ")", ";", "long", "numberOfDeletedKeys", ";", "if", "(", "shouldDeleteWithoutFilter", "(", "keySearchCriteria", ")", ")", "{", "numberOfDeletedKeys", "=", "keyRepository", ".", "size", "(", ")", ";", "keyRepository", ".", "clear", "(", ")", ";", "// If no filter are precised use the \"deleteAll()\" method which is more optimized", "}", "else", "{", "numberOfDeletedKeys", "=", "deleteFilteredKeys", "(", "keySearchCriteria", ")", ";", "}", "return", "Response", ".", "ok", "(", "String", ".", "format", "(", "\"%d deleted keys\"", ",", "numberOfDeletedKeys", ")", ")", ".", "build", "(", ")", ";", "}" ]
Deletes all the filtered keys. @param isMissing filter on missing default translation @param isApprox filter on approximate default translation @param isOutdated filter on outdated key @param searchName filter on key name @return http status code 200 (ok) with the number of deleted keys
[ "Deletes", "all", "the", "filtered", "keys", "." ]
train
https://github.com/seedstack/i18n-addon/blob/1e65101d8554623f09bda2497b0151fd10a16615/rest/src/main/java/org/seedstack/i18n/rest/internal/key/KeysResource.java#L147-L162
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java
State.getPropAsDouble
public double getPropAsDouble(String key, double def) { """ Get the value of a property as a double, using the given default value if the property is not set. @param key property key @param def default value @return double value associated with the key or the default value if the property is not set """ return Double.parseDouble(getProp(key, String.valueOf(def))); }
java
public double getPropAsDouble(String key, double def) { return Double.parseDouble(getProp(key, String.valueOf(def))); }
[ "public", "double", "getPropAsDouble", "(", "String", "key", ",", "double", "def", ")", "{", "return", "Double", ".", "parseDouble", "(", "getProp", "(", "key", ",", "String", ".", "valueOf", "(", "def", ")", ")", ")", ";", "}" ]
Get the value of a property as a double, using the given default value if the property is not set. @param key property key @param def default value @return double value associated with the key or the default value if the property is not set
[ "Get", "the", "value", "of", "a", "property", "as", "a", "double", "using", "the", "given", "default", "value", "if", "the", "property", "is", "not", "set", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L449-L451
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java
PipelineBuilder.addOrExpression
public void addOrExpression(final INodeReadTrx mTransaction) { """ Adds a or expression to the pipeline. @param mTransaction Transaction to operate with. """ assert getPipeStack().size() >= 2; final AbsAxis mOperand2 = getPipeStack().pop().getExpr(); final AbsAxis mOperand1 = getPipeStack().pop().getExpr(); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(new OrExpr(mTransaction, mOperand1, mOperand2)); }
java
public void addOrExpression(final INodeReadTrx mTransaction) { assert getPipeStack().size() >= 2; final AbsAxis mOperand2 = getPipeStack().pop().getExpr(); final AbsAxis mOperand1 = getPipeStack().pop().getExpr(); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(new OrExpr(mTransaction, mOperand1, mOperand2)); }
[ "public", "void", "addOrExpression", "(", "final", "INodeReadTrx", "mTransaction", ")", "{", "assert", "getPipeStack", "(", ")", ".", "size", "(", ")", ">=", "2", ";", "final", "AbsAxis", "mOperand2", "=", "getPipeStack", "(", ")", ".", "pop", "(", ")", ".", "getExpr", "(", ")", ";", "final", "AbsAxis", "mOperand1", "=", "getPipeStack", "(", ")", ".", "pop", "(", ")", ".", "getExpr", "(", ")", ";", "if", "(", "getPipeStack", "(", ")", ".", "empty", "(", ")", "||", "getExpression", "(", ")", ".", "getSize", "(", ")", "!=", "0", ")", "{", "addExpressionSingle", "(", ")", ";", "}", "getExpression", "(", ")", ".", "add", "(", "new", "OrExpr", "(", "mTransaction", ",", "mOperand1", ",", "mOperand2", ")", ")", ";", "}" ]
Adds a or expression to the pipeline. @param mTransaction Transaction to operate with.
[ "Adds", "a", "or", "expression", "to", "the", "pipeline", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L437-L448
landawn/AbacusUtil
src/com/landawn/abacus/util/IOUtil.java
IOUtil.splitBySize
public static void splitBySize(final File file, final long sizeOfPart, final File destDir) throws UncheckedIOException { """ Mostly it's designed for (zipped/unzipped/log) text files. @param file @param sizeOfPart @param destDir """ final int numOfParts = (int) ((file.length() % sizeOfPart) == 0 ? (file.length() / sizeOfPart) : (file.length() / sizeOfPart) + 1); final String fileName = file.getName(); final long fileLength = file.length(); int fileSerNum = 1; final byte[] buf = Objectory.createByteArrayBuffer(); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); for (int i = 0; i < numOfParts; i++) { String subFileNmae = destDir.getAbsolutePath() + IOUtil.FILE_SEPARATOR + fileName + "_" + StringUtil.padStart(N.stringOf(fileSerNum++), 4, '0'); output = new FileOutputStream(new File(subFileNmae)); long partLength = sizeOfPart; if (i == numOfParts - 1) { partLength += fileLength % numOfParts; } int count = 0; try { while (partLength > 0 && EOF != (count = read(input, buf, 0, (int) Math.min(buf.length, partLength)))) { output.write(buf, 0, count); partLength = partLength - count; } output.flush(); } finally { close(output); } } } catch (IOException e) { throw new UncheckedIOException(e); } finally { Objectory.recycle(buf); closeQuietly(input); } }
java
public static void splitBySize(final File file, final long sizeOfPart, final File destDir) throws UncheckedIOException { final int numOfParts = (int) ((file.length() % sizeOfPart) == 0 ? (file.length() / sizeOfPart) : (file.length() / sizeOfPart) + 1); final String fileName = file.getName(); final long fileLength = file.length(); int fileSerNum = 1; final byte[] buf = Objectory.createByteArrayBuffer(); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); for (int i = 0; i < numOfParts; i++) { String subFileNmae = destDir.getAbsolutePath() + IOUtil.FILE_SEPARATOR + fileName + "_" + StringUtil.padStart(N.stringOf(fileSerNum++), 4, '0'); output = new FileOutputStream(new File(subFileNmae)); long partLength = sizeOfPart; if (i == numOfParts - 1) { partLength += fileLength % numOfParts; } int count = 0; try { while (partLength > 0 && EOF != (count = read(input, buf, 0, (int) Math.min(buf.length, partLength)))) { output.write(buf, 0, count); partLength = partLength - count; } output.flush(); } finally { close(output); } } } catch (IOException e) { throw new UncheckedIOException(e); } finally { Objectory.recycle(buf); closeQuietly(input); } }
[ "public", "static", "void", "splitBySize", "(", "final", "File", "file", ",", "final", "long", "sizeOfPart", ",", "final", "File", "destDir", ")", "throws", "UncheckedIOException", "{", "final", "int", "numOfParts", "=", "(", "int", ")", "(", "(", "file", ".", "length", "(", ")", "%", "sizeOfPart", ")", "==", "0", "?", "(", "file", ".", "length", "(", ")", "/", "sizeOfPart", ")", ":", "(", "file", ".", "length", "(", ")", "/", "sizeOfPart", ")", "+", "1", ")", ";", "final", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "final", "long", "fileLength", "=", "file", ".", "length", "(", ")", ";", "int", "fileSerNum", "=", "1", ";", "final", "byte", "[", "]", "buf", "=", "Objectory", ".", "createByteArrayBuffer", "(", ")", ";", "InputStream", "input", "=", "null", ";", "OutputStream", "output", "=", "null", ";", "try", "{", "input", "=", "new", "FileInputStream", "(", "file", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numOfParts", ";", "i", "++", ")", "{", "String", "subFileNmae", "=", "destDir", ".", "getAbsolutePath", "(", ")", "+", "IOUtil", ".", "FILE_SEPARATOR", "+", "fileName", "+", "\"_\"", "+", "StringUtil", ".", "padStart", "(", "N", ".", "stringOf", "(", "fileSerNum", "++", ")", ",", "4", ",", "'", "'", ")", ";", "output", "=", "new", "FileOutputStream", "(", "new", "File", "(", "subFileNmae", ")", ")", ";", "long", "partLength", "=", "sizeOfPart", ";", "if", "(", "i", "==", "numOfParts", "-", "1", ")", "{", "partLength", "+=", "fileLength", "%", "numOfParts", ";", "}", "int", "count", "=", "0", ";", "try", "{", "while", "(", "partLength", ">", "0", "&&", "EOF", "!=", "(", "count", "=", "read", "(", "input", ",", "buf", ",", "0", ",", "(", "int", ")", "Math", ".", "min", "(", "buf", ".", "length", ",", "partLength", ")", ")", ")", ")", "{", "output", ".", "write", "(", "buf", ",", "0", ",", "count", ")", ";", "partLength", "=", "partLength", "-", "count", ";", "}", "output", ".", "flush", "(", ")", ";", "}", "finally", "{", "close", "(", "output", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "UncheckedIOException", "(", "e", ")", ";", "}", "finally", "{", "Objectory", ".", "recycle", "(", "buf", ")", ";", "closeQuietly", "(", "input", ")", ";", "}", "}" ]
Mostly it's designed for (zipped/unzipped/log) text files. @param file @param sizeOfPart @param destDir
[ "Mostly", "it", "s", "designed", "for", "(", "zipped", "/", "unzipped", "/", "log", ")", "text", "files", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/IOUtil.java#L3342-L3385
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.deleteClosedListEntityRole
public OperationStatus deleteClosedListEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) { """ Delete an entity role. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role Id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful. """ return deleteClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body(); }
java
public OperationStatus deleteClosedListEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) { return deleteClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body(); }
[ "public", "OperationStatus", "deleteClosedListEntityRole", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ")", "{", "return", "deleteClosedListEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "roleId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Delete an entity role. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role Id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful.
[ "Delete", "an", "entity", "role", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L11853-L11855
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.getMass
public static double getMass(IMolecularFormula mf, int flav) { """ Calculate the mass of a formula, this function takes an optional 'mass flavour' that switches the computation type. The key distinction is how specified/unspecified isotopes are handled. A specified isotope is an atom that has either {@link IAtom#setMassNumber(Integer)} or {@link IAtom#setExactMass(Double)} set to non-null and non-zero. <br> The flavours are: <br> <ul> <li>{@link #MolWeight} (default) - uses the exact mass of each atom when an isotope is specified, if not specified the average mass of the element is used.</li> <li>{@link #MolWeightIgnoreSpecified} - uses the average mass of each element, ignoring any isotopic/exact mass specification</li> <li>{@link #MonoIsotopic} - uses the exact mass of each atom when an isotope is specified, if not specified the major isotope mass for that element is used.</li> <li>{@link #MostAbundant} - uses the exact mass of each atom when specified, if not specified a distribution is calculated and the most abundant isotope pattern is used.</li> </ul> @param mf molecular formula @param flav flavor @return the mass of the molecule @see #getMass(IMolecularFormula, int) @see #MolWeight @see #MolWeightIgnoreSpecified @see #MonoIsotopic @see #MostAbundant """ final Isotopes isofact; try { isofact = Isotopes.getInstance(); } catch (IOException e) { throw new IllegalStateException("Could not load Isotopes!"); } double mass = 0; switch (flav & 0xf) { case MolWeight: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * getMassOrAvg(isofact, iso); } break; case MolWeightIgnoreSpecified: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * isofact.getNaturalMass(iso.getAtomicNumber()); } break; case MonoIsotopic: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * getExactMass(isofact, iso); } break; case MostAbundant: IMolecularFormula mamf = getMostAbundant(mf); if (mamf != null) mass = getMass(mamf, MonoIsotopic); break; } return mass; }
java
public static double getMass(IMolecularFormula mf, int flav) { final Isotopes isofact; try { isofact = Isotopes.getInstance(); } catch (IOException e) { throw new IllegalStateException("Could not load Isotopes!"); } double mass = 0; switch (flav & 0xf) { case MolWeight: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * getMassOrAvg(isofact, iso); } break; case MolWeightIgnoreSpecified: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * isofact.getNaturalMass(iso.getAtomicNumber()); } break; case MonoIsotopic: for (IIsotope iso : mf.isotopes()) { mass += mf.getIsotopeCount(iso) * getExactMass(isofact, iso); } break; case MostAbundant: IMolecularFormula mamf = getMostAbundant(mf); if (mamf != null) mass = getMass(mamf, MonoIsotopic); break; } return mass; }
[ "public", "static", "double", "getMass", "(", "IMolecularFormula", "mf", ",", "int", "flav", ")", "{", "final", "Isotopes", "isofact", ";", "try", "{", "isofact", "=", "Isotopes", ".", "getInstance", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Could not load Isotopes!\"", ")", ";", "}", "double", "mass", "=", "0", ";", "switch", "(", "flav", "&", "0xf", ")", "{", "case", "MolWeight", ":", "for", "(", "IIsotope", "iso", ":", "mf", ".", "isotopes", "(", ")", ")", "{", "mass", "+=", "mf", ".", "getIsotopeCount", "(", "iso", ")", "*", "getMassOrAvg", "(", "isofact", ",", "iso", ")", ";", "}", "break", ";", "case", "MolWeightIgnoreSpecified", ":", "for", "(", "IIsotope", "iso", ":", "mf", ".", "isotopes", "(", ")", ")", "{", "mass", "+=", "mf", ".", "getIsotopeCount", "(", "iso", ")", "*", "isofact", ".", "getNaturalMass", "(", "iso", ".", "getAtomicNumber", "(", ")", ")", ";", "}", "break", ";", "case", "MonoIsotopic", ":", "for", "(", "IIsotope", "iso", ":", "mf", ".", "isotopes", "(", ")", ")", "{", "mass", "+=", "mf", ".", "getIsotopeCount", "(", "iso", ")", "*", "getExactMass", "(", "isofact", ",", "iso", ")", ";", "}", "break", ";", "case", "MostAbundant", ":", "IMolecularFormula", "mamf", "=", "getMostAbundant", "(", "mf", ")", ";", "if", "(", "mamf", "!=", "null", ")", "mass", "=", "getMass", "(", "mamf", ",", "MonoIsotopic", ")", ";", "break", ";", "}", "return", "mass", ";", "}" ]
Calculate the mass of a formula, this function takes an optional 'mass flavour' that switches the computation type. The key distinction is how specified/unspecified isotopes are handled. A specified isotope is an atom that has either {@link IAtom#setMassNumber(Integer)} or {@link IAtom#setExactMass(Double)} set to non-null and non-zero. <br> The flavours are: <br> <ul> <li>{@link #MolWeight} (default) - uses the exact mass of each atom when an isotope is specified, if not specified the average mass of the element is used.</li> <li>{@link #MolWeightIgnoreSpecified} - uses the average mass of each element, ignoring any isotopic/exact mass specification</li> <li>{@link #MonoIsotopic} - uses the exact mass of each atom when an isotope is specified, if not specified the major isotope mass for that element is used.</li> <li>{@link #MostAbundant} - uses the exact mass of each atom when specified, if not specified a distribution is calculated and the most abundant isotope pattern is used.</li> </ul> @param mf molecular formula @param flav flavor @return the mass of the molecule @see #getMass(IMolecularFormula, int) @see #MolWeight @see #MolWeightIgnoreSpecified @see #MonoIsotopic @see #MostAbundant
[ "Calculate", "the", "mass", "of", "a", "formula", "this", "function", "takes", "an", "optional", "mass", "flavour", "that", "switches", "the", "computation", "type", ".", "The", "key", "distinction", "is", "how", "specified", "/", "unspecified", "isotopes", "are", "handled", ".", "A", "specified", "isotope", "is", "an", "atom", "that", "has", "either", "{", "@link", "IAtom#setMassNumber", "(", "Integer", ")", "}", "or", "{", "@link", "IAtom#setExactMass", "(", "Double", ")", "}", "set", "to", "non", "-", "null", "and", "non", "-", "zero", ".", "<br", ">", "The", "flavours", "are", ":", "<br", ">", "<ul", ">", "<li", ">", "{", "@link", "#MolWeight", "}", "(", "default", ")", "-", "uses", "the", "exact", "mass", "of", "each", "atom", "when", "an", "isotope", "is", "specified", "if", "not", "specified", "the", "average", "mass", "of", "the", "element", "is", "used", ".", "<", "/", "li", ">", "<li", ">", "{", "@link", "#MolWeightIgnoreSpecified", "}", "-", "uses", "the", "average", "mass", "of", "each", "element", "ignoring", "any", "isotopic", "/", "exact", "mass", "specification<", "/", "li", ">", "<li", ">", "{", "@link", "#MonoIsotopic", "}", "-", "uses", "the", "exact", "mass", "of", "each", "atom", "when", "an", "isotope", "is", "specified", "if", "not", "specified", "the", "major", "isotope", "mass", "for", "that", "element", "is", "used", ".", "<", "/", "li", ">", "<li", ">", "{", "@link", "#MostAbundant", "}", "-", "uses", "the", "exact", "mass", "of", "each", "atom", "when", "specified", "if", "not", "specified", "a", "distribution", "is", "calculated", "and", "the", "most", "abundant", "isotope", "pattern", "is", "used", ".", "<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L907-L942
apache/incubator-druid
extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchBuildBufferAggregator.java
DoublesSketchBuildBufferAggregator.relocate
@Override public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer) { """ In that case we need to reuse the object from the cache as opposed to wrapping the new buffer. """ UpdateDoublesSketch sketch = sketches.get(oldBuffer).get(oldPosition); final WritableMemory oldRegion = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize); if (sketch.isSameResource(oldRegion)) { // sketch was not relocated on heap final WritableMemory newRegion = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize); sketch = UpdateDoublesSketch.wrap(newRegion); } putSketch(newBuffer, newPosition, sketch); final Int2ObjectMap<UpdateDoublesSketch> map = sketches.get(oldBuffer); map.remove(oldPosition); if (map.isEmpty()) { sketches.remove(oldBuffer); memCache.remove(oldBuffer); } }
java
@Override public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer) { UpdateDoublesSketch sketch = sketches.get(oldBuffer).get(oldPosition); final WritableMemory oldRegion = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize); if (sketch.isSameResource(oldRegion)) { // sketch was not relocated on heap final WritableMemory newRegion = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize); sketch = UpdateDoublesSketch.wrap(newRegion); } putSketch(newBuffer, newPosition, sketch); final Int2ObjectMap<UpdateDoublesSketch> map = sketches.get(oldBuffer); map.remove(oldPosition); if (map.isEmpty()) { sketches.remove(oldBuffer); memCache.remove(oldBuffer); } }
[ "@", "Override", "public", "synchronized", "void", "relocate", "(", "int", "oldPosition", ",", "int", "newPosition", ",", "ByteBuffer", "oldBuffer", ",", "ByteBuffer", "newBuffer", ")", "{", "UpdateDoublesSketch", "sketch", "=", "sketches", ".", "get", "(", "oldBuffer", ")", ".", "get", "(", "oldPosition", ")", ";", "final", "WritableMemory", "oldRegion", "=", "getMemory", "(", "oldBuffer", ")", ".", "writableRegion", "(", "oldPosition", ",", "maxIntermediateSize", ")", ";", "if", "(", "sketch", ".", "isSameResource", "(", "oldRegion", ")", ")", "{", "// sketch was not relocated on heap", "final", "WritableMemory", "newRegion", "=", "getMemory", "(", "newBuffer", ")", ".", "writableRegion", "(", "newPosition", ",", "maxIntermediateSize", ")", ";", "sketch", "=", "UpdateDoublesSketch", ".", "wrap", "(", "newRegion", ")", ";", "}", "putSketch", "(", "newBuffer", ",", "newPosition", ",", "sketch", ")", ";", "final", "Int2ObjectMap", "<", "UpdateDoublesSketch", ">", "map", "=", "sketches", ".", "get", "(", "oldBuffer", ")", ";", "map", ".", "remove", "(", "oldPosition", ")", ";", "if", "(", "map", ".", "isEmpty", "(", ")", ")", "{", "sketches", ".", "remove", "(", "oldBuffer", ")", ";", "memCache", ".", "remove", "(", "oldBuffer", ")", ";", "}", "}" ]
In that case we need to reuse the object from the cache as opposed to wrapping the new buffer.
[ "In", "that", "case", "we", "need", "to", "reuse", "the", "object", "from", "the", "cache", "as", "opposed", "to", "wrapping", "the", "new", "buffer", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchBuildBufferAggregator.java#L96-L113
tvesalainen/bcc
src/main/java/org/vesalainen/bcc/MethodCompiler.java
MethodCompiler.putStaticField
public void putStaticField(Class<?> cls, String name) throws IOException { """ Set field in class <p>Stack: ..., value =&gt; ... @param cls @param name @throws IOException """ putStaticField(El.getField(cls, name)); }
java
public void putStaticField(Class<?> cls, String name) throws IOException { putStaticField(El.getField(cls, name)); }
[ "public", "void", "putStaticField", "(", "Class", "<", "?", ">", "cls", ",", "String", "name", ")", "throws", "IOException", "{", "putStaticField", "(", "El", ".", "getField", "(", "cls", ",", "name", ")", ")", ";", "}" ]
Set field in class <p>Stack: ..., value =&gt; ... @param cls @param name @throws IOException
[ "Set", "field", "in", "class", "<p", ">", "Stack", ":", "...", "value", "=", "&gt", ";", "..." ]
train
https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L1020-L1023
twilio/twilio-java
src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java
PublicKeyReader.firstPage
@Override @SuppressWarnings("checkstyle:linelength") public Page<PublicKey> firstPage(final TwilioRestClient client) { """ Make the request to the Twilio API to perform the read. @param client TwilioRestClient with which to make the request @return PublicKey ResourceSet """ Request request = new Request( HttpMethod.GET, Domains.ACCOUNTS.toString(), "/v1/Credentials/PublicKeys", client.getRegion() ); addQueryParams(request); return pageForRequest(client, request); }
java
@Override @SuppressWarnings("checkstyle:linelength") public Page<PublicKey> firstPage(final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, Domains.ACCOUNTS.toString(), "/v1/Credentials/PublicKeys", client.getRegion() ); addQueryParams(request); return pageForRequest(client, request); }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"checkstyle:linelength\"", ")", "public", "Page", "<", "PublicKey", ">", "firstPage", "(", "final", "TwilioRestClient", "client", ")", "{", "Request", "request", "=", "new", "Request", "(", "HttpMethod", ".", "GET", ",", "Domains", ".", "ACCOUNTS", ".", "toString", "(", ")", ",", "\"/v1/Credentials/PublicKeys\"", ",", "client", ".", "getRegion", "(", ")", ")", ";", "addQueryParams", "(", "request", ")", ";", "return", "pageForRequest", "(", "client", ",", "request", ")", ";", "}" ]
Make the request to the Twilio API to perform the read. @param client TwilioRestClient with which to make the request @return PublicKey ResourceSet
[ "Make", "the", "request", "to", "the", "Twilio", "API", "to", "perform", "the", "read", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java#L40-L52
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java
SubnetsInner.getAsync
public Observable<SubnetInner> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName) { """ Gets the specified subnet by virtual network and resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param subnetName The name of the subnet. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SubnetInner object """ return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName).map(new Func1<ServiceResponse<SubnetInner>, SubnetInner>() { @Override public SubnetInner call(ServiceResponse<SubnetInner> response) { return response.body(); } }); }
java
public Observable<SubnetInner> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName) { return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName).map(new Func1<ServiceResponse<SubnetInner>, SubnetInner>() { @Override public SubnetInner call(ServiceResponse<SubnetInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "SubnetInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkName", ",", "String", "subnetName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkName", ",", "subnetName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "SubnetInner", ">", ",", "SubnetInner", ">", "(", ")", "{", "@", "Override", "public", "SubnetInner", "call", "(", "ServiceResponse", "<", "SubnetInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the specified subnet by virtual network and resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param subnetName The name of the subnet. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SubnetInner object
[ "Gets", "the", "specified", "subnet", "by", "virtual", "network", "and", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java#L297-L304
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/ByteArrayUtil.java
ByteArrayUtil.putIntLE
public static void putIntLE(final byte[] array, final int offset, final int value) { """ Put the source <i>int</i> into the destination byte array starting at the given offset in little endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>int</i> """ array[offset ] = (byte) (value ); array[offset + 1] = (byte) (value >>> 8); array[offset + 2] = (byte) (value >>> 16); array[offset + 3] = (byte) (value >>> 24); }
java
public static void putIntLE(final byte[] array, final int offset, final int value) { array[offset ] = (byte) (value ); array[offset + 1] = (byte) (value >>> 8); array[offset + 2] = (byte) (value >>> 16); array[offset + 3] = (byte) (value >>> 24); }
[ "public", "static", "void", "putIntLE", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "int", "value", ")", "{", "array", "[", "offset", "]", "=", "(", "byte", ")", "(", "value", ")", ";", "array", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "value", ">>>", "8", ")", ";", "array", "[", "offset", "+", "2", "]", "=", "(", "byte", ")", "(", "value", ">>>", "16", ")", ";", "array", "[", "offset", "+", "3", "]", "=", "(", "byte", ")", "(", "value", ">>>", "24", ")", ";", "}" ]
Put the source <i>int</i> into the destination byte array starting at the given offset in little endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>int</i>
[ "Put", "the", "source", "<i", ">", "int<", "/", "i", ">", "into", "the", "destination", "byte", "array", "starting", "at", "the", "given", "offset", "in", "little", "endian", "order", ".", "There", "is", "no", "bounds", "checking", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/ByteArrayUtil.java#L80-L85
virgo47/javasimon
core/src/main/java/org/javasimon/callback/quantiles/PropertiesQuantilesCallback.java
PropertiesQuantilesCallback.getProperty
private String getProperty(Simon simon, String name) { """ Returns value of Simon property. @param simon Simon @param name Property name @return Raw property value """ return properties.getProperty(simon.getName() + "." + name); }
java
private String getProperty(Simon simon, String name) { return properties.getProperty(simon.getName() + "." + name); }
[ "private", "String", "getProperty", "(", "Simon", "simon", ",", "String", "name", ")", "{", "return", "properties", ".", "getProperty", "(", "simon", ".", "getName", "(", ")", "+", "\".\"", "+", "name", ")", ";", "}" ]
Returns value of Simon property. @param simon Simon @param name Property name @return Raw property value
[ "Returns", "value", "of", "Simon", "property", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/quantiles/PropertiesQuantilesCallback.java#L71-L73
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/CollectionUtilities.java
CollectionUtilities.getSortOrder
public static <T extends Comparable<? super T>> Integer getSortOrder(final T first, final T second) { """ Provides an easy way to compare two possibly null comparable objects @param first The first object to compare @param second The second object to compare @return < 0 if the first object is less than the second object, 0 if they are equal, and > 0 otherwise """ if (first == null && second == null) return null; if (first == null && second != null) return -1; if (first != null && second == null) return 1; return first.compareTo(second); }
java
public static <T extends Comparable<? super T>> Integer getSortOrder(final T first, final T second) { if (first == null && second == null) return null; if (first == null && second != null) return -1; if (first != null && second == null) return 1; return first.compareTo(second); }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", "super", "T", ">", ">", "Integer", "getSortOrder", "(", "final", "T", "first", ",", "final", "T", "second", ")", "{", "if", "(", "first", "==", "null", "&&", "second", "==", "null", ")", "return", "null", ";", "if", "(", "first", "==", "null", "&&", "second", "!=", "null", ")", "return", "-", "1", ";", "if", "(", "first", "!=", "null", "&&", "second", "==", "null", ")", "return", "1", ";", "return", "first", ".", "compareTo", "(", "second", ")", ";", "}" ]
Provides an easy way to compare two possibly null comparable objects @param first The first object to compare @param second The second object to compare @return < 0 if the first object is less than the second object, 0 if they are equal, and > 0 otherwise
[ "Provides", "an", "easy", "way", "to", "compare", "two", "possibly", "null", "comparable", "objects" ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/CollectionUtilities.java#L163-L171
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java
CeCPMain.filterDuplicateAFPs
public static AFPChain filterDuplicateAFPs(AFPChain afpChain, CECalculator ceCalc, Atom[] ca1, Atom[] ca2duplicated) throws StructureException { """ Takes as input an AFPChain where ca2 has been artificially duplicated. This raises the possibility that some residues of ca2 will appear in multiple AFPs. This method filters out duplicates and makes sure that all AFPs are numbered relative to the original ca2. <p>The current version chooses a CP site such that the length of the alignment is maximized. <p>This method does <i>not</i> update scores to reflect the filtered alignment. It <i>does</i> update the RMSD and superposition. @param afpChain The alignment between ca1 and ca2-ca2. Blindly assumes that ca2 has been duplicated. @return A new AFPChain consisting of ca1 to ca2, with each residue in at most 1 AFP. @throws StructureException """ return filterDuplicateAFPs(afpChain, ceCalc, ca1, ca2duplicated, null); }
java
public static AFPChain filterDuplicateAFPs(AFPChain afpChain, CECalculator ceCalc, Atom[] ca1, Atom[] ca2duplicated) throws StructureException { return filterDuplicateAFPs(afpChain, ceCalc, ca1, ca2duplicated, null); }
[ "public", "static", "AFPChain", "filterDuplicateAFPs", "(", "AFPChain", "afpChain", ",", "CECalculator", "ceCalc", ",", "Atom", "[", "]", "ca1", ",", "Atom", "[", "]", "ca2duplicated", ")", "throws", "StructureException", "{", "return", "filterDuplicateAFPs", "(", "afpChain", ",", "ceCalc", ",", "ca1", ",", "ca2duplicated", ",", "null", ")", ";", "}" ]
Takes as input an AFPChain where ca2 has been artificially duplicated. This raises the possibility that some residues of ca2 will appear in multiple AFPs. This method filters out duplicates and makes sure that all AFPs are numbered relative to the original ca2. <p>The current version chooses a CP site such that the length of the alignment is maximized. <p>This method does <i>not</i> update scores to reflect the filtered alignment. It <i>does</i> update the RMSD and superposition. @param afpChain The alignment between ca1 and ca2-ca2. Blindly assumes that ca2 has been duplicated. @return A new AFPChain consisting of ca1 to ca2, with each residue in at most 1 AFP. @throws StructureException
[ "Takes", "as", "input", "an", "AFPChain", "where", "ca2", "has", "been", "artificially", "duplicated", ".", "This", "raises", "the", "possibility", "that", "some", "residues", "of", "ca2", "will", "appear", "in", "multiple", "AFPs", ".", "This", "method", "filters", "out", "duplicates", "and", "makes", "sure", "that", "all", "AFPs", "are", "numbered", "relative", "to", "the", "original", "ca2", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java#L323-L325
jnr/jnr-x86asm
src/main/java/jnr/x86asm/SerializerIntrinsics.java
SerializerIntrinsics.pcmpestri
public final void pcmpestri(XMMRegister dst, XMMRegister src, Immediate imm8) { """ Packed Compare Explicit Length Strings, Return Index (SSE4.2). """ emitX86(INST_PCMPESTRI, dst, src, imm8); }
java
public final void pcmpestri(XMMRegister dst, XMMRegister src, Immediate imm8) { emitX86(INST_PCMPESTRI, dst, src, imm8); }
[ "public", "final", "void", "pcmpestri", "(", "XMMRegister", "dst", ",", "XMMRegister", "src", ",", "Immediate", "imm8", ")", "{", "emitX86", "(", "INST_PCMPESTRI", ",", "dst", ",", "src", ",", "imm8", ")", ";", "}" ]
Packed Compare Explicit Length Strings, Return Index (SSE4.2).
[ "Packed", "Compare", "Explicit", "Length", "Strings", "Return", "Index", "(", "SSE4", ".", "2", ")", "." ]
train
https://github.com/jnr/jnr-x86asm/blob/fdcf68fb3dae49e607a49e33399e3dad1ada5536/src/main/java/jnr/x86asm/SerializerIntrinsics.java#L6529-L6532
alipay/sofa-hessian
src/main/java/com/caucho/hessian/server/HessianServlet.java
HessianServlet.service
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { """ Execute a request. The path-info of the request selects the bean. Once the bean's selected, it will be applied. """ HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if (!req.getMethod().equals("POST")) { res.setStatus(500); // , "Hessian Requires POST"); PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<h1>Hessian Requires POST</h1>"); return; } String serviceId = req.getPathInfo(); String objectId = req.getParameter("id"); if (objectId == null) objectId = req.getParameter("ejbid"); ServiceContext.begin(req, res, serviceId, objectId); try { InputStream is = request.getInputStream(); OutputStream os = response.getOutputStream(); response.setContentType("x-application/hessian"); SerializerFactory serializerFactory = getSerializerFactory(); invoke(is, os, objectId, serializerFactory); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (Throwable e) { throw new ServletException(e); } finally { ServiceContext.end(); } }
java
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if (!req.getMethod().equals("POST")) { res.setStatus(500); // , "Hessian Requires POST"); PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<h1>Hessian Requires POST</h1>"); return; } String serviceId = req.getPathInfo(); String objectId = req.getParameter("id"); if (objectId == null) objectId = req.getParameter("ejbid"); ServiceContext.begin(req, res, serviceId, objectId); try { InputStream is = request.getInputStream(); OutputStream os = response.getOutputStream(); response.setContentType("x-application/hessian"); SerializerFactory serializerFactory = getSerializerFactory(); invoke(is, os, objectId, serializerFactory); } catch (RuntimeException e) { throw e; } catch (ServletException e) { throw e; } catch (Throwable e) { throw new ServletException(e); } finally { ServiceContext.end(); } }
[ "public", "void", "service", "(", "ServletRequest", "request", ",", "ServletResponse", "response", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "req", "=", "(", "HttpServletRequest", ")", "request", ";", "HttpServletResponse", "res", "=", "(", "HttpServletResponse", ")", "response", ";", "if", "(", "!", "req", ".", "getMethod", "(", ")", ".", "equals", "(", "\"POST\"", ")", ")", "{", "res", ".", "setStatus", "(", "500", ")", ";", "// , \"Hessian Requires POST\");", "PrintWriter", "out", "=", "res", ".", "getWriter", "(", ")", ";", "res", ".", "setContentType", "(", "\"text/html\"", ")", ";", "out", ".", "println", "(", "\"<h1>Hessian Requires POST</h1>\"", ")", ";", "return", ";", "}", "String", "serviceId", "=", "req", ".", "getPathInfo", "(", ")", ";", "String", "objectId", "=", "req", ".", "getParameter", "(", "\"id\"", ")", ";", "if", "(", "objectId", "==", "null", ")", "objectId", "=", "req", ".", "getParameter", "(", "\"ejbid\"", ")", ";", "ServiceContext", ".", "begin", "(", "req", ",", "res", ",", "serviceId", ",", "objectId", ")", ";", "try", "{", "InputStream", "is", "=", "request", ".", "getInputStream", "(", ")", ";", "OutputStream", "os", "=", "response", ".", "getOutputStream", "(", ")", ";", "response", ".", "setContentType", "(", "\"x-application/hessian\"", ")", ";", "SerializerFactory", "serializerFactory", "=", "getSerializerFactory", "(", ")", ";", "invoke", "(", "is", ",", "os", ",", "objectId", ",", "serializerFactory", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "ServletException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "throw", "new", "ServletException", "(", "e", ")", ";", "}", "finally", "{", "ServiceContext", ".", "end", "(", ")", ";", "}", "}" ]
Execute a request. The path-info of the request selects the bean. Once the bean's selected, it will be applied.
[ "Execute", "a", "request", ".", "The", "path", "-", "info", "of", "the", "request", "selects", "the", "bean", ".", "Once", "the", "bean", "s", "selected", "it", "will", "be", "applied", "." ]
train
https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/caucho/hessian/server/HessianServlet.java#L372-L413
before/uadetector
modules/uadetector-core/src/main/java/net/sf/uadetector/datareader/XmlDataReader.java
XmlDataReader.readXml
protected static Data readXml(@Nonnull final InputStream inputStream, @Nonnull final Charset charset) { """ Reads the <em>UAS data</em> in XML format based on the given URL.<br> <br> When during the reading errors occur which lead to a termination of the read operation, the information will be written to a log. The termination of the read operation will not lead to a program termination and in this case this method returns {@link Data#EMPTY}. @param inputStream an input stream for reading <em>UAS data</em> @param charset the character set in which the data should be read @return read in <em>UAS data</em> as {@code Data} instance @throws net.sf.qualitycheck.exception.IllegalNullArgumentException if any of the given arguments is {@code null} @throws net.sf.uadetector.exception.CanNotOpenStreamException if no stream to the given {@code URL} can be established """ Check.notNull(inputStream, "inputStream"); Check.notNull(charset, "charset"); final DataBuilder builder = new DataBuilder(); boolean hasErrors = false; try { XmlParser.parse(inputStream, builder); } catch (final ParserConfigurationException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final SAXException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IOException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IllegalStateException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final Exception e) { hasErrors = true; LOG.warn(e.getLocalizedMessage(), e); } finally { Closeables.closeAndConvert(inputStream, true); } return hasErrors ? Data.EMPTY : builder.build(); }
java
protected static Data readXml(@Nonnull final InputStream inputStream, @Nonnull final Charset charset) { Check.notNull(inputStream, "inputStream"); Check.notNull(charset, "charset"); final DataBuilder builder = new DataBuilder(); boolean hasErrors = false; try { XmlParser.parse(inputStream, builder); } catch (final ParserConfigurationException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final SAXException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IOException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IllegalStateException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final Exception e) { hasErrors = true; LOG.warn(e.getLocalizedMessage(), e); } finally { Closeables.closeAndConvert(inputStream, true); } return hasErrors ? Data.EMPTY : builder.build(); }
[ "protected", "static", "Data", "readXml", "(", "@", "Nonnull", "final", "InputStream", "inputStream", ",", "@", "Nonnull", "final", "Charset", "charset", ")", "{", "Check", ".", "notNull", "(", "inputStream", ",", "\"inputStream\"", ")", ";", "Check", ".", "notNull", "(", "charset", ",", "\"charset\"", ")", ";", "final", "DataBuilder", "builder", "=", "new", "DataBuilder", "(", ")", ";", "boolean", "hasErrors", "=", "false", ";", "try", "{", "XmlParser", ".", "parse", "(", "inputStream", ",", "builder", ")", ";", "}", "catch", "(", "final", "ParserConfigurationException", "e", ")", "{", "hasErrors", "=", "true", ";", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "catch", "(", "final", "SAXException", "e", ")", "{", "hasErrors", "=", "true", ";", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "hasErrors", "=", "true", ";", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "catch", "(", "final", "IllegalStateException", "e", ")", "{", "hasErrors", "=", "true", ";", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "hasErrors", "=", "true", ";", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "Closeables", ".", "closeAndConvert", "(", "inputStream", ",", "true", ")", ";", "}", "return", "hasErrors", "?", "Data", ".", "EMPTY", ":", "builder", ".", "build", "(", ")", ";", "}" ]
Reads the <em>UAS data</em> in XML format based on the given URL.<br> <br> When during the reading errors occur which lead to a termination of the read operation, the information will be written to a log. The termination of the read operation will not lead to a program termination and in this case this method returns {@link Data#EMPTY}. @param inputStream an input stream for reading <em>UAS data</em> @param charset the character set in which the data should be read @return read in <em>UAS data</em> as {@code Data} instance @throws net.sf.qualitycheck.exception.IllegalNullArgumentException if any of the given arguments is {@code null} @throws net.sf.uadetector.exception.CanNotOpenStreamException if no stream to the given {@code URL} can be established
[ "Reads", "the", "<em", ">", "UAS", "data<", "/", "em", ">", "in", "XML", "format", "based", "on", "the", "given", "URL", ".", "<br", ">", "<br", ">", "When", "during", "the", "reading", "errors", "occur", "which", "lead", "to", "a", "termination", "of", "the", "read", "operation", "the", "information", "will", "be", "written", "to", "a", "log", ".", "The", "termination", "of", "the", "read", "operation", "will", "not", "lead", "to", "a", "program", "termination", "and", "in", "this", "case", "this", "method", "returns", "{", "@link", "Data#EMPTY", "}", "." ]
train
https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/datareader/XmlDataReader.java#L104-L132
gocd/gocd
base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java
DirectoryScanner.isSymlink
private boolean isSymlink(File base, String path) { """ Do we have to traverse a symlink when trying to reach path from basedir? @param base base File (dir). @param path file path. @since Ant 1.6 """ return isSymlink(base, SelectorUtils.tokenizePath(path)); }
java
private boolean isSymlink(File base, String path) { return isSymlink(base, SelectorUtils.tokenizePath(path)); }
[ "private", "boolean", "isSymlink", "(", "File", "base", ",", "String", "path", ")", "{", "return", "isSymlink", "(", "base", ",", "SelectorUtils", ".", "tokenizePath", "(", "path", ")", ")", ";", "}" ]
Do we have to traverse a symlink when trying to reach path from basedir? @param base base File (dir). @param path file path. @since Ant 1.6
[ "Do", "we", "have", "to", "traverse", "a", "symlink", "when", "trying", "to", "reach", "path", "from", "basedir?" ]
train
https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java#L1584-L1586
pawelprazak/java-extended
hamcrest/src/main/java/com/bluecatcode/hamcrest/matchers/IsThrowable.java
IsThrowable.withMessage
@Factory public static <T extends Throwable> Matcher<T> withMessage(final Matcher<String> matcher) { """ Matches if value is a throwable with a message that matches the <tt>matcher</tt> @param matcher message matcher @param <T> the throwable type @return the matcher """ return new CustomTypeSafeMatcher<T>(CustomMatchers.fixedDescription("message ", matcher)) { @Override protected boolean matchesSafely(T item) { return matcher.matches(item.getMessage()); } public void describeMismatchSafely(T item, Description mismatchDescription) { matcher.describeMismatch(item.getMessage(), mismatchDescription); } }; }
java
@Factory public static <T extends Throwable> Matcher<T> withMessage(final Matcher<String> matcher) { return new CustomTypeSafeMatcher<T>(CustomMatchers.fixedDescription("message ", matcher)) { @Override protected boolean matchesSafely(T item) { return matcher.matches(item.getMessage()); } public void describeMismatchSafely(T item, Description mismatchDescription) { matcher.describeMismatch(item.getMessage(), mismatchDescription); } }; }
[ "@", "Factory", "public", "static", "<", "T", "extends", "Throwable", ">", "Matcher", "<", "T", ">", "withMessage", "(", "final", "Matcher", "<", "String", ">", "matcher", ")", "{", "return", "new", "CustomTypeSafeMatcher", "<", "T", ">", "(", "CustomMatchers", ".", "fixedDescription", "(", "\"message \"", ",", "matcher", ")", ")", "{", "@", "Override", "protected", "boolean", "matchesSafely", "(", "T", "item", ")", "{", "return", "matcher", ".", "matches", "(", "item", ".", "getMessage", "(", ")", ")", ";", "}", "public", "void", "describeMismatchSafely", "(", "T", "item", ",", "Description", "mismatchDescription", ")", "{", "matcher", ".", "describeMismatch", "(", "item", ".", "getMessage", "(", ")", ",", "mismatchDescription", ")", ";", "}", "}", ";", "}" ]
Matches if value is a throwable with a message that matches the <tt>matcher</tt> @param matcher message matcher @param <T> the throwable type @return the matcher
[ "Matches", "if", "value", "is", "a", "throwable", "with", "a", "message", "that", "matches", "the", "<tt", ">", "matcher<", "/", "tt", ">" ]
train
https://github.com/pawelprazak/java-extended/blob/ce1a556a95cbbf7c950a03662938bc02622de69b/hamcrest/src/main/java/com/bluecatcode/hamcrest/matchers/IsThrowable.java#L76-L88
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.editInlineCaption
public boolean editInlineCaption(String inlineMessageId, String caption, InlineReplyMarkup inlineReplyMarkup) { """ This allows you to edit the caption of any captionable inline message you have sent previously (The inline message must have an InlineReplyMarkup object attached in order to be editable) @param inlineMessageId The ID of the inline message you want to edit @param caption The new caption you want to display @param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message @return True if the edit succeeded, otherwise False """ if(caption != null && inlineReplyMarkup != null) { JSONObject jsonResponse = this.editMessageCaption(null, null, inlineMessageId, caption, inlineReplyMarkup); if(jsonResponse != null) { if(jsonResponse.getBoolean("result")) return true; } } return false; }
java
public boolean editInlineCaption(String inlineMessageId, String caption, InlineReplyMarkup inlineReplyMarkup) { if(caption != null && inlineReplyMarkup != null) { JSONObject jsonResponse = this.editMessageCaption(null, null, inlineMessageId, caption, inlineReplyMarkup); if(jsonResponse != null) { if(jsonResponse.getBoolean("result")) return true; } } return false; }
[ "public", "boolean", "editInlineCaption", "(", "String", "inlineMessageId", ",", "String", "caption", ",", "InlineReplyMarkup", "inlineReplyMarkup", ")", "{", "if", "(", "caption", "!=", "null", "&&", "inlineReplyMarkup", "!=", "null", ")", "{", "JSONObject", "jsonResponse", "=", "this", ".", "editMessageCaption", "(", "null", ",", "null", ",", "inlineMessageId", ",", "caption", ",", "inlineReplyMarkup", ")", ";", "if", "(", "jsonResponse", "!=", "null", ")", "{", "if", "(", "jsonResponse", ".", "getBoolean", "(", "\"result\"", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
This allows you to edit the caption of any captionable inline message you have sent previously (The inline message must have an InlineReplyMarkup object attached in order to be editable) @param inlineMessageId The ID of the inline message you want to edit @param caption The new caption you want to display @param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message @return True if the edit succeeded, otherwise False
[ "This", "allows", "you", "to", "edit", "the", "caption", "of", "any", "captionable", "inline", "message", "you", "have", "sent", "previously", "(", "The", "inline", "message", "must", "have", "an", "InlineReplyMarkup", "object", "attached", "in", "order", "to", "be", "editable", ")" ]
train
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L799-L812
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/history/CmsResourceHistoryTable.java
CmsResourceHistoryTable.addColumn
private void addColumn(String label, int width, Column<CmsHistoryResourceBean, ?> col) { """ Helper method for adding a table column with a given width and label.<p> @param label the column label @param width the column width in pixels @param col the column to add """ addColumn(col, label); setColumnWidth(col, width, Unit.PX); }
java
private void addColumn(String label, int width, Column<CmsHistoryResourceBean, ?> col) { addColumn(col, label); setColumnWidth(col, width, Unit.PX); }
[ "private", "void", "addColumn", "(", "String", "label", ",", "int", "width", ",", "Column", "<", "CmsHistoryResourceBean", ",", "?", ">", "col", ")", "{", "addColumn", "(", "col", ",", "label", ")", ";", "setColumnWidth", "(", "col", ",", "width", ",", "Unit", ".", "PX", ")", ";", "}" ]
Helper method for adding a table column with a given width and label.<p> @param label the column label @param width the column width in pixels @param col the column to add
[ "Helper", "method", "for", "adding", "a", "table", "column", "with", "a", "given", "width", "and", "label", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/history/CmsResourceHistoryTable.java#L132-L136
tomgibara/bits
src/main/java/com/tomgibara/bits/BitVector.java
BitVector.performSetAdj
private void performSetAdj(int position, boolean value) { """ specialized implementation for the common case of setting an individual bit """ checkMutable(); final int i = position >> ADDRESS_BITS; final long m = 1L << (position & ADDRESS_MASK); if (value) { bits[i] |= m; } else { bits[i] &= ~m; } }
java
private void performSetAdj(int position, boolean value) { checkMutable(); final int i = position >> ADDRESS_BITS; final long m = 1L << (position & ADDRESS_MASK); if (value) { bits[i] |= m; } else { bits[i] &= ~m; } }
[ "private", "void", "performSetAdj", "(", "int", "position", ",", "boolean", "value", ")", "{", "checkMutable", "(", ")", ";", "final", "int", "i", "=", "position", ">>", "ADDRESS_BITS", ";", "final", "long", "m", "=", "1L", "<<", "(", "position", "&", "ADDRESS_MASK", ")", ";", "if", "(", "value", ")", "{", "bits", "[", "i", "]", "|=", "m", ";", "}", "else", "{", "bits", "[", "i", "]", "&=", "~", "m", ";", "}", "}" ]
specialized implementation for the common case of setting an individual bit
[ "specialized", "implementation", "for", "the", "common", "case", "of", "setting", "an", "individual", "bit" ]
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/BitVector.java#L1741-L1750
khmarbaise/sapm
src/main/java/com/soebes/subversion/sapm/AccessRule.java
AccessRule.getAccess
public AccessLevel getAccess(User user, String repository, String path) { """ Convenience method if you have a {@link User} object instead of user name as a string. @param user The user for which you like to know the access level. @param repository The repository which will be checked for. @param path The path within the repository. @return The AccessLevel which represents the permission for the given user in the repository and the given path. """ return getAccess(user.getName(), repository, path); }
java
public AccessLevel getAccess(User user, String repository, String path) { return getAccess(user.getName(), repository, path); }
[ "public", "AccessLevel", "getAccess", "(", "User", "user", ",", "String", "repository", ",", "String", "path", ")", "{", "return", "getAccess", "(", "user", ".", "getName", "(", ")", ",", "repository", ",", "path", ")", ";", "}" ]
Convenience method if you have a {@link User} object instead of user name as a string. @param user The user for which you like to know the access level. @param repository The repository which will be checked for. @param path The path within the repository. @return The AccessLevel which represents the permission for the given user in the repository and the given path.
[ "Convenience", "method", "if", "you", "have", "a", "{" ]
train
https://github.com/khmarbaise/sapm/blob/b5da5b0d8929324f03cb3a4233a3534813f93eea/src/main/java/com/soebes/subversion/sapm/AccessRule.java#L190-L192
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UsersApi.java
UsersApi.supervisorRemotePlaceOperation
public ApiSuccessResponse supervisorRemotePlaceOperation(String dbid, SupervisorPlaceData supervisorPlaceData) throws ApiException { """ Log out the agent specified by the dbid. Log out the agent specified by the dbid. @param dbid The dbid of the agent. (required) @param supervisorPlaceData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = supervisorRemotePlaceOperationWithHttpInfo(dbid, supervisorPlaceData); return resp.getData(); }
java
public ApiSuccessResponse supervisorRemotePlaceOperation(String dbid, SupervisorPlaceData supervisorPlaceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = supervisorRemotePlaceOperationWithHttpInfo(dbid, supervisorPlaceData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "supervisorRemotePlaceOperation", "(", "String", "dbid", ",", "SupervisorPlaceData", "supervisorPlaceData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "supervisorRemotePlaceOperationWithHttpInfo", "(", "dbid", ",", "supervisorPlaceData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Log out the agent specified by the dbid. Log out the agent specified by the dbid. @param dbid The dbid of the agent. (required) @param supervisorPlaceData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Log", "out", "the", "agent", "specified", "by", "the", "dbid", ".", "Log", "out", "the", "agent", "specified", "by", "the", "dbid", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UsersApi.java#L569-L572
apache/incubator-shardingsphere
sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/OptimizeEngineFactory.java
OptimizeEngineFactory.newInstance
public static OptimizeEngine newInstance(final EncryptRule encryptRule, final SQLStatement sqlStatement, final List<Object> parameters) { """ Create encrypt optimize engine instance. @param encryptRule encrypt rule @param sqlStatement sql statement @param parameters parameters @return encrypt optimize engine instance """ if (sqlStatement instanceof InsertStatement) { return new EncryptInsertOptimizeEngine(encryptRule, (InsertStatement) sqlStatement, parameters); } return new EncryptDefaultOptimizeEngine(); }
java
public static OptimizeEngine newInstance(final EncryptRule encryptRule, final SQLStatement sqlStatement, final List<Object> parameters) { if (sqlStatement instanceof InsertStatement) { return new EncryptInsertOptimizeEngine(encryptRule, (InsertStatement) sqlStatement, parameters); } return new EncryptDefaultOptimizeEngine(); }
[ "public", "static", "OptimizeEngine", "newInstance", "(", "final", "EncryptRule", "encryptRule", ",", "final", "SQLStatement", "sqlStatement", ",", "final", "List", "<", "Object", ">", "parameters", ")", "{", "if", "(", "sqlStatement", "instanceof", "InsertStatement", ")", "{", "return", "new", "EncryptInsertOptimizeEngine", "(", "encryptRule", ",", "(", "InsertStatement", ")", "sqlStatement", ",", "parameters", ")", ";", "}", "return", "new", "EncryptDefaultOptimizeEngine", "(", ")", ";", "}" ]
Create encrypt optimize engine instance. @param encryptRule encrypt rule @param sqlStatement sql statement @param parameters parameters @return encrypt optimize engine instance
[ "Create", "encrypt", "optimize", "engine", "instance", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/OptimizeEngineFactory.java#L74-L79
apache/groovy
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.executeInsert
public List<GroovyRowResult> executeInsert(String sql, String[] keyColumnNames) throws SQLException { """ Executes the given SQL statement (typically an INSERT statement). This variant allows you to receive the values of any auto-generated columns, such as an autoincrement ID field (or fields) when you know the column name(s) of the ID field(s). <p> This method supports named and named ordinal parameters by supplying such parameters in the <code>params</code> array. See the class Javadoc for more details. @param sql The SQL statement to execute @param keyColumnNames an array of column names indicating the columns that should be returned from the inserted row or rows (some drivers may be case sensitive, e.g. may require uppercase names) @return A list of the auto-generated row results for each inserted row (typically auto-generated keys) @throws SQLException if a database access error occurs @since 2.3.2 """ Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); this.updateCount = statement.executeUpdate(sql, keyColumnNames); ResultSet keys = statement.getGeneratedKeys(); return asList(sql, keys); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } }
java
public List<GroovyRowResult> executeInsert(String sql, String[] keyColumnNames) throws SQLException { Connection connection = createConnection(); Statement statement = null; try { statement = getStatement(connection, sql); this.updateCount = statement.executeUpdate(sql, keyColumnNames); ResultSet keys = statement.getGeneratedKeys(); return asList(sql, keys); } catch (SQLException e) { LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage()); throw e; } finally { closeResources(connection, statement); } }
[ "public", "List", "<", "GroovyRowResult", ">", "executeInsert", "(", "String", "sql", ",", "String", "[", "]", "keyColumnNames", ")", "throws", "SQLException", "{", "Connection", "connection", "=", "createConnection", "(", ")", ";", "Statement", "statement", "=", "null", ";", "try", "{", "statement", "=", "getStatement", "(", "connection", ",", "sql", ")", ";", "this", ".", "updateCount", "=", "statement", ".", "executeUpdate", "(", "sql", ",", "keyColumnNames", ")", ";", "ResultSet", "keys", "=", "statement", ".", "getGeneratedKeys", "(", ")", ";", "return", "asList", "(", "sql", ",", "keys", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "LOG", ".", "warning", "(", "\"Failed to execute: \"", "+", "sql", "+", "\" because: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "e", ";", "}", "finally", "{", "closeResources", "(", "connection", ",", "statement", ")", ";", "}", "}" ]
Executes the given SQL statement (typically an INSERT statement). This variant allows you to receive the values of any auto-generated columns, such as an autoincrement ID field (or fields) when you know the column name(s) of the ID field(s). <p> This method supports named and named ordinal parameters by supplying such parameters in the <code>params</code> array. See the class Javadoc for more details. @param sql The SQL statement to execute @param keyColumnNames an array of column names indicating the columns that should be returned from the inserted row or rows (some drivers may be case sensitive, e.g. may require uppercase names) @return A list of the auto-generated row results for each inserted row (typically auto-generated keys) @throws SQLException if a database access error occurs @since 2.3.2
[ "Executes", "the", "given", "SQL", "statement", "(", "typically", "an", "INSERT", "statement", ")", ".", "This", "variant", "allows", "you", "to", "receive", "the", "values", "of", "any", "auto", "-", "generated", "columns", "such", "as", "an", "autoincrement", "ID", "field", "(", "or", "fields", ")", "when", "you", "know", "the", "column", "name", "(", "s", ")", "of", "the", "ID", "field", "(", "s", ")", ".", "<p", ">", "This", "method", "supports", "named", "and", "named", "ordinal", "parameters", "by", "supplying", "such", "parameters", "in", "the", "<code", ">", "params<", "/", "code", ">", "array", ".", "See", "the", "class", "Javadoc", "for", "more", "details", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L2774-L2788
icode/ameba
src/main/java/ameba/db/ebean/support/ModelResourceStructure.java
ModelResourceStructure.processCheckRowCountError
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception { """ <p>processCheckRowCountError.</p> @param t Transaction @param root root exception @param e exception @param process process method @param <T> model @return model @throws java.lang.Exception if any. """ if (e == null) { throw root; } if (e instanceof OptimisticLockException) { if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) { if (process != null) return process.call(t); } } return processCheckRowCountError(t, root, e.getCause(), process); }
java
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception { if (e == null) { throw root; } if (e instanceof OptimisticLockException) { if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) { if (process != null) return process.call(t); } } return processCheckRowCountError(t, root, e.getCause(), process); }
[ "protected", "<", "T", ">", "T", "processCheckRowCountError", "(", "Transaction", "t", ",", "Exception", "root", ",", "Throwable", "e", ",", "TxCallable", "<", "T", ">", "process", ")", "throws", "Exception", "{", "if", "(", "e", "==", "null", ")", "{", "throw", "root", ";", "}", "if", "(", "e", "instanceof", "OptimisticLockException", ")", "{", "if", "(", "\"checkRowCount\"", ".", "equals", "(", "e", ".", "getStackTrace", "(", ")", "[", "0", "]", ".", "getMethodName", "(", ")", ")", ")", "{", "if", "(", "process", "!=", "null", ")", "return", "process", ".", "call", "(", "t", ")", ";", "}", "}", "return", "processCheckRowCountError", "(", "t", ",", "root", ",", "e", ".", "getCause", "(", ")", ",", "process", ")", ";", "}" ]
<p>processCheckRowCountError.</p> @param t Transaction @param root root exception @param e exception @param process process method @param <T> model @return model @throws java.lang.Exception if any.
[ "<p", ">", "processCheckRowCountError", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L1076-L1087
operasoftware/operaprestodriver
src/com/opera/core/systems/internal/WatirUtils.java
WatirUtils.textMatchesWithANY
public static boolean textMatchesWithANY(String haystack, String needle) { """ Compares haystack and needle taking into the account that the needle may contain any number of ANY_MATCHER occurrences, that will be matched to any substring in haystack, i.e. "Show _ANY_ more..." will match anything like "Show 1 more...", "Show 2 more..." and so on. @param haystack the text that will be compared, may not contain any ANY_MATCHER occurrence @param needle the text that will be used for comparision, may contain any number of ANY_MATCHER occurrences @return a boolean indicating whether needle matched haystack. """ haystack = haystack.trim(); needle = needle.trim(); // Make sure we escape every character that is considered to be a special character inside a // regular expression. Matcher.quoteReplacement() takes care of '\\' and '$'. needle = Matcher.quoteReplacement(needle); String chars_to_be_escaped = ".|*?+(){}[]^"; for (char c : chars_to_be_escaped.toCharArray()) { String regex = "\\" + c; String replacement = "\\\\" + c; needle = needle.replaceAll(regex, replacement); } String pattern = needle.replaceAll(ANY_MATCHER, "(?:.+)"); logger.finest("Looking for pattern '" + pattern + "' in '" + haystack + "'"); return haystack.matches(pattern); }
java
public static boolean textMatchesWithANY(String haystack, String needle) { haystack = haystack.trim(); needle = needle.trim(); // Make sure we escape every character that is considered to be a special character inside a // regular expression. Matcher.quoteReplacement() takes care of '\\' and '$'. needle = Matcher.quoteReplacement(needle); String chars_to_be_escaped = ".|*?+(){}[]^"; for (char c : chars_to_be_escaped.toCharArray()) { String regex = "\\" + c; String replacement = "\\\\" + c; needle = needle.replaceAll(regex, replacement); } String pattern = needle.replaceAll(ANY_MATCHER, "(?:.+)"); logger.finest("Looking for pattern '" + pattern + "' in '" + haystack + "'"); return haystack.matches(pattern); }
[ "public", "static", "boolean", "textMatchesWithANY", "(", "String", "haystack", ",", "String", "needle", ")", "{", "haystack", "=", "haystack", ".", "trim", "(", ")", ";", "needle", "=", "needle", ".", "trim", "(", ")", ";", "// Make sure we escape every character that is considered to be a special character inside a", "// regular expression. Matcher.quoteReplacement() takes care of '\\\\' and '$'.", "needle", "=", "Matcher", ".", "quoteReplacement", "(", "needle", ")", ";", "String", "chars_to_be_escaped", "=", "\".|*?+(){}[]^\"", ";", "for", "(", "char", "c", ":", "chars_to_be_escaped", ".", "toCharArray", "(", ")", ")", "{", "String", "regex", "=", "\"\\\\\"", "+", "c", ";", "String", "replacement", "=", "\"\\\\\\\\\"", "+", "c", ";", "needle", "=", "needle", ".", "replaceAll", "(", "regex", ",", "replacement", ")", ";", "}", "String", "pattern", "=", "needle", ".", "replaceAll", "(", "ANY_MATCHER", ",", "\"(?:.+)\"", ")", ";", "logger", ".", "finest", "(", "\"Looking for pattern '\"", "+", "pattern", "+", "\"' in '\"", "+", "haystack", "+", "\"'\"", ")", ";", "return", "haystack", ".", "matches", "(", "pattern", ")", ";", "}" ]
Compares haystack and needle taking into the account that the needle may contain any number of ANY_MATCHER occurrences, that will be matched to any substring in haystack, i.e. "Show _ANY_ more..." will match anything like "Show 1 more...", "Show 2 more..." and so on. @param haystack the text that will be compared, may not contain any ANY_MATCHER occurrence @param needle the text that will be used for comparision, may contain any number of ANY_MATCHER occurrences @return a boolean indicating whether needle matched haystack.
[ "Compares", "haystack", "and", "needle", "taking", "into", "the", "account", "that", "the", "needle", "may", "contain", "any", "number", "of", "ANY_MATCHER", "occurrences", "that", "will", "be", "matched", "to", "any", "substring", "in", "haystack", "i", ".", "e", ".", "Show", "_ANY_", "more", "...", "will", "match", "anything", "like", "Show", "1", "more", "...", "Show", "2", "more", "...", "and", "so", "on", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/internal/WatirUtils.java#L133-L152
petrbouda/joyrest
joyrest-core/src/main/java/org/joyrest/context/ApplicationContextImpl.java
ApplicationContextImpl.setExceptionHandlers
public void setExceptionHandlers(Map<Class<? extends Exception>, InternalExceptionHandler> handlers) { """ Adds a map of {@link ExceptionHandler} into the application @param handlers configurations which keep given handlers """ requireNonNull(handlers); this.exceptionHandlers = handlers; }
java
public void setExceptionHandlers(Map<Class<? extends Exception>, InternalExceptionHandler> handlers) { requireNonNull(handlers); this.exceptionHandlers = handlers; }
[ "public", "void", "setExceptionHandlers", "(", "Map", "<", "Class", "<", "?", "extends", "Exception", ">", ",", "InternalExceptionHandler", ">", "handlers", ")", "{", "requireNonNull", "(", "handlers", ")", ";", "this", ".", "exceptionHandlers", "=", "handlers", ";", "}" ]
Adds a map of {@link ExceptionHandler} into the application @param handlers configurations which keep given handlers
[ "Adds", "a", "map", "of", "{", "@link", "ExceptionHandler", "}", "into", "the", "application" ]
train
https://github.com/petrbouda/joyrest/blob/58903f06fb7f0b8fdf1ef91318fb48a88bf970e0/joyrest-core/src/main/java/org/joyrest/context/ApplicationContextImpl.java#L64-L67
primefaces/primefaces
src/main/java/org/primefaces/application/exceptionhandler/PrimeExceptionHandler.java
PrimeExceptionHandler.buildView
protected Throwable buildView(FacesContext context, Throwable throwable, Throwable rootCause) throws IOException { """ Builds the view if not already available. This is mostly required for ViewExpiredException's. @param context The {@link FacesContext}. @param throwable The occurred {@link Throwable}. @param rootCause The root cause. @return The unwrapped {@link Throwable}. @throws java.io.IOException If building the view fails. """ if (context.getViewRoot() == null) { ViewHandler viewHandler = context.getApplication().getViewHandler(); String viewId = viewHandler.deriveViewId(context, ComponentUtils.calculateViewId(context)); ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, viewId); UIViewRoot viewRoot = vdl.createView(context, viewId); context.setViewRoot(viewRoot); vdl.buildView(context, viewRoot); // Workaround for Mojarra // if UIViewRoot == null -> 'IllegalArgumentException' is throwed instead of 'ViewExpiredException' if (rootCause == null && throwable instanceof IllegalArgumentException) { rootCause = new javax.faces.application.ViewExpiredException(viewId); } } return rootCause; }
java
protected Throwable buildView(FacesContext context, Throwable throwable, Throwable rootCause) throws IOException { if (context.getViewRoot() == null) { ViewHandler viewHandler = context.getApplication().getViewHandler(); String viewId = viewHandler.deriveViewId(context, ComponentUtils.calculateViewId(context)); ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, viewId); UIViewRoot viewRoot = vdl.createView(context, viewId); context.setViewRoot(viewRoot); vdl.buildView(context, viewRoot); // Workaround for Mojarra // if UIViewRoot == null -> 'IllegalArgumentException' is throwed instead of 'ViewExpiredException' if (rootCause == null && throwable instanceof IllegalArgumentException) { rootCause = new javax.faces.application.ViewExpiredException(viewId); } } return rootCause; }
[ "protected", "Throwable", "buildView", "(", "FacesContext", "context", ",", "Throwable", "throwable", ",", "Throwable", "rootCause", ")", "throws", "IOException", "{", "if", "(", "context", ".", "getViewRoot", "(", ")", "==", "null", ")", "{", "ViewHandler", "viewHandler", "=", "context", ".", "getApplication", "(", ")", ".", "getViewHandler", "(", ")", ";", "String", "viewId", "=", "viewHandler", ".", "deriveViewId", "(", "context", ",", "ComponentUtils", ".", "calculateViewId", "(", "context", ")", ")", ";", "ViewDeclarationLanguage", "vdl", "=", "viewHandler", ".", "getViewDeclarationLanguage", "(", "context", ",", "viewId", ")", ";", "UIViewRoot", "viewRoot", "=", "vdl", ".", "createView", "(", "context", ",", "viewId", ")", ";", "context", ".", "setViewRoot", "(", "viewRoot", ")", ";", "vdl", ".", "buildView", "(", "context", ",", "viewRoot", ")", ";", "// Workaround for Mojarra", "// if UIViewRoot == null -> 'IllegalArgumentException' is throwed instead of 'ViewExpiredException'", "if", "(", "rootCause", "==", "null", "&&", "throwable", "instanceof", "IllegalArgumentException", ")", "{", "rootCause", "=", "new", "javax", ".", "faces", ".", "application", ".", "ViewExpiredException", "(", "viewId", ")", ";", "}", "}", "return", "rootCause", ";", "}" ]
Builds the view if not already available. This is mostly required for ViewExpiredException's. @param context The {@link FacesContext}. @param throwable The occurred {@link Throwable}. @param rootCause The root cause. @return The unwrapped {@link Throwable}. @throws java.io.IOException If building the view fails.
[ "Builds", "the", "view", "if", "not", "already", "available", ".", "This", "is", "mostly", "required", "for", "ViewExpiredException", "s", "." ]
train
https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/application/exceptionhandler/PrimeExceptionHandler.java#L318-L337
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geodesy/SphereUtil.java
SphereUtil.alongTrackDistanceDeg
public static double alongTrackDistanceDeg(double lat1, double lon1, double lat2, double lon2, double latQ, double lonQ, double dist1Q, double ctd) { """ The along track distance is the distance from S to Q along the track from S to E. <p> ATD=acos(cos(dist_SQ)/cos(XTD)) @param lat1 Latitude of starting point. @param lon1 Longitude of starting point. @param lat2 Latitude of destination point. @param lon2 Longitude of destination point. @param latQ Latitude of query point. @param lonQ Longitude of query point. @param dist1Q Distance S to Q in radians. @param ctd Cross-track-distance in radians. @return Along-track distance in radians. May be negative - this gives the side. """ return alongTrackDistanceRad(deg2rad(lat1), deg2rad(lon1), deg2rad(lat2), deg2rad(lon2), deg2rad(latQ), deg2rad(lonQ), dist1Q, ctd); }
java
public static double alongTrackDistanceDeg(double lat1, double lon1, double lat2, double lon2, double latQ, double lonQ, double dist1Q, double ctd) { return alongTrackDistanceRad(deg2rad(lat1), deg2rad(lon1), deg2rad(lat2), deg2rad(lon2), deg2rad(latQ), deg2rad(lonQ), dist1Q, ctd); }
[ "public", "static", "double", "alongTrackDistanceDeg", "(", "double", "lat1", ",", "double", "lon1", ",", "double", "lat2", ",", "double", "lon2", ",", "double", "latQ", ",", "double", "lonQ", ",", "double", "dist1Q", ",", "double", "ctd", ")", "{", "return", "alongTrackDistanceRad", "(", "deg2rad", "(", "lat1", ")", ",", "deg2rad", "(", "lon1", ")", ",", "deg2rad", "(", "lat2", ")", ",", "deg2rad", "(", "lon2", ")", ",", "deg2rad", "(", "latQ", ")", ",", "deg2rad", "(", "lonQ", ")", ",", "dist1Q", ",", "ctd", ")", ";", "}" ]
The along track distance is the distance from S to Q along the track from S to E. <p> ATD=acos(cos(dist_SQ)/cos(XTD)) @param lat1 Latitude of starting point. @param lon1 Longitude of starting point. @param lat2 Latitude of destination point. @param lon2 Longitude of destination point. @param latQ Latitude of query point. @param lonQ Longitude of query point. @param dist1Q Distance S to Q in radians. @param ctd Cross-track-distance in radians. @return Along-track distance in radians. May be negative - this gives the side.
[ "The", "along", "track", "distance", "is", "the", "distance", "from", "S", "to", "Q", "along", "the", "track", "from", "S", "to", "E", ".", "<p", ">", "ATD", "=", "acos", "(", "cos", "(", "dist_SQ", ")", "/", "cos", "(", "XTD", "))" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geodesy/SphereUtil.java#L593-L595
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java
ClassUtil.hasBeanMethods
public static boolean hasBeanMethods(Class<?> type, String propertyName, Class<?> propertyType, boolean caseSensitive) { """ Checks if the class implements public "bean" methods (get and set) for the name. For example, for a name such as "firstName", this method will check if the class has both getFirstName() and setFirstName() methods. Also, this method will validate the return type matches the paramType on the getXXX() method and that the setXXX() method only accepts that paramType. The search is optionally case sensitive. @param type The class to search @param propertyName The property name to search for, if "firstName", then this method will internally add the "get" and "set" to the beginning. @param propertyType The class type of the property @param caseSensitive If the search is case sensitive or not @return True if the "bean" methods are correct, otherwise false. """ try { // if this succeeds without an exception, then the properties exist! @SuppressWarnings("unused") Method[] methods = getBeanMethods(type, propertyName, propertyType, caseSensitive); return true; } catch (Exception e) { return false; } }
java
public static boolean hasBeanMethods(Class<?> type, String propertyName, Class<?> propertyType, boolean caseSensitive) { try { // if this succeeds without an exception, then the properties exist! @SuppressWarnings("unused") Method[] methods = getBeanMethods(type, propertyName, propertyType, caseSensitive); return true; } catch (Exception e) { return false; } }
[ "public", "static", "boolean", "hasBeanMethods", "(", "Class", "<", "?", ">", "type", ",", "String", "propertyName", ",", "Class", "<", "?", ">", "propertyType", ",", "boolean", "caseSensitive", ")", "{", "try", "{", "// if this succeeds without an exception, then the properties exist!", "@", "SuppressWarnings", "(", "\"unused\"", ")", "Method", "[", "]", "methods", "=", "getBeanMethods", "(", "type", ",", "propertyName", ",", "propertyType", ",", "caseSensitive", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks if the class implements public "bean" methods (get and set) for the name. For example, for a name such as "firstName", this method will check if the class has both getFirstName() and setFirstName() methods. Also, this method will validate the return type matches the paramType on the getXXX() method and that the setXXX() method only accepts that paramType. The search is optionally case sensitive. @param type The class to search @param propertyName The property name to search for, if "firstName", then this method will internally add the "get" and "set" to the beginning. @param propertyType The class type of the property @param caseSensitive If the search is case sensitive or not @return True if the "bean" methods are correct, otherwise false.
[ "Checks", "if", "the", "class", "implements", "public", "bean", "methods", "(", "get", "and", "set", ")", "for", "the", "name", ".", "For", "example", "for", "a", "name", "such", "as", "firstName", "this", "method", "will", "check", "if", "the", "class", "has", "both", "getFirstName", "()", "and", "setFirstName", "()", "methods", ".", "Also", "this", "method", "will", "validate", "the", "return", "type", "matches", "the", "paramType", "on", "the", "getXXX", "()", "method", "and", "that", "the", "setXXX", "()", "method", "only", "accepts", "that", "paramType", ".", "The", "search", "is", "optionally", "case", "sensitive", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java#L102-L111
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/slider/SliderRenderer.java
SliderRenderer.encodeBegin
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { """ This methods generates the HTML code of the current b:slider. @param context the FacesContext. @param component the current b:slider. @throws IOException thrown if something goes wrong when writing the HTML code. """ if (!component.isRendered()) { return; } Slider slider = (Slider) component; ResponseWriter rw = context.getResponseWriter(); encodeHTML(slider, context, rw); Tooltip.activateTooltips(context, slider); }
java
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } Slider slider = (Slider) component; ResponseWriter rw = context.getResponseWriter(); encodeHTML(slider, context, rw); Tooltip.activateTooltips(context, slider); }
[ "@", "Override", "public", "void", "encodeBegin", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "throws", "IOException", "{", "if", "(", "!", "component", ".", "isRendered", "(", ")", ")", "{", "return", ";", "}", "Slider", "slider", "=", "(", "Slider", ")", "component", ";", "ResponseWriter", "rw", "=", "context", ".", "getResponseWriter", "(", ")", ";", "encodeHTML", "(", "slider", ",", "context", ",", "rw", ")", ";", "Tooltip", ".", "activateTooltips", "(", "context", ",", "slider", ")", ";", "}" ]
This methods generates the HTML code of the current b:slider. @param context the FacesContext. @param component the current b:slider. @throws IOException thrown if something goes wrong when writing the HTML code.
[ "This", "methods", "generates", "the", "HTML", "code", "of", "the", "current", "b", ":", "slider", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/slider/SliderRenderer.java#L81-L91
molgenis/molgenis
molgenis-api-data/src/main/java/org/molgenis/api/data/v1/RestController.java
RestController.retrieveEntityAttributeMetaPost
@PostMapping( value = "/ { """ Same as retrieveEntityAttributeMeta (GET) only tunneled through POST. @return EntityType """entityTypeId}/meta/{attributeName}", params = "_method=GET", produces = APPLICATION_JSON_VALUE) public AttributeResponse retrieveEntityAttributeMetaPost( @PathVariable("entityTypeId") String entityTypeId, @PathVariable("attributeName") String attributeName, @Valid @RequestBody EntityTypeRequest request) { Set<String> attributeSet = toAttributeSet(request != null ? request.getAttributes() : null); Map<String, Set<String>> attributeExpandSet = toExpandMap(request != null ? request.getExpand() : null); return getAttributePostInternal(entityTypeId, attributeName, attributeSet, attributeExpandSet); }
java
@PostMapping( value = "/{entityTypeId}/meta/{attributeName}", params = "_method=GET", produces = APPLICATION_JSON_VALUE) public AttributeResponse retrieveEntityAttributeMetaPost( @PathVariable("entityTypeId") String entityTypeId, @PathVariable("attributeName") String attributeName, @Valid @RequestBody EntityTypeRequest request) { Set<String> attributeSet = toAttributeSet(request != null ? request.getAttributes() : null); Map<String, Set<String>> attributeExpandSet = toExpandMap(request != null ? request.getExpand() : null); return getAttributePostInternal(entityTypeId, attributeName, attributeSet, attributeExpandSet); }
[ "@", "PostMapping", "(", "value", "=", "\"/{entityTypeId}/meta/{attributeName}\"", ",", "params", "=", "\"_method=GET\"", ",", "produces", "=", "APPLICATION_JSON_VALUE", ")", "public", "AttributeResponse", "retrieveEntityAttributeMetaPost", "(", "@", "PathVariable", "(", "\"entityTypeId\"", ")", "String", "entityTypeId", ",", "@", "PathVariable", "(", "\"attributeName\"", ")", "String", "attributeName", ",", "@", "Valid", "@", "RequestBody", "EntityTypeRequest", "request", ")", "{", "Set", "<", "String", ">", "attributeSet", "=", "toAttributeSet", "(", "request", "!=", "null", "?", "request", ".", "getAttributes", "(", ")", ":", "null", ")", ";", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "attributeExpandSet", "=", "toExpandMap", "(", "request", "!=", "null", "?", "request", ".", "getExpand", "(", ")", ":", "null", ")", ";", "return", "getAttributePostInternal", "(", "entityTypeId", ",", "attributeName", ",", "attributeSet", ",", "attributeExpandSet", ")", ";", "}" ]
Same as retrieveEntityAttributeMeta (GET) only tunneled through POST. @return EntityType
[ "Same", "as", "retrieveEntityAttributeMeta", "(", "GET", ")", "only", "tunneled", "through", "POST", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-api-data/src/main/java/org/molgenis/api/data/v1/RestController.java#L234-L247
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java
CmsInheritanceContainerEditor.createOptionBar
private CmsElementOptionBar createOptionBar(CmsContainerPageElementPanel elementWidget) { """ Creates an option bar for the given element.<p> @param elementWidget the element widget @return the option bar """ CmsElementOptionBar optionBar = new CmsElementOptionBar(elementWidget); CmsPushButton button = new CmsRemoveOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsFavoritesOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsSettingsOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsInfoOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsAddOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsInheritedOptionButton(elementWidget, this); optionBar.add(button); button = new CmsMoveOptionButton(elementWidget, this); // setting the drag and drop handler button.addMouseDownHandler(getController().getDndHandler()); optionBar.add(button); button = new CmsEditOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); return optionBar; }
java
private CmsElementOptionBar createOptionBar(CmsContainerPageElementPanel elementWidget) { CmsElementOptionBar optionBar = new CmsElementOptionBar(elementWidget); CmsPushButton button = new CmsRemoveOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsFavoritesOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsSettingsOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsInfoOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsAddOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); button = new CmsInheritedOptionButton(elementWidget, this); optionBar.add(button); button = new CmsMoveOptionButton(elementWidget, this); // setting the drag and drop handler button.addMouseDownHandler(getController().getDndHandler()); optionBar.add(button); button = new CmsEditOptionButton(elementWidget, this); button.addClickHandler(m_optionClickHandler); optionBar.add(button); return optionBar; }
[ "private", "CmsElementOptionBar", "createOptionBar", "(", "CmsContainerPageElementPanel", "elementWidget", ")", "{", "CmsElementOptionBar", "optionBar", "=", "new", "CmsElementOptionBar", "(", "elementWidget", ")", ";", "CmsPushButton", "button", "=", "new", "CmsRemoveOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsFavoritesOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsSettingsOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsInfoOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsAddOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsInheritedOptionButton", "(", "elementWidget", ",", "this", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsMoveOptionButton", "(", "elementWidget", ",", "this", ")", ";", "// setting the drag and drop handler\r", "button", ".", "addMouseDownHandler", "(", "getController", "(", ")", ".", "getDndHandler", "(", ")", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "button", "=", "new", "CmsEditOptionButton", "(", "elementWidget", ",", "this", ")", ";", "button", ".", "addClickHandler", "(", "m_optionClickHandler", ")", ";", "optionBar", ".", "add", "(", "button", ")", ";", "return", "optionBar", ";", "}" ]
Creates an option bar for the given element.<p> @param elementWidget the element widget @return the option bar
[ "Creates", "an", "option", "bar", "for", "the", "given", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java#L528-L564
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java
SigninFormPanel.newButton
protected Button newButton(final String id) { """ Factory method for creating the new {@link Button}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Button}. @param id the id @return the new {@link Button} """ return new AjaxButton(id) { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Listener method invoked on form submit with errors * * @param target * @param form */ @Override protected void onError(final AjaxRequestTarget target, final Form<?> form) { SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form); } /** * {@inheritDoc} */ @Override public void onSubmit(final AjaxRequestTarget target, final Form<?> form) { SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form); } }; }
java
protected Button newButton(final String id) { return new AjaxButton(id) { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Listener method invoked on form submit with errors * * @param target * @param form */ @Override protected void onError(final AjaxRequestTarget target, final Form<?> form) { SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form); } /** * {@inheritDoc} */ @Override public void onSubmit(final AjaxRequestTarget target, final Form<?> form) { SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form); } }; }
[ "protected", "Button", "newButton", "(", "final", "String", "id", ")", "{", "return", "new", "AjaxButton", "(", "id", ")", "{", "/**\n\t\t\t * The serialVersionUID.\n\t\t\t */", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n\t\t\t * Listener method invoked on form submit with errors\n\t\t\t *\n\t\t\t * @param target\n\t\t\t * @param form\n\t\t\t */", "@", "Override", "protected", "void", "onError", "(", "final", "AjaxRequestTarget", "target", ",", "final", "Form", "<", "?", ">", "form", ")", "{", "SigninFormPanel", ".", "this", ".", "onSignin", "(", "target", ",", "SigninFormPanel", ".", "this", ".", "form", ")", ";", "}", "/**\n\t\t\t * {@inheritDoc}\n\t\t\t */", "@", "Override", "public", "void", "onSubmit", "(", "final", "AjaxRequestTarget", "target", ",", "final", "Form", "<", "?", ">", "form", ")", "{", "SigninFormPanel", ".", "this", ".", "onSignin", "(", "target", ",", "SigninFormPanel", ".", "this", ".", "form", ")", ";", "}", "}", ";", "}" ]
Factory method for creating the new {@link Button}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Button}. @param id the id @return the new {@link Button}
[ "Factory", "method", "for", "creating", "the", "new", "{", "@link", "Button", "}", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridden", "so", "users", "can", "provide", "their", "own", "version", "of", "a", "new", "{", "@link", "Button", "}", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java#L90-L121
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/GeoParser.java
GeoParser.parse
public List<ResolvedLocation> parse(String inputText) throws Exception { """ Takes an unstructured text document (as a String), extracts the location names contained therein, and resolves them into geographic entities representing the best match for those location names. @param inputText unstructured text to be processed @return list of geo entities resolved from text @throws Exception """ return parse(inputText, ClavinLocationResolver.DEFAULT_ANCESTRY_MODE); }
java
public List<ResolvedLocation> parse(String inputText) throws Exception { return parse(inputText, ClavinLocationResolver.DEFAULT_ANCESTRY_MODE); }
[ "public", "List", "<", "ResolvedLocation", ">", "parse", "(", "String", "inputText", ")", "throws", "Exception", "{", "return", "parse", "(", "inputText", ",", "ClavinLocationResolver", ".", "DEFAULT_ANCESTRY_MODE", ")", ";", "}" ]
Takes an unstructured text document (as a String), extracts the location names contained therein, and resolves them into geographic entities representing the best match for those location names. @param inputText unstructured text to be processed @return list of geo entities resolved from text @throws Exception
[ "Takes", "an", "unstructured", "text", "document", "(", "as", "a", "String", ")", "extracts", "the", "location", "names", "contained", "therein", "and", "resolves", "them", "into", "geographic", "entities", "representing", "the", "best", "match", "for", "those", "location", "names", "." ]
train
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParser.java#L96-L98
morimekta/utils
io-util/src/main/java/net/morimekta/util/FileWatcher.java
FileWatcher.addWatcher
@Deprecated public void addWatcher(File file, Listener watcher) { """ Start watching file path and notify watcher for updates on that file. @param file The file path to watch. @param watcher The watcher to be notified. @deprecated Use {@link #addWatcher(Path, Listener)} """ addWatcher(file.toPath(), watcher); }
java
@Deprecated public void addWatcher(File file, Listener watcher) { addWatcher(file.toPath(), watcher); }
[ "@", "Deprecated", "public", "void", "addWatcher", "(", "File", "file", ",", "Listener", "watcher", ")", "{", "addWatcher", "(", "file", ".", "toPath", "(", ")", ",", "watcher", ")", ";", "}" ]
Start watching file path and notify watcher for updates on that file. @param file The file path to watch. @param watcher The watcher to be notified. @deprecated Use {@link #addWatcher(Path, Listener)}
[ "Start", "watching", "file", "path", "and", "notify", "watcher", "for", "updates", "on", "that", "file", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/FileWatcher.java#L176-L179
kite-sdk/kite
kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/shaded/com/google/common/reflect/FluentIterable.java
FluentIterable.transform
public final <T> FluentIterable<T> transform(Function<? super E, T> function) { """ Returns a fluent iterable that applies {@code function} to each element of this fluent iterable. <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's iterator does. After a successful {@code remove()} call, this fluent iterable no longer contains the corresponding element. """ return from(Iterables.transform(iterable, function)); }
java
public final <T> FluentIterable<T> transform(Function<? super E, T> function) { return from(Iterables.transform(iterable, function)); }
[ "public", "final", "<", "T", ">", "FluentIterable", "<", "T", ">", "transform", "(", "Function", "<", "?", "super", "E", ",", "T", ">", "function", ")", "{", "return", "from", "(", "Iterables", ".", "transform", "(", "iterable", ",", "function", ")", ")", ";", "}" ]
Returns a fluent iterable that applies {@code function} to each element of this fluent iterable. <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's iterator does. After a successful {@code remove()} call, this fluent iterable no longer contains the corresponding element.
[ "Returns", "a", "fluent", "iterable", "that", "applies", "{", "@code", "function", "}", "to", "each", "element", "of", "this", "fluent", "iterable", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/shaded/com/google/common/reflect/FluentIterable.java#L203-L205
aws/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StreamingStep.java
StreamingStep.withHadoopConfig
public StreamingStep withHadoopConfig(String key, String value) { """ Add a Hadoop config override (-D value). @param key Hadoop configuration key. @param value Configuration value. @return A reference to this updated object so that method calls can be chained together. """ hadoopConfig.put(key, value); return this; }
java
public StreamingStep withHadoopConfig(String key, String value) { hadoopConfig.put(key, value); return this; }
[ "public", "StreamingStep", "withHadoopConfig", "(", "String", "key", ",", "String", "value", ")", "{", "hadoopConfig", ".", "put", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add a Hadoop config override (-D value). @param key Hadoop configuration key. @param value Configuration value. @return A reference to this updated object so that method calls can be chained together.
[ "Add", "a", "Hadoop", "config", "override", "(", "-", "D", "value", ")", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StreamingStep.java#L217-L220
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.toSortedString
public static <T> String toSortedString(Counter<T> counter, int k, String itemFormat, String joiner, String wrapperFormat) { """ Returns a string representation of a Counter, displaying the keys and their counts in decreasing order of count. At most k keys are displayed. Note that this method subsumes many of the other toString methods, e.g.: toString(c, k) and toBiggestValuesFirstString(c, k) => toSortedString(c, k, "%s=%f", ", ", "[%s]") toVerticalString(c, k) => toSortedString(c, k, "%2$g\t%1$s", "\n", "%s\n") @param counter A Counter. @param k The number of keys to include. Use Integer.MAX_VALUE to include all keys. @param itemFormat The format string for key/count pairs, where the key is first and the value is second. To display the value first, use argument indices, e.g. "%2$f %1$s". @param joiner The string used between pairs of key/value strings. @param wrapperFormat The format string for wrapping text around the joined items, where the joined item string value is "%s". @return The top k values from the Counter, formatted as specified. """ PriorityQueue<T> queue = toPriorityQueue(counter); List<String> strings = new ArrayList<String>(); for (int rank = 0; rank < k && !queue.isEmpty(); ++rank) { T key = queue.removeFirst(); double value = counter.getCount(key); strings.add(String.format(itemFormat, key, value)); } return String.format(wrapperFormat, StringUtils.join(strings, joiner)); }
java
public static <T> String toSortedString(Counter<T> counter, int k, String itemFormat, String joiner, String wrapperFormat) { PriorityQueue<T> queue = toPriorityQueue(counter); List<String> strings = new ArrayList<String>(); for (int rank = 0; rank < k && !queue.isEmpty(); ++rank) { T key = queue.removeFirst(); double value = counter.getCount(key); strings.add(String.format(itemFormat, key, value)); } return String.format(wrapperFormat, StringUtils.join(strings, joiner)); }
[ "public", "static", "<", "T", ">", "String", "toSortedString", "(", "Counter", "<", "T", ">", "counter", ",", "int", "k", ",", "String", "itemFormat", ",", "String", "joiner", ",", "String", "wrapperFormat", ")", "{", "PriorityQueue", "<", "T", ">", "queue", "=", "toPriorityQueue", "(", "counter", ")", ";", "List", "<", "String", ">", "strings", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "int", "rank", "=", "0", ";", "rank", "<", "k", "&&", "!", "queue", ".", "isEmpty", "(", ")", ";", "++", "rank", ")", "{", "T", "key", "=", "queue", ".", "removeFirst", "(", ")", ";", "double", "value", "=", "counter", ".", "getCount", "(", "key", ")", ";", "strings", ".", "add", "(", "String", ".", "format", "(", "itemFormat", ",", "key", ",", "value", ")", ")", ";", "}", "return", "String", ".", "format", "(", "wrapperFormat", ",", "StringUtils", ".", "join", "(", "strings", ",", "joiner", ")", ")", ";", "}" ]
Returns a string representation of a Counter, displaying the keys and their counts in decreasing order of count. At most k keys are displayed. Note that this method subsumes many of the other toString methods, e.g.: toString(c, k) and toBiggestValuesFirstString(c, k) => toSortedString(c, k, "%s=%f", ", ", "[%s]") toVerticalString(c, k) => toSortedString(c, k, "%2$g\t%1$s", "\n", "%s\n") @param counter A Counter. @param k The number of keys to include. Use Integer.MAX_VALUE to include all keys. @param itemFormat The format string for key/count pairs, where the key is first and the value is second. To display the value first, use argument indices, e.g. "%2$f %1$s". @param joiner The string used between pairs of key/value strings. @param wrapperFormat The format string for wrapping text around the joined items, where the joined item string value is "%s". @return The top k values from the Counter, formatted as specified.
[ "Returns", "a", "string", "representation", "of", "a", "Counter", "displaying", "the", "keys", "and", "their", "counts", "in", "decreasing", "order", "of", "count", ".", "At", "most", "k", "keys", "are", "displayed", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L1764-L1773
alkacon/opencms-core
src/org/opencms/ui/apps/lists/CmsListManager.java
CmsListManager.setBackendSpecificOptions
private void setBackendSpecificOptions(CmsSimpleSearchConfigurationParser configParser, Locale locale) { """ Sets options which are specific to the backend list manager on the cnofiguration parser.<p> @param configParser the configuration parser @param locale the search locale """ configParser.setSearchLocale(locale); configParser.setIgnoreBlacklist(true); configParser.setPagination(PAGINATION); }
java
private void setBackendSpecificOptions(CmsSimpleSearchConfigurationParser configParser, Locale locale) { configParser.setSearchLocale(locale); configParser.setIgnoreBlacklist(true); configParser.setPagination(PAGINATION); }
[ "private", "void", "setBackendSpecificOptions", "(", "CmsSimpleSearchConfigurationParser", "configParser", ",", "Locale", "locale", ")", "{", "configParser", ".", "setSearchLocale", "(", "locale", ")", ";", "configParser", ".", "setIgnoreBlacklist", "(", "true", ")", ";", "configParser", ".", "setPagination", "(", "PAGINATION", ")", ";", "}" ]
Sets options which are specific to the backend list manager on the cnofiguration parser.<p> @param configParser the configuration parser @param locale the search locale
[ "Sets", "options", "which", "are", "specific", "to", "the", "backend", "list", "manager", "on", "the", "cnofiguration", "parser", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/lists/CmsListManager.java#L2198-L2203
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/AttributesImplSerializer.java
AttributesImplSerializer.getIndex
public final int getIndex(String uri, String localName) { """ This method gets the index of an attribute given its uri and locanName. @param uri the URI of the attribute name. @param localName the local namer (after the ':' ) of the attribute name. @return the integer index of the attribute. @see org.xml.sax.Attributes#getIndex(String) """ int index; if (super.getLength() < MAX) { // if we haven't got too many attributes let the // super class look it up index = super.getIndex(uri,localName); return index; } // we have too many attributes and the super class is slow // so find it quickly using our Hashtable. // Form the key of format "{uri}localName" m_buff.setLength(0); m_buff.append('{').append(uri).append('}').append(localName); String key = m_buff.toString(); Integer i = (Integer)m_indexFromQName.get(key); if (i == null) index = -1; else index = i.intValue(); return index; }
java
public final int getIndex(String uri, String localName) { int index; if (super.getLength() < MAX) { // if we haven't got too many attributes let the // super class look it up index = super.getIndex(uri,localName); return index; } // we have too many attributes and the super class is slow // so find it quickly using our Hashtable. // Form the key of format "{uri}localName" m_buff.setLength(0); m_buff.append('{').append(uri).append('}').append(localName); String key = m_buff.toString(); Integer i = (Integer)m_indexFromQName.get(key); if (i == null) index = -1; else index = i.intValue(); return index; }
[ "public", "final", "int", "getIndex", "(", "String", "uri", ",", "String", "localName", ")", "{", "int", "index", ";", "if", "(", "super", ".", "getLength", "(", ")", "<", "MAX", ")", "{", "// if we haven't got too many attributes let the", "// super class look it up", "index", "=", "super", ".", "getIndex", "(", "uri", ",", "localName", ")", ";", "return", "index", ";", "}", "// we have too many attributes and the super class is slow", "// so find it quickly using our Hashtable.", "// Form the key of format \"{uri}localName\"", "m_buff", ".", "setLength", "(", "0", ")", ";", "m_buff", ".", "append", "(", "'", "'", ")", ".", "append", "(", "uri", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "localName", ")", ";", "String", "key", "=", "m_buff", ".", "toString", "(", ")", ";", "Integer", "i", "=", "(", "Integer", ")", "m_indexFromQName", ".", "get", "(", "key", ")", ";", "if", "(", "i", "==", "null", ")", "index", "=", "-", "1", ";", "else", "index", "=", "i", ".", "intValue", "(", ")", ";", "return", "index", ";", "}" ]
This method gets the index of an attribute given its uri and locanName. @param uri the URI of the attribute name. @param localName the local namer (after the ':' ) of the attribute name. @return the integer index of the attribute. @see org.xml.sax.Attributes#getIndex(String)
[ "This", "method", "gets", "the", "index", "of", "an", "attribute", "given", "its", "uri", "and", "locanName", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/AttributesImplSerializer.java#L213-L236
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/bolt/AmBaseBolt.java
AmBaseBolt.emit
protected void emit(StreamMessage message, Object messageKey) { """ Use anchor function(child message failed. notify fail to parent message.), MessageKey(Use key history's value).<br> Send message to downstream component.<br> Use following situation. <ol> <li>Use this class's key history function.</li> <li>Use storm's fault detect function.</li> </ol> @param message sending message @param messageKey MessageKey(Use key history's value) """ KeyHistory newHistory = null; if (this.recordHistory) { newHistory = createKeyRecorededHistory(this.executingKeyHistory, messageKey); } else { newHistory = createKeyRecorededHistory(this.executingKeyHistory); } message.getHeader().setHistory(newHistory); getCollector().emit(this.getExecutingTuple(), new Values("", message)); }
java
protected void emit(StreamMessage message, Object messageKey) { KeyHistory newHistory = null; if (this.recordHistory) { newHistory = createKeyRecorededHistory(this.executingKeyHistory, messageKey); } else { newHistory = createKeyRecorededHistory(this.executingKeyHistory); } message.getHeader().setHistory(newHistory); getCollector().emit(this.getExecutingTuple(), new Values("", message)); }
[ "protected", "void", "emit", "(", "StreamMessage", "message", ",", "Object", "messageKey", ")", "{", "KeyHistory", "newHistory", "=", "null", ";", "if", "(", "this", ".", "recordHistory", ")", "{", "newHistory", "=", "createKeyRecorededHistory", "(", "this", ".", "executingKeyHistory", ",", "messageKey", ")", ";", "}", "else", "{", "newHistory", "=", "createKeyRecorededHistory", "(", "this", ".", "executingKeyHistory", ")", ";", "}", "message", ".", "getHeader", "(", ")", ".", "setHistory", "(", "newHistory", ")", ";", "getCollector", "(", ")", ".", "emit", "(", "this", ".", "getExecutingTuple", "(", ")", ",", "new", "Values", "(", "\"\"", ",", "message", ")", ")", ";", "}" ]
Use anchor function(child message failed. notify fail to parent message.), MessageKey(Use key history's value).<br> Send message to downstream component.<br> Use following situation. <ol> <li>Use this class's key history function.</li> <li>Use storm's fault detect function.</li> </ol> @param message sending message @param messageKey MessageKey(Use key history's value)
[ "Use", "anchor", "function", "(", "child", "message", "failed", ".", "notify", "fail", "to", "parent", "message", ".", ")", "MessageKey", "(", "Use", "key", "history", "s", "value", ")", ".", "<br", ">", "Send", "message", "to", "downstream", "component", ".", "<br", ">", "Use", "following", "situation", ".", "<ol", ">", "<li", ">", "Use", "this", "class", "s", "key", "history", "function", ".", "<", "/", "li", ">", "<li", ">", "Use", "storm", "s", "fault", "detect", "function", ".", "<", "/", "li", ">", "<", "/", "ol", ">" ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/bolt/AmBaseBolt.java#L359-L374
socialsensor/socialsensor-framework-client
src/main/java/eu/socialsensor/framework/client/search/visual/VisualIndexHandler.java
VisualIndexHandler.getSimilarImages
public JsonResultSet getSimilarImages(String imageId, double threshold) { """ Get similar images for a specific media item @param imageId @param threshold @return """ JsonResultSet similar = new JsonResultSet(); PostMethod queryMethod = null; String response = null; try { Part[] parts = { new StringPart("id", imageId), new StringPart("threshold", String.valueOf(threshold)) }; queryMethod = new PostMethod(webServiceHost + "/rest/visual/query_id/" + collectionName); queryMethod.setRequestEntity(new MultipartRequestEntity(parts, queryMethod.getParams())); int code = httpClient.executeMethod(queryMethod); if (code == 200) { InputStream inputStream = queryMethod.getResponseBodyAsStream(); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer); response = writer.toString(); queryMethod.releaseConnection(); similar = parseResponse(response); } else { _logger.error("Http returned code: " + code); } } catch (Exception e) { _logger.error("Exception for ID: " + imageId, e); response = null; } finally { if (queryMethod != null) { queryMethod.releaseConnection(); } } return similar; }
java
public JsonResultSet getSimilarImages(String imageId, double threshold) { JsonResultSet similar = new JsonResultSet(); PostMethod queryMethod = null; String response = null; try { Part[] parts = { new StringPart("id", imageId), new StringPart("threshold", String.valueOf(threshold)) }; queryMethod = new PostMethod(webServiceHost + "/rest/visual/query_id/" + collectionName); queryMethod.setRequestEntity(new MultipartRequestEntity(parts, queryMethod.getParams())); int code = httpClient.executeMethod(queryMethod); if (code == 200) { InputStream inputStream = queryMethod.getResponseBodyAsStream(); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer); response = writer.toString(); queryMethod.releaseConnection(); similar = parseResponse(response); } else { _logger.error("Http returned code: " + code); } } catch (Exception e) { _logger.error("Exception for ID: " + imageId, e); response = null; } finally { if (queryMethod != null) { queryMethod.releaseConnection(); } } return similar; }
[ "public", "JsonResultSet", "getSimilarImages", "(", "String", "imageId", ",", "double", "threshold", ")", "{", "JsonResultSet", "similar", "=", "new", "JsonResultSet", "(", ")", ";", "PostMethod", "queryMethod", "=", "null", ";", "String", "response", "=", "null", ";", "try", "{", "Part", "[", "]", "parts", "=", "{", "new", "StringPart", "(", "\"id\"", ",", "imageId", ")", ",", "new", "StringPart", "(", "\"threshold\"", ",", "String", ".", "valueOf", "(", "threshold", ")", ")", "}", ";", "queryMethod", "=", "new", "PostMethod", "(", "webServiceHost", "+", "\"/rest/visual/query_id/\"", "+", "collectionName", ")", ";", "queryMethod", ".", "setRequestEntity", "(", "new", "MultipartRequestEntity", "(", "parts", ",", "queryMethod", ".", "getParams", "(", ")", ")", ")", ";", "int", "code", "=", "httpClient", ".", "executeMethod", "(", "queryMethod", ")", ";", "if", "(", "code", "==", "200", ")", "{", "InputStream", "inputStream", "=", "queryMethod", ".", "getResponseBodyAsStream", "(", ")", ";", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "IOUtils", ".", "copy", "(", "inputStream", ",", "writer", ")", ";", "response", "=", "writer", ".", "toString", "(", ")", ";", "queryMethod", ".", "releaseConnection", "(", ")", ";", "similar", "=", "parseResponse", "(", "response", ")", ";", "}", "else", "{", "_logger", ".", "error", "(", "\"Http returned code: \"", "+", "code", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "_logger", ".", "error", "(", "\"Exception for ID: \"", "+", "imageId", ",", "e", ")", ";", "response", "=", "null", ";", "}", "finally", "{", "if", "(", "queryMethod", "!=", "null", ")", "{", "queryMethod", ".", "releaseConnection", "(", ")", ";", "}", "}", "return", "similar", ";", "}" ]
Get similar images for a specific media item @param imageId @param threshold @return
[ "Get", "similar", "images", "for", "a", "specific", "media", "item" ]
train
https://github.com/socialsensor/socialsensor-framework-client/blob/67cd45c5d8e096d5f76ace49f453ff6438920473/src/main/java/eu/socialsensor/framework/client/search/visual/VisualIndexHandler.java#L74-L111
NessComputing/components-ness-amqp
src/main/java/com/nesscomputing/amqp/AmqpRunnableFactory.java
AmqpRunnableFactory.createExchangeListener
public ExchangeConsumer createExchangeListener(final String name, final ConsumerCallback messageCallback) { """ Creates a new {@link ExchangeConsumer}. For every message received (or when the timeout waiting for messages is hit), the callback is invoked with the message received. """ Preconditions.checkState(connectionFactory != null, "connection factory was never injected!"); return new ExchangeConsumer(connectionFactory, amqpConfig, name, messageCallback); }
java
public ExchangeConsumer createExchangeListener(final String name, final ConsumerCallback messageCallback) { Preconditions.checkState(connectionFactory != null, "connection factory was never injected!"); return new ExchangeConsumer(connectionFactory, amqpConfig, name, messageCallback); }
[ "public", "ExchangeConsumer", "createExchangeListener", "(", "final", "String", "name", ",", "final", "ConsumerCallback", "messageCallback", ")", "{", "Preconditions", ".", "checkState", "(", "connectionFactory", "!=", "null", ",", "\"connection factory was never injected!\"", ")", ";", "return", "new", "ExchangeConsumer", "(", "connectionFactory", ",", "amqpConfig", ",", "name", ",", "messageCallback", ")", ";", "}" ]
Creates a new {@link ExchangeConsumer}. For every message received (or when the timeout waiting for messages is hit), the callback is invoked with the message received.
[ "Creates", "a", "new", "{" ]
train
https://github.com/NessComputing/components-ness-amqp/blob/3d36b0b71d975f943efb3c181a16c72d46892922/src/main/java/com/nesscomputing/amqp/AmqpRunnableFactory.java#L129-L133
stevespringett/Alpine
alpine/src/main/java/alpine/filters/RequestRateThrottleFilter.java
RequestRateThrottleFilter.doFilter
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { """ Determines if the request rate is below or has exceeded the the maximum requests per second for the given time period. If exceeded, a HTTP status code of 429 (too many requests) will be send and no further processing of the request will be done. If the request has not exceeded the limit, the request will continue on as normal. @param request a ServletRequest @param response a ServletResponse @param chain a FilterChain @throws IOException a IOException @throws ServletException a ServletException """ final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final HttpSession session = httpRequest.getSession(true); synchronized (session.getId().intern()) { Stack<Date> times = HttpUtil.getSessionAttribute(session, "times"); if (times == null) { times = new Stack<>(); times.push(new Date(0)); session.setAttribute("times", times); } times.push(new Date()); if (times.size() >= maximumRequestsPerPeriod) { times.removeElementAt(0); } final Date newest = times.get(times.size() - 1); final Date oldest = times.get(0); final long elapsed = newest.getTime() - oldest.getTime(); if (elapsed < timePeriodSeconds * 1000) { httpResponse.sendError(429); return; } } chain.doFilter(request, response); }
java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final HttpSession session = httpRequest.getSession(true); synchronized (session.getId().intern()) { Stack<Date> times = HttpUtil.getSessionAttribute(session, "times"); if (times == null) { times = new Stack<>(); times.push(new Date(0)); session.setAttribute("times", times); } times.push(new Date()); if (times.size() >= maximumRequestsPerPeriod) { times.removeElementAt(0); } final Date newest = times.get(times.size() - 1); final Date oldest = times.get(0); final long elapsed = newest.getTime() - oldest.getTime(); if (elapsed < timePeriodSeconds * 1000) { httpResponse.sendError(429); return; } } chain.doFilter(request, response); }
[ "public", "void", "doFilter", "(", "final", "ServletRequest", "request", ",", "final", "ServletResponse", "response", ",", "final", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "final", "HttpServletRequest", "httpRequest", "=", "(", "HttpServletRequest", ")", "request", ";", "final", "HttpServletResponse", "httpResponse", "=", "(", "HttpServletResponse", ")", "response", ";", "final", "HttpSession", "session", "=", "httpRequest", ".", "getSession", "(", "true", ")", ";", "synchronized", "(", "session", ".", "getId", "(", ")", ".", "intern", "(", ")", ")", "{", "Stack", "<", "Date", ">", "times", "=", "HttpUtil", ".", "getSessionAttribute", "(", "session", ",", "\"times\"", ")", ";", "if", "(", "times", "==", "null", ")", "{", "times", "=", "new", "Stack", "<>", "(", ")", ";", "times", ".", "push", "(", "new", "Date", "(", "0", ")", ")", ";", "session", ".", "setAttribute", "(", "\"times\"", ",", "times", ")", ";", "}", "times", ".", "push", "(", "new", "Date", "(", ")", ")", ";", "if", "(", "times", ".", "size", "(", ")", ">=", "maximumRequestsPerPeriod", ")", "{", "times", ".", "removeElementAt", "(", "0", ")", ";", "}", "final", "Date", "newest", "=", "times", ".", "get", "(", "times", ".", "size", "(", ")", "-", "1", ")", ";", "final", "Date", "oldest", "=", "times", ".", "get", "(", "0", ")", ";", "final", "long", "elapsed", "=", "newest", ".", "getTime", "(", ")", "-", "oldest", ".", "getTime", "(", ")", ";", "if", "(", "elapsed", "<", "timePeriodSeconds", "*", "1000", ")", "{", "httpResponse", ".", "sendError", "(", "429", ")", ";", "return", ";", "}", "}", "chain", ".", "doFilter", "(", "request", ",", "response", ")", ";", "}" ]
Determines if the request rate is below or has exceeded the the maximum requests per second for the given time period. If exceeded, a HTTP status code of 429 (too many requests) will be send and no further processing of the request will be done. If the request has not exceeded the limit, the request will continue on as normal. @param request a ServletRequest @param response a ServletResponse @param chain a FilterChain @throws IOException a IOException @throws ServletException a ServletException
[ "Determines", "if", "the", "request", "rate", "is", "below", "or", "has", "exceeded", "the", "the", "maximum", "requests", "per", "second", "for", "the", "given", "time", "period", ".", "If", "exceeded", "a", "HTTP", "status", "code", "of", "429", "(", "too", "many", "requests", ")", "will", "be", "send", "and", "no", "further", "processing", "of", "the", "request", "will", "be", "done", ".", "If", "the", "request", "has", "not", "exceeded", "the", "limit", "the", "request", "will", "continue", "on", "as", "normal", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/RequestRateThrottleFilter.java#L92-L118
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java
JobOperations.createJob
public void createJob(JobAddParameter job, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { """ Adds a job to the Batch account. @param job The job to be added. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ JobAddOptions options = new JobAddOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().jobs().add(job, options); }
java
public void createJob(JobAddParameter job, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { JobAddOptions options = new JobAddOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().jobs().add(job, options); }
[ "public", "void", "createJob", "(", "JobAddParameter", "job", ",", "Iterable", "<", "BatchClientBehavior", ">", "additionalBehaviors", ")", "throws", "BatchErrorException", ",", "IOException", "{", "JobAddOptions", "options", "=", "new", "JobAddOptions", "(", ")", ";", "BehaviorManager", "bhMgr", "=", "new", "BehaviorManager", "(", "this", ".", "customBehaviors", "(", ")", ",", "additionalBehaviors", ")", ";", "bhMgr", ".", "applyRequestBehaviors", "(", "options", ")", ";", "this", ".", "parentBatchClient", ".", "protocolLayer", "(", ")", ".", "jobs", "(", ")", ".", "add", "(", "job", ",", "options", ")", ";", "}" ]
Adds a job to the Batch account. @param job The job to be added. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Adds", "a", "job", "to", "the", "Batch", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L316-L322
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/modules/CmsCloneModuleThread.java
CmsCloneModuleThread.cloneExplorerTypeIcons
private void cloneExplorerTypeIcons(Map<String, String> iconPaths) throws CmsException { """ Copies the explorer type icons.<p> @param iconPaths the path to the location where the icons are located @throws CmsException if something goes wrong """ for (Map.Entry<String, String> entry : iconPaths.entrySet()) { String source = ICON_PATH + entry.getKey(); String target = ICON_PATH + entry.getValue(); if (getCms().existsResource(source) && !getCms().existsResource(target)) { getCms().copyResource(source, target); } } }
java
private void cloneExplorerTypeIcons(Map<String, String> iconPaths) throws CmsException { for (Map.Entry<String, String> entry : iconPaths.entrySet()) { String source = ICON_PATH + entry.getKey(); String target = ICON_PATH + entry.getValue(); if (getCms().existsResource(source) && !getCms().existsResource(target)) { getCms().copyResource(source, target); } } }
[ "private", "void", "cloneExplorerTypeIcons", "(", "Map", "<", "String", ",", "String", ">", "iconPaths", ")", "throws", "CmsException", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "iconPaths", ".", "entrySet", "(", ")", ")", "{", "String", "source", "=", "ICON_PATH", "+", "entry", ".", "getKey", "(", ")", ";", "String", "target", "=", "ICON_PATH", "+", "entry", ".", "getValue", "(", ")", ";", "if", "(", "getCms", "(", ")", ".", "existsResource", "(", "source", ")", "&&", "!", "getCms", "(", ")", ".", "existsResource", "(", "target", ")", ")", "{", "getCms", "(", ")", ".", "copyResource", "(", "source", ",", "target", ")", ";", "}", "}", "}" ]
Copies the explorer type icons.<p> @param iconPaths the path to the location where the icons are located @throws CmsException if something goes wrong
[ "Copies", "the", "explorer", "type", "icons", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/modules/CmsCloneModuleThread.java#L539-L548
ModeShape/modeshape
modeshape-jcr-api/src/main/java/org/modeshape/jcr/api/JcrTools.java
JcrTools.uploadFile
public Node uploadFile( Session session, String path, URL contentUrl ) throws RepositoryException, IOException { """ Upload the content at the supplied URL into the repository at the defined path, using the given session. This method will create a 'nt:file' node at the supplied path, and any non-existant ancestors with nodes of type 'nt:folder'. As defined by the JCR specification, the binary content (and other properties) will be placed on a child of the 'nt:file' node named 'jcr:content' with a node type of 'nt:resource'. @param session the JCR session @param path the path to the file @param contentUrl the URL where the content can be found @return the newly created 'nt:file' node @throws RepositoryException if there is a problem uploading the file @throws IOException if there is a problem using the stream @throws IllegalArgumentException is any of the parameters are null """ isNotNull(session, "session"); isNotNull(path, "path"); isNotNull(contentUrl, "contentUrl"); // Open the URL's stream first ... InputStream stream = contentUrl.openStream(); return uploadFile(session, path, stream); }
java
public Node uploadFile( Session session, String path, URL contentUrl ) throws RepositoryException, IOException { isNotNull(session, "session"); isNotNull(path, "path"); isNotNull(contentUrl, "contentUrl"); // Open the URL's stream first ... InputStream stream = contentUrl.openStream(); return uploadFile(session, path, stream); }
[ "public", "Node", "uploadFile", "(", "Session", "session", ",", "String", "path", ",", "URL", "contentUrl", ")", "throws", "RepositoryException", ",", "IOException", "{", "isNotNull", "(", "session", ",", "\"session\"", ")", ";", "isNotNull", "(", "path", ",", "\"path\"", ")", ";", "isNotNull", "(", "contentUrl", ",", "\"contentUrl\"", ")", ";", "// Open the URL's stream first ...", "InputStream", "stream", "=", "contentUrl", ".", "openStream", "(", ")", ";", "return", "uploadFile", "(", "session", ",", "path", ",", "stream", ")", ";", "}" ]
Upload the content at the supplied URL into the repository at the defined path, using the given session. This method will create a 'nt:file' node at the supplied path, and any non-existant ancestors with nodes of type 'nt:folder'. As defined by the JCR specification, the binary content (and other properties) will be placed on a child of the 'nt:file' node named 'jcr:content' with a node type of 'nt:resource'. @param session the JCR session @param path the path to the file @param contentUrl the URL where the content can be found @return the newly created 'nt:file' node @throws RepositoryException if there is a problem uploading the file @throws IOException if there is a problem using the stream @throws IllegalArgumentException is any of the parameters are null
[ "Upload", "the", "content", "at", "the", "supplied", "URL", "into", "the", "repository", "at", "the", "defined", "path", "using", "the", "given", "session", ".", "This", "method", "will", "create", "a", "nt", ":", "file", "node", "at", "the", "supplied", "path", "and", "any", "non", "-", "existant", "ancestors", "with", "nodes", "of", "type", "nt", ":", "folder", ".", "As", "defined", "by", "the", "JCR", "specification", "the", "binary", "content", "(", "and", "other", "properties", ")", "will", "be", "placed", "on", "a", "child", "of", "the", "nt", ":", "file", "node", "named", "jcr", ":", "content", "with", "a", "node", "type", "of", "nt", ":", "resource", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr-api/src/main/java/org/modeshape/jcr/api/JcrTools.java#L206-L216
igniterealtime/Smack
smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java
ChatManager.createChat
private Chat createChat(Message message) { """ Creates a new {@link Chat} based on the message. May returns null if no chat could be created, e.g. because the message comes without from. @param message @return a Chat or null if none can be created """ Jid from = message.getFrom(); // According to RFC6120 8.1.2.1 4. messages without a 'from' attribute are valid, but they // are of no use in this case for ChatManager if (from == null) { return null; } EntityJid userJID = from.asEntityJidIfPossible(); if (userJID == null) { LOGGER.warning("Message from JID without localpart: '" + message.toXML() + "'"); return null; } String threadID = message.getThread(); if (threadID == null) { threadID = nextID(); } return createChat(userJID, threadID, false); }
java
private Chat createChat(Message message) { Jid from = message.getFrom(); // According to RFC6120 8.1.2.1 4. messages without a 'from' attribute are valid, but they // are of no use in this case for ChatManager if (from == null) { return null; } EntityJid userJID = from.asEntityJidIfPossible(); if (userJID == null) { LOGGER.warning("Message from JID without localpart: '" + message.toXML() + "'"); return null; } String threadID = message.getThread(); if (threadID == null) { threadID = nextID(); } return createChat(userJID, threadID, false); }
[ "private", "Chat", "createChat", "(", "Message", "message", ")", "{", "Jid", "from", "=", "message", ".", "getFrom", "(", ")", ";", "// According to RFC6120 8.1.2.1 4. messages without a 'from' attribute are valid, but they", "// are of no use in this case for ChatManager", "if", "(", "from", "==", "null", ")", "{", "return", "null", ";", "}", "EntityJid", "userJID", "=", "from", ".", "asEntityJidIfPossible", "(", ")", ";", "if", "(", "userJID", "==", "null", ")", "{", "LOGGER", ".", "warning", "(", "\"Message from JID without localpart: '\"", "+", "message", ".", "toXML", "(", ")", "+", "\"'\"", ")", ";", "return", "null", ";", "}", "String", "threadID", "=", "message", ".", "getThread", "(", ")", ";", "if", "(", "threadID", "==", "null", ")", "{", "threadID", "=", "nextID", "(", ")", ";", "}", "return", "createChat", "(", "userJID", ",", "threadID", ",", "false", ")", ";", "}" ]
Creates a new {@link Chat} based on the message. May returns null if no chat could be created, e.g. because the message comes without from. @param message @return a Chat or null if none can be created
[ "Creates", "a", "new", "{", "@link", "Chat", "}", "based", "on", "the", "message", ".", "May", "returns", "null", "if", "no", "chat", "could", "be", "created", "e", ".", "g", ".", "because", "the", "message", "comes", "without", "from", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java#L287-L306
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java
LongExtensions.bitwiseOr
@Pure @Inline(value="($1 | $2)", constantExpression=true) public static long bitwiseOr(long a, long b) { """ The bitwise inclusive <code>or</code> operation. This is the equivalent to the java <code>|</code> operator. @param a a long. @param b a long @return <code>a|b</code> """ return a | b; }
java
@Pure @Inline(value="($1 | $2)", constantExpression=true) public static long bitwiseOr(long a, long b) { return a | b; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($1 | $2)\"", ",", "constantExpression", "=", "true", ")", "public", "static", "long", "bitwiseOr", "(", "long", "a", ",", "long", "b", ")", "{", "return", "a", "|", "b", ";", "}" ]
The bitwise inclusive <code>or</code> operation. This is the equivalent to the java <code>|</code> operator. @param a a long. @param b a long @return <code>a|b</code>
[ "The", "bitwise", "inclusive", "<code", ">", "or<", "/", "code", ">", "operation", ".", "This", "is", "the", "equivalent", "to", "the", "java", "<code", ">", "|<", "/", "code", ">", "operator", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java#L30-L34
akarnokd/akarnokd-xml
src/main/java/hu/akarnokd/xml/XNSerializables.java
XNSerializables.parseItem
public static <T extends XNSerializable> T parseItem(XNElement item, Supplier<T> creator) { """ Create an XNSerializable object through the {@code creator} function and load it from the {@code item}. @param <T> the XNSerializable object @param item the item to load from @param creator the function to create Ts @return the created and loaded object """ T result = creator.get(); result.load(item); return result; }
java
public static <T extends XNSerializable> T parseItem(XNElement item, Supplier<T> creator) { T result = creator.get(); result.load(item); return result; }
[ "public", "static", "<", "T", "extends", "XNSerializable", ">", "T", "parseItem", "(", "XNElement", "item", ",", "Supplier", "<", "T", ">", "creator", ")", "{", "T", "result", "=", "creator", ".", "get", "(", ")", ";", "result", ".", "load", "(", "item", ")", ";", "return", "result", ";", "}" ]
Create an XNSerializable object through the {@code creator} function and load it from the {@code item}. @param <T> the XNSerializable object @param item the item to load from @param creator the function to create Ts @return the created and loaded object
[ "Create", "an", "XNSerializable", "object", "through", "the", "{" ]
train
https://github.com/akarnokd/akarnokd-xml/blob/57466a5a9cb455a13d7121557c165287b31ee870/src/main/java/hu/akarnokd/xml/XNSerializables.java#L80-L84
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java
CommerceOrderNotePersistenceImpl.findAll
@Override public List<CommerceOrderNote> findAll() { """ Returns all the commerce order notes. @return the commerce order notes """ return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommerceOrderNote> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommerceOrderNote", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce order notes. @return the commerce order notes
[ "Returns", "all", "the", "commerce", "order", "notes", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java#L2011-L2014
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsDateTimeUtil.java
CmsDateTimeUtil.getTime
public static String getTime(Date date, Format format) { """ Returns a formated time String from a Date value, the formatting based on the provided options.<p> @param date the Date object to format as String @param format the format to use @return the formatted time """ DateTimeFormat df; switch (format) { case FULL: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_FULL); break; case LONG: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_LONG); break; case MEDIUM: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_MEDIUM); break; case SHORT: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_SHORT); break; default: // can never happen, just to prevent stupid warning return ""; } return df.format(date); }
java
public static String getTime(Date date, Format format) { DateTimeFormat df; switch (format) { case FULL: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_FULL); break; case LONG: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_LONG); break; case MEDIUM: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_MEDIUM); break; case SHORT: df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_SHORT); break; default: // can never happen, just to prevent stupid warning return ""; } return df.format(date); }
[ "public", "static", "String", "getTime", "(", "Date", "date", ",", "Format", "format", ")", "{", "DateTimeFormat", "df", ";", "switch", "(", "format", ")", "{", "case", "FULL", ":", "df", "=", "DateTimeFormat", ".", "getFormat", "(", "DateTimeFormat", ".", "PredefinedFormat", ".", "TIME_FULL", ")", ";", "break", ";", "case", "LONG", ":", "df", "=", "DateTimeFormat", ".", "getFormat", "(", "DateTimeFormat", ".", "PredefinedFormat", ".", "TIME_LONG", ")", ";", "break", ";", "case", "MEDIUM", ":", "df", "=", "DateTimeFormat", ".", "getFormat", "(", "DateTimeFormat", ".", "PredefinedFormat", ".", "TIME_MEDIUM", ")", ";", "break", ";", "case", "SHORT", ":", "df", "=", "DateTimeFormat", ".", "getFormat", "(", "DateTimeFormat", ".", "PredefinedFormat", ".", "TIME_SHORT", ")", ";", "break", ";", "default", ":", "// can never happen, just to prevent stupid warning", "return", "\"\"", ";", "}", "return", "df", ".", "format", "(", "date", ")", ";", "}" ]
Returns a formated time String from a Date value, the formatting based on the provided options.<p> @param date the Date object to format as String @param format the format to use @return the formatted time
[ "Returns", "a", "formated", "time", "String", "from", "a", "Date", "value", "the", "formatting", "based", "on", "the", "provided", "options", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsDateTimeUtil.java#L155-L176
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java
Schema.createPublicSchema
static Schema createPublicSchema(SqlgGraph sqlgGraph, Topology topology, String publicSchemaName) { """ Creates the 'public' schema that always already exist and is pre-loaded in {@link Topology()} @see {@link Topology#cacheTopology()} @param publicSchemaName The 'public' schema's name. Sometimes its upper case (Hsqldb) sometimes lower (Postgresql) @param topology The {@link Topology} that contains the public schema. @return The Schema that represents 'public' """ Schema schema = new Schema(topology, publicSchemaName); if (!existPublicSchema(sqlgGraph)) { schema.createSchemaOnDb(); } schema.committed = false; return schema; }
java
static Schema createPublicSchema(SqlgGraph sqlgGraph, Topology topology, String publicSchemaName) { Schema schema = new Schema(topology, publicSchemaName); if (!existPublicSchema(sqlgGraph)) { schema.createSchemaOnDb(); } schema.committed = false; return schema; }
[ "static", "Schema", "createPublicSchema", "(", "SqlgGraph", "sqlgGraph", ",", "Topology", "topology", ",", "String", "publicSchemaName", ")", "{", "Schema", "schema", "=", "new", "Schema", "(", "topology", ",", "publicSchemaName", ")", ";", "if", "(", "!", "existPublicSchema", "(", "sqlgGraph", ")", ")", "{", "schema", ".", "createSchemaOnDb", "(", ")", ";", "}", "schema", ".", "committed", "=", "false", ";", "return", "schema", ";", "}" ]
Creates the 'public' schema that always already exist and is pre-loaded in {@link Topology()} @see {@link Topology#cacheTopology()} @param publicSchemaName The 'public' schema's name. Sometimes its upper case (Hsqldb) sometimes lower (Postgresql) @param topology The {@link Topology} that contains the public schema. @return The Schema that represents 'public'
[ "Creates", "the", "public", "schema", "that", "always", "already", "exist", "and", "is", "pre", "-", "loaded", "in", "{", "@link", "Topology", "()", "}", "@see", "{", "@link", "Topology#cacheTopology", "()", "}" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java#L73-L80
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java
ExamplesImpl.listWithServiceResponseAsync
public Observable<ServiceResponse<List<LabeledUtterance>>> listWithServiceResponseAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { """ Returns examples to be reviewed. @param appId The application ID. @param versionId The version ID. @param listOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LabeledUtterance&gt; object """ if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null; final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null; return listWithServiceResponseAsync(appId, versionId, skip, take); }
java
public Observable<ServiceResponse<List<LabeledUtterance>>> listWithServiceResponseAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null; final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null; return listWithServiceResponseAsync(appId, versionId, skip, take); }
[ "public", "Observable", "<", "ServiceResponse", "<", "List", "<", "LabeledUtterance", ">", ">", ">", "listWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "ListExamplesOptionalParameter", "listOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.endpoint() is required and cannot be null.\"", ")", ";", "}", "if", "(", "appId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter appId is required and cannot be null.\"", ")", ";", "}", "if", "(", "versionId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter versionId is required and cannot be null.\"", ")", ";", "}", "final", "Integer", "skip", "=", "listOptionalParameter", "!=", "null", "?", "listOptionalParameter", ".", "skip", "(", ")", ":", "null", ";", "final", "Integer", "take", "=", "listOptionalParameter", "!=", "null", "?", "listOptionalParameter", ".", "take", "(", ")", ":", "null", ";", "return", "listWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "skip", ",", "take", ")", ";", "}" ]
Returns examples to be reviewed. @param appId The application ID. @param versionId The version ID. @param listOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LabeledUtterance&gt; object
[ "Returns", "examples", "to", "be", "reviewed", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java#L328-L342
lucee/Lucee
core/src/main/java/lucee/runtime/op/Caster.java
Caster.toQuery
public static Query toQuery(Object o, Query defaultValue) { """ cast a Object to a Query Object @param o Object to cast @param defaultValue @return casted Query Object """ if (o instanceof Query) return (Query) o; else if (o instanceof ObjectWrap) { return toQuery(((ObjectWrap) o).getEmbededObject(defaultValue), defaultValue); } return defaultValue; }
java
public static Query toQuery(Object o, Query defaultValue) { if (o instanceof Query) return (Query) o; else if (o instanceof ObjectWrap) { return toQuery(((ObjectWrap) o).getEmbededObject(defaultValue), defaultValue); } return defaultValue; }
[ "public", "static", "Query", "toQuery", "(", "Object", "o", ",", "Query", "defaultValue", ")", "{", "if", "(", "o", "instanceof", "Query", ")", "return", "(", "Query", ")", "o", ";", "else", "if", "(", "o", "instanceof", "ObjectWrap", ")", "{", "return", "toQuery", "(", "(", "(", "ObjectWrap", ")", "o", ")", ".", "getEmbededObject", "(", "defaultValue", ")", ",", "defaultValue", ")", ";", "}", "return", "defaultValue", ";", "}" ]
cast a Object to a Query Object @param o Object to cast @param defaultValue @return casted Query Object
[ "cast", "a", "Object", "to", "a", "Query", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L3021-L3027
osmdroid/osmdroid
osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java
SphericalUtil.computeAngleBetween
static double computeAngleBetween(IGeoPoint from, IGeoPoint to) { """ Returns the angle between two IGeoPoints, in radians. This is the same as the distance on the unit sphere. """ return distanceRadians(toRadians(from.getLatitude()), toRadians(from.getLongitude()), toRadians(to.getLatitude()), toRadians(to.getLongitude())); }
java
static double computeAngleBetween(IGeoPoint from, IGeoPoint to) { return distanceRadians(toRadians(from.getLatitude()), toRadians(from.getLongitude()), toRadians(to.getLatitude()), toRadians(to.getLongitude())); }
[ "static", "double", "computeAngleBetween", "(", "IGeoPoint", "from", ",", "IGeoPoint", "to", ")", "{", "return", "distanceRadians", "(", "toRadians", "(", "from", ".", "getLatitude", "(", ")", ")", ",", "toRadians", "(", "from", ".", "getLongitude", "(", ")", ")", ",", "toRadians", "(", "to", ".", "getLatitude", "(", ")", ")", ",", "toRadians", "(", "to", ".", "getLongitude", "(", ")", ")", ")", ";", "}" ]
Returns the angle between two IGeoPoints, in radians. This is the same as the distance on the unit sphere.
[ "Returns", "the", "angle", "between", "two", "IGeoPoints", "in", "radians", ".", "This", "is", "the", "same", "as", "the", "distance", "on", "the", "unit", "sphere", "." ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L265-L268
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/DatatypeConverter.java
DatatypeConverter.printDuration
public static final String printDuration(MSPDIWriter writer, Duration duration) { """ Print duration. Note that Microsoft's xsd:duration parser implementation does not appear to recognise durations other than those expressed in hours. We use the compatibility flag to determine whether the output is adjusted for the benefit of Microsoft Project. @param writer parent MSPDIWriter instance @param duration Duration value @return xsd:duration value """ String result = null; if (duration != null && duration.getDuration() != 0) { result = printDurationMandatory(writer, duration); } return (result); }
java
public static final String printDuration(MSPDIWriter writer, Duration duration) { String result = null; if (duration != null && duration.getDuration() != 0) { result = printDurationMandatory(writer, duration); } return (result); }
[ "public", "static", "final", "String", "printDuration", "(", "MSPDIWriter", "writer", ",", "Duration", "duration", ")", "{", "String", "result", "=", "null", ";", "if", "(", "duration", "!=", "null", "&&", "duration", ".", "getDuration", "(", ")", "!=", "0", ")", "{", "result", "=", "printDurationMandatory", "(", "writer", ",", "duration", ")", ";", "}", "return", "(", "result", ")", ";", "}" ]
Print duration. Note that Microsoft's xsd:duration parser implementation does not appear to recognise durations other than those expressed in hours. We use the compatibility flag to determine whether the output is adjusted for the benefit of Microsoft Project. @param writer parent MSPDIWriter instance @param duration Duration value @return xsd:duration value
[ "Print", "duration", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/DatatypeConverter.java#L936-L946
alkacon/opencms-core
src/org/opencms/ui/apps/cacheadmin/CmsImageCacheHelper.java
CmsImageCacheHelper.init
private void init(CmsObject cms, boolean withVariations, boolean showSize, boolean statsOnly) { """ Reads all cached images.<p> @param cms the cms context @param withVariations if also variations should be read @param showSize if it is needed to compute the image size @param statsOnly if only statistical information should be retrieved """ File basedir = new File(CmsImageLoader.getImageRepositoryPath()); try { CmsObject clonedCms = getClonedCmsObject(cms); visitImages(clonedCms, basedir, withVariations, showSize, statsOnly); } catch (CmsException e) { // should never happen } m_variations = Collections.unmodifiableMap(m_variations); m_sizes = Collections.unmodifiableMap(m_sizes); m_lengths = Collections.unmodifiableMap(m_lengths); }
java
private void init(CmsObject cms, boolean withVariations, boolean showSize, boolean statsOnly) { File basedir = new File(CmsImageLoader.getImageRepositoryPath()); try { CmsObject clonedCms = getClonedCmsObject(cms); visitImages(clonedCms, basedir, withVariations, showSize, statsOnly); } catch (CmsException e) { // should never happen } m_variations = Collections.unmodifiableMap(m_variations); m_sizes = Collections.unmodifiableMap(m_sizes); m_lengths = Collections.unmodifiableMap(m_lengths); }
[ "private", "void", "init", "(", "CmsObject", "cms", ",", "boolean", "withVariations", ",", "boolean", "showSize", ",", "boolean", "statsOnly", ")", "{", "File", "basedir", "=", "new", "File", "(", "CmsImageLoader", ".", "getImageRepositoryPath", "(", ")", ")", ";", "try", "{", "CmsObject", "clonedCms", "=", "getClonedCmsObject", "(", "cms", ")", ";", "visitImages", "(", "clonedCms", ",", "basedir", ",", "withVariations", ",", "showSize", ",", "statsOnly", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "// should never happen", "}", "m_variations", "=", "Collections", ".", "unmodifiableMap", "(", "m_variations", ")", ";", "m_sizes", "=", "Collections", ".", "unmodifiableMap", "(", "m_sizes", ")", ";", "m_lengths", "=", "Collections", ".", "unmodifiableMap", "(", "m_lengths", ")", ";", "}" ]
Reads all cached images.<p> @param cms the cms context @param withVariations if also variations should be read @param showSize if it is needed to compute the image size @param statsOnly if only statistical information should be retrieved
[ "Reads", "all", "cached", "images", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/cacheadmin/CmsImageCacheHelper.java#L248-L260
neoremind/fluent-validator
fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java
FluentValidator.composeIfPossible
private <T> void composeIfPossible(Validator<T> v, T t) { """ 如果验证器是一个{@link ValidatorHandler}实例,那么可以通过{@link ValidatorHandler#compose(FluentValidator, ValidatorContext, Object)} 方法增加一些验证逻辑 @param v 验证器 @param t 待验证对象 """ final FluentValidator self = this; if (v instanceof ValidatorHandler) { ((ValidatorHandler) v).compose(self, context, t); } }
java
private <T> void composeIfPossible(Validator<T> v, T t) { final FluentValidator self = this; if (v instanceof ValidatorHandler) { ((ValidatorHandler) v).compose(self, context, t); } }
[ "private", "<", "T", ">", "void", "composeIfPossible", "(", "Validator", "<", "T", ">", "v", ",", "T", "t", ")", "{", "final", "FluentValidator", "self", "=", "this", ";", "if", "(", "v", "instanceof", "ValidatorHandler", ")", "{", "(", "(", "ValidatorHandler", ")", "v", ")", ".", "compose", "(", "self", ",", "context", ",", "t", ")", ";", "}", "}" ]
如果验证器是一个{@link ValidatorHandler}实例,那么可以通过{@link ValidatorHandler#compose(FluentValidator, ValidatorContext, Object)} 方法增加一些验证逻辑 @param v 验证器 @param t 待验证对象
[ "如果验证器是一个", "{", "@link", "ValidatorHandler", "}", "实例,那么可以通过", "{", "@link", "ValidatorHandler#compose", "(", "FluentValidator", "ValidatorContext", "Object", ")", "}", "方法增加一些验证逻辑" ]
train
https://github.com/neoremind/fluent-validator/blob/b516970591aa9468b44ba63938b98ec341fd6ead/fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java#L587-L592