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
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
jingwei/krati
krati-main/src/main/java/krati/core/StoreConfig.java
StoreConfig.getClass
public Class<?> getClass(String pName, Class<?> defaultValue) { """ Gets a class property via a string property name. @param pName - the property name @param defaultValue - the default property value @return a {@link Class} property """ String pValue = _properties.getProperty(pName); return parseClass(pName, pValue, defaultValue); }
java
public Class<?> getClass(String pName, Class<?> defaultValue) { String pValue = _properties.getProperty(pName); return parseClass(pName, pValue, defaultValue); }
[ "public", "Class", "<", "?", ">", "getClass", "(", "String", "pName", ",", "Class", "<", "?", ">", "defaultValue", ")", "{", "String", "pValue", "=", "_properties", ".", "getProperty", "(", "pName", ")", ";", "return", "parseClass", "(", "pName", ",", "pValue", ",", "defaultValue", ")", ";", "}" ]
Gets a class property via a string property name. @param pName - the property name @param defaultValue - the default property value @return a {@link Class} property
[ "Gets", "a", "class", "property", "via", "a", "string", "property", "name", "." ]
train
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/core/StoreConfig.java#L471-L474
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java
Constraints.gtProperty
public PropertyConstraint gtProperty(String propertyName, String otherPropertyName) { """ Apply a "greater than" constraint to two properties @param propertyName The first property @param otherPropertyName The other property @return The constraint """ return valueProperties(propertyName, GreaterThan.instance(), otherPropertyName); }
java
public PropertyConstraint gtProperty(String propertyName, String otherPropertyName) { return valueProperties(propertyName, GreaterThan.instance(), otherPropertyName); }
[ "public", "PropertyConstraint", "gtProperty", "(", "String", "propertyName", ",", "String", "otherPropertyName", ")", "{", "return", "valueProperties", "(", "propertyName", ",", "GreaterThan", ".", "instance", "(", ")", ",", "otherPropertyName", ")", ";", "}" ]
Apply a "greater than" constraint to two properties @param propertyName The first property @param otherPropertyName The other property @return The constraint
[ "Apply", "a", "greater", "than", "constraint", "to", "two", "properties" ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java#L853-L855
elki-project/elki
elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/VectorUtil.java
VectorUtil.angleSparseDense
public static double angleSparseDense(SparseNumberVector v1, NumberVector v2) { """ Compute the angle for a sparse and a dense vector. @param v1 Sparse first vector @param v2 Dense second vector @return angle """ // TODO: exploit precomputed length, when available. final int dim2 = v2.getDimensionality(); double l1 = 0., l2 = 0., cross = 0.; int i1 = v1.iter(), d2 = 0; while(v1.iterValid(i1)) { final int d1 = v1.iterDim(i1); while(d2 < d1 && d2 < dim2) { final double val = v2.doubleValue(d2); l2 += val * val; ++d2; } if(d2 < dim2) { assert (d1 == d2) : "Dimensions not ordered"; final double val1 = v1.iterDoubleValue(i1); final double val2 = v2.doubleValue(d2); l1 += val1 * val1; l2 += val2 * val2; cross += val1 * val2; i1 = v1.iterAdvance(i1); ++d2; } else { final double val = v1.iterDoubleValue(i1); l1 += val * val; i1 = v1.iterAdvance(i1); } } while(d2 < dim2) { final double val = v2.doubleValue(d2); l2 += val * val; ++d2; } final double a = (cross == 0.) ? 0. : // (l1 == 0. || l2 == 0.) ? 1. : // FastMath.sqrt((cross / l1) * (cross / l2)); return (a < 1.) ? a : 1.; }
java
public static double angleSparseDense(SparseNumberVector v1, NumberVector v2) { // TODO: exploit precomputed length, when available. final int dim2 = v2.getDimensionality(); double l1 = 0., l2 = 0., cross = 0.; int i1 = v1.iter(), d2 = 0; while(v1.iterValid(i1)) { final int d1 = v1.iterDim(i1); while(d2 < d1 && d2 < dim2) { final double val = v2.doubleValue(d2); l2 += val * val; ++d2; } if(d2 < dim2) { assert (d1 == d2) : "Dimensions not ordered"; final double val1 = v1.iterDoubleValue(i1); final double val2 = v2.doubleValue(d2); l1 += val1 * val1; l2 += val2 * val2; cross += val1 * val2; i1 = v1.iterAdvance(i1); ++d2; } else { final double val = v1.iterDoubleValue(i1); l1 += val * val; i1 = v1.iterAdvance(i1); } } while(d2 < dim2) { final double val = v2.doubleValue(d2); l2 += val * val; ++d2; } final double a = (cross == 0.) ? 0. : // (l1 == 0. || l2 == 0.) ? 1. : // FastMath.sqrt((cross / l1) * (cross / l2)); return (a < 1.) ? a : 1.; }
[ "public", "static", "double", "angleSparseDense", "(", "SparseNumberVector", "v1", ",", "NumberVector", "v2", ")", "{", "// TODO: exploit precomputed length, when available.", "final", "int", "dim2", "=", "v2", ".", "getDimensionality", "(", ")", ";", "double", "l1", "=", "0.", ",", "l2", "=", "0.", ",", "cross", "=", "0.", ";", "int", "i1", "=", "v1", ".", "iter", "(", ")", ",", "d2", "=", "0", ";", "while", "(", "v1", ".", "iterValid", "(", "i1", ")", ")", "{", "final", "int", "d1", "=", "v1", ".", "iterDim", "(", "i1", ")", ";", "while", "(", "d2", "<", "d1", "&&", "d2", "<", "dim2", ")", "{", "final", "double", "val", "=", "v2", ".", "doubleValue", "(", "d2", ")", ";", "l2", "+=", "val", "*", "val", ";", "++", "d2", ";", "}", "if", "(", "d2", "<", "dim2", ")", "{", "assert", "(", "d1", "==", "d2", ")", ":", "\"Dimensions not ordered\"", ";", "final", "double", "val1", "=", "v1", ".", "iterDoubleValue", "(", "i1", ")", ";", "final", "double", "val2", "=", "v2", ".", "doubleValue", "(", "d2", ")", ";", "l1", "+=", "val1", "*", "val1", ";", "l2", "+=", "val2", "*", "val2", ";", "cross", "+=", "val1", "*", "val2", ";", "i1", "=", "v1", ".", "iterAdvance", "(", "i1", ")", ";", "++", "d2", ";", "}", "else", "{", "final", "double", "val", "=", "v1", ".", "iterDoubleValue", "(", "i1", ")", ";", "l1", "+=", "val", "*", "val", ";", "i1", "=", "v1", ".", "iterAdvance", "(", "i1", ")", ";", "}", "}", "while", "(", "d2", "<", "dim2", ")", "{", "final", "double", "val", "=", "v2", ".", "doubleValue", "(", "d2", ")", ";", "l2", "+=", "val", "*", "val", ";", "++", "d2", ";", "}", "final", "double", "a", "=", "(", "cross", "==", "0.", ")", "?", "0.", ":", "//", "(", "l1", "==", "0.", "||", "l2", "==", "0.", ")", "?", "1.", ":", "//", "FastMath", ".", "sqrt", "(", "(", "cross", "/", "l1", ")", "*", "(", "cross", "/", "l2", ")", ")", ";", "return", "(", "a", "<", "1.", ")", "?", "a", ":", "1.", ";", "}" ]
Compute the angle for a sparse and a dense vector. @param v1 Sparse first vector @param v2 Dense second vector @return angle
[ "Compute", "the", "angle", "for", "a", "sparse", "and", "a", "dense", "vector", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/VectorUtil.java#L179-L216
rsocket/rsocket-java
rsocket-transport-netty/src/main/java/io/rsocket/transport/netty/server/WebsocketRouteTransport.java
WebsocketRouteTransport.newHandler
public static BiFunction<WebsocketInbound, WebsocketOutbound, Publisher<Void>> newHandler( ConnectionAcceptor acceptor) { """ Creates a new Websocket handler @param acceptor the {@link ConnectionAcceptor} to use with the handler @return a new Websocket handler @throws NullPointerException if {@code acceptor} is {@code null} """ return newHandler(acceptor, 0); }
java
public static BiFunction<WebsocketInbound, WebsocketOutbound, Publisher<Void>> newHandler( ConnectionAcceptor acceptor) { return newHandler(acceptor, 0); }
[ "public", "static", "BiFunction", "<", "WebsocketInbound", ",", "WebsocketOutbound", ",", "Publisher", "<", "Void", ">", ">", "newHandler", "(", "ConnectionAcceptor", "acceptor", ")", "{", "return", "newHandler", "(", "acceptor", ",", "0", ")", ";", "}" ]
Creates a new Websocket handler @param acceptor the {@link ConnectionAcceptor} to use with the handler @return a new Websocket handler @throws NullPointerException if {@code acceptor} is {@code null}
[ "Creates", "a", "new", "Websocket", "handler" ]
train
https://github.com/rsocket/rsocket-java/blob/5101748fbd224ec86570351cebd24d079b63fbfc/rsocket-transport-netty/src/main/java/io/rsocket/transport/netty/server/WebsocketRouteTransport.java#L97-L100
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceId.java
InstanceId.of
public static InstanceId of(ZoneId zoneId, String instance) { """ Returns an instance identity given the zone identity and the instance name. The instance name must be 1-63 characters long and comply with RFC1035. Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. @see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a> """ return new InstanceId(zoneId.getProject(), zoneId.getZone(), instance); }
java
public static InstanceId of(ZoneId zoneId, String instance) { return new InstanceId(zoneId.getProject(), zoneId.getZone(), instance); }
[ "public", "static", "InstanceId", "of", "(", "ZoneId", "zoneId", ",", "String", "instance", ")", "{", "return", "new", "InstanceId", "(", "zoneId", ".", "getProject", "(", ")", ",", "zoneId", ".", "getZone", "(", ")", ",", "instance", ")", ";", "}" ]
Returns an instance identity given the zone identity and the instance name. The instance name must be 1-63 characters long and comply with RFC1035. Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. @see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a>
[ "Returns", "an", "instance", "identity", "given", "the", "zone", "identity", "and", "the", "instance", "name", ".", "The", "instance", "name", "must", "be", "1", "-", "63", "characters", "long", "and", "comply", "with", "RFC1035", ".", "Specifically", "the", "name", "must", "match", "the", "regular", "expression", "{", "@code", "[", "a", "-", "z", "]", "(", "[", "-", "a", "-", "z0", "-", "9", "]", "*", "[", "a", "-", "z0", "-", "9", "]", ")", "?", "}", "which", "means", "the", "first", "character", "must", "be", "a", "lowercase", "letter", "and", "all", "following", "characters", "must", "be", "a", "dash", "lowercase", "letter", "or", "digit", "except", "the", "last", "character", "which", "cannot", "be", "a", "dash", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceId.java#L127-L129
abel533/Mapper
core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java
SqlHelper.logicDeleteColumnEqualsValue
public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) { """ 返回格式: column = value <br> 默认isDeletedValue = 1 notDeletedValue = 0 <br> 则返回is_deleted = 1 或 is_deleted = 0 <br> 若没有逻辑删除注解,则返回空字符串 @param column @param isDeleted true 已经逻辑删除 false 未逻辑删除 """ String result = ""; if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { result = column.getColumn() + " = " + getLogicDeletedValue(column, isDeleted); } return result; }
java
public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) { String result = ""; if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { result = column.getColumn() + " = " + getLogicDeletedValue(column, isDeleted); } return result; }
[ "public", "static", "String", "logicDeleteColumnEqualsValue", "(", "EntityColumn", "column", ",", "boolean", "isDeleted", ")", "{", "String", "result", "=", "\"\"", ";", "if", "(", "column", ".", "getEntityField", "(", ")", ".", "isAnnotationPresent", "(", "LogicDelete", ".", "class", ")", ")", "{", "result", "=", "column", ".", "getColumn", "(", ")", "+", "\" = \"", "+", "getLogicDeletedValue", "(", "column", ",", "isDeleted", ")", ";", "}", "return", "result", ";", "}" ]
返回格式: column = value <br> 默认isDeletedValue = 1 notDeletedValue = 0 <br> 则返回is_deleted = 1 或 is_deleted = 0 <br> 若没有逻辑删除注解,则返回空字符串 @param column @param isDeleted true 已经逻辑删除 false 未逻辑删除
[ "返回格式", ":", "column", "=", "value", "<br", ">", "默认isDeletedValue", "=", "1", "notDeletedValue", "=", "0", "<br", ">", "则返回is_deleted", "=", "1", "或", "is_deleted", "=", "0", "<br", ">", "若没有逻辑删除注解,则返回空字符串" ]
train
https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java#L762-L768
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ParsedScheduleExpression.java
ParsedScheduleExpression.getNextLastDayOfMonth
private int getNextLastDayOfMonth(int day, int lastDay) { """ Returns the next day of the month after <tt>day</tt> that satisfies the lastDayOfMonth constraint. @param day the current 0-based day of the month @param lastDay the current 0-based last day of the month @return a value greater than or equal to <tt>day</tt> """ // lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7 // Shift left so that "Last" aligns with the last day of the month. // For example, for Jan, we want the Last bit in position 31, so we // shift 30-7=23 (note: 0-based last day for Jan is 30) resulting in: // bits = 0b0100 0001 1000 0000 0000 0000 0000 0000 (LSB) int offset = lastDay - 7; long bits = lastDaysOfMonth << offset; if (!contains(bits, day)) { long higher = higher(bits, day); if (higher != 0) { return first(higher); } return ADVANCE_TO_NEXT_MONTH; } return day; }
java
private int getNextLastDayOfMonth(int day, int lastDay) { // lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7 // Shift left so that "Last" aligns with the last day of the month. // For example, for Jan, we want the Last bit in position 31, so we // shift 30-7=23 (note: 0-based last day for Jan is 30) resulting in: // bits = 0b0100 0001 1000 0000 0000 0000 0000 0000 (LSB) int offset = lastDay - 7; long bits = lastDaysOfMonth << offset; if (!contains(bits, day)) { long higher = higher(bits, day); if (higher != 0) { return first(higher); } return ADVANCE_TO_NEXT_MONTH; } return day; }
[ "private", "int", "getNextLastDayOfMonth", "(", "int", "day", ",", "int", "lastDay", ")", "{", "// lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7", "// Shift left so that \"Last\" aligns with the last day of the month.", "// For example, for Jan, we want the Last bit in position 31, so we", "// shift 30-7=23 (note: 0-based last day for Jan is 30) resulting in:", "// bits = 0b0100 0001 1000 0000 0000 0000 0000 0000 (LSB)", "int", "offset", "=", "lastDay", "-", "7", ";", "long", "bits", "=", "lastDaysOfMonth", "<<", "offset", ";", "if", "(", "!", "contains", "(", "bits", ",", "day", ")", ")", "{", "long", "higher", "=", "higher", "(", "bits", ",", "day", ")", ";", "if", "(", "higher", "!=", "0", ")", "{", "return", "first", "(", "higher", ")", ";", "}", "return", "ADVANCE_TO_NEXT_MONTH", ";", "}", "return", "day", ";", "}" ]
Returns the next day of the month after <tt>day</tt> that satisfies the lastDayOfMonth constraint. @param day the current 0-based day of the month @param lastDay the current 0-based last day of the month @return a value greater than or equal to <tt>day</tt>
[ "Returns", "the", "next", "day", "of", "the", "month", "after", "<tt", ">", "day<", "/", "tt", ">", "that", "satisfies", "the", "lastDayOfMonth", "constraint", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ParsedScheduleExpression.java#L937-L959
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.updateSasDefinition
public SasDefinitionBundle updateSasDefinition(String vaultBaseUrl, String storageAccountName, String sasDefinitionName) { """ Updates the specified attributes associated with the given SAS definition. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SasDefinitionBundle object if successful. """ return updateSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName).toBlocking().single().body(); }
java
public SasDefinitionBundle updateSasDefinition(String vaultBaseUrl, String storageAccountName, String sasDefinitionName) { return updateSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName).toBlocking().single().body(); }
[ "public", "SasDefinitionBundle", "updateSasDefinition", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "String", "sasDefinitionName", ")", "{", "return", "updateSasDefinitionWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageAccountName", ",", "sasDefinitionName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates the specified attributes associated with the given SAS definition. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SasDefinitionBundle object if successful.
[ "Updates", "the", "specified", "attributes", "associated", "with", "the", "given", "SAS", "definition", ".", "This", "operation", "requires", "the", "storage", "/", "setsas", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L11492-L11494
jingwei/krati
krati-main/src/main/java/krati/core/StoreConfig.java
StoreConfig.getFloat
public float getFloat(String pName, float defaultValue) { """ Gets a float property via a string property name. @param pName - the property name @param defaultValue - the default property value @return a float property """ String pValue = _properties.getProperty(pName); return parseFloat(pName, pValue, defaultValue); }
java
public float getFloat(String pName, float defaultValue) { String pValue = _properties.getProperty(pName); return parseFloat(pName, pValue, defaultValue); }
[ "public", "float", "getFloat", "(", "String", "pName", ",", "float", "defaultValue", ")", "{", "String", "pValue", "=", "_properties", ".", "getProperty", "(", "pName", ")", ";", "return", "parseFloat", "(", "pName", ",", "pValue", ",", "defaultValue", ")", ";", "}" ]
Gets a float property via a string property name. @param pName - the property name @param defaultValue - the default property value @return a float property
[ "Gets", "a", "float", "property", "via", "a", "string", "property", "name", "." ]
train
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/core/StoreConfig.java#L435-L438
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.catalog_formatted_cloud_GET
public OvhCatalog catalog_formatted_cloud_GET(OvhOvhSubsidiaryEnum ovhSubsidiary) throws IOException { """ Retrieve information of Public Cloud catalog REST: GET /order/catalog/formatted/cloud @param ovhSubsidiary [required] Subsidiary of the country you want to consult catalog API beta """ String qPath = "/order/catalog/formatted/cloud"; StringBuilder sb = path(qPath); query(sb, "ovhSubsidiary", ovhSubsidiary); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCatalog.class); }
java
public OvhCatalog catalog_formatted_cloud_GET(OvhOvhSubsidiaryEnum ovhSubsidiary) throws IOException { String qPath = "/order/catalog/formatted/cloud"; StringBuilder sb = path(qPath); query(sb, "ovhSubsidiary", ovhSubsidiary); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCatalog.class); }
[ "public", "OvhCatalog", "catalog_formatted_cloud_GET", "(", "OvhOvhSubsidiaryEnum", "ovhSubsidiary", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/catalog/formatted/cloud\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", ",", "\"ovhSubsidiary\"", ",", "ovhSubsidiary", ")", ";", "String", "resp", "=", "execN", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhCatalog", ".", "class", ")", ";", "}" ]
Retrieve information of Public Cloud catalog REST: GET /order/catalog/formatted/cloud @param ovhSubsidiary [required] Subsidiary of the country you want to consult catalog API beta
[ "Retrieve", "information", "of", "Public", "Cloud", "catalog" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L7006-L7012
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/BeanAccess.java
BeanAccess.getPropertyInfoDirectly
public static IPropertyInfo getPropertyInfoDirectly( IType classBean, String strProperty ) throws ParseException { """ Resolves the property directly, as if the type were requesting it, giving access to all properties """ return getPropertyInfo( classBean, classBean, strProperty, null, null, null ); }
java
public static IPropertyInfo getPropertyInfoDirectly( IType classBean, String strProperty ) throws ParseException { return getPropertyInfo( classBean, classBean, strProperty, null, null, null ); }
[ "public", "static", "IPropertyInfo", "getPropertyInfoDirectly", "(", "IType", "classBean", ",", "String", "strProperty", ")", "throws", "ParseException", "{", "return", "getPropertyInfo", "(", "classBean", ",", "classBean", ",", "strProperty", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Resolves the property directly, as if the type were requesting it, giving access to all properties
[ "Resolves", "the", "property", "directly", "as", "if", "the", "type", "were", "requesting", "it", "giving", "access", "to", "all", "properties" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/BeanAccess.java#L354-L357
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/build/Factory.java
Factory.registerAsType
public void registerAsType(Object locator, Class<?> type) { """ Registers a component using its type (a constructor function). @param locator a locator to identify component to be created. @param type a component type. """ if (locator == null) throw new NullPointerException("Locator cannot be null"); if (type == null) throw new NullPointerException("Type cannot be null"); IComponentFactory factory = new DefaultComponentFactory(type); _registrations.add(new Registration(locator, factory)); }
java
public void registerAsType(Object locator, Class<?> type) { if (locator == null) throw new NullPointerException("Locator cannot be null"); if (type == null) throw new NullPointerException("Type cannot be null"); IComponentFactory factory = new DefaultComponentFactory(type); _registrations.add(new Registration(locator, factory)); }
[ "public", "void", "registerAsType", "(", "Object", "locator", ",", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "locator", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"Locator cannot be null\"", ")", ";", "if", "(", "type", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"Type cannot be null\"", ")", ";", "IComponentFactory", "factory", "=", "new", "DefaultComponentFactory", "(", "type", ")", ";", "_registrations", ".", "add", "(", "new", "Registration", "(", "locator", ",", "factory", ")", ")", ";", "}" ]
Registers a component using its type (a constructor function). @param locator a locator to identify component to be created. @param type a component type.
[ "Registers", "a", "component", "using", "its", "type", "(", "a", "constructor", "function", ")", "." ]
train
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/build/Factory.java#L94-L102
grpc/grpc-java
netty/src/main/java/io/grpc/netty/GrpcSslContexts.java
GrpcSslContexts.configure
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784") @CanIgnoreReturnValue public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) { """ Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if an application requires particular settings it should override the options set here. """ switch (provider) { case JDK: { Provider jdkProvider = findJdkProvider(); if (jdkProvider == null) { throw new IllegalArgumentException( "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers"); } return configure(builder, jdkProvider); } case OPENSSL: { ApplicationProtocolConfig apc; if (OpenSsl.isAlpnSupported()) { apc = NPN_AND_ALPN; } else { apc = NPN; } return builder .sslProvider(SslProvider.OPENSSL) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(apc); } default: throw new IllegalArgumentException("Unsupported provider: " + provider); } }
java
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784") @CanIgnoreReturnValue public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) { switch (provider) { case JDK: { Provider jdkProvider = findJdkProvider(); if (jdkProvider == null) { throw new IllegalArgumentException( "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers"); } return configure(builder, jdkProvider); } case OPENSSL: { ApplicationProtocolConfig apc; if (OpenSsl.isAlpnSupported()) { apc = NPN_AND_ALPN; } else { apc = NPN; } return builder .sslProvider(SslProvider.OPENSSL) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(apc); } default: throw new IllegalArgumentException("Unsupported provider: " + provider); } }
[ "@", "ExperimentalApi", "(", "\"https://github.com/grpc/grpc-java/issues/1784\"", ")", "@", "CanIgnoreReturnValue", "public", "static", "SslContextBuilder", "configure", "(", "SslContextBuilder", "builder", ",", "SslProvider", "provider", ")", "{", "switch", "(", "provider", ")", "{", "case", "JDK", ":", "{", "Provider", "jdkProvider", "=", "findJdkProvider", "(", ")", ";", "if", "(", "jdkProvider", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers\"", ")", ";", "}", "return", "configure", "(", "builder", ",", "jdkProvider", ")", ";", "}", "case", "OPENSSL", ":", "{", "ApplicationProtocolConfig", "apc", ";", "if", "(", "OpenSsl", ".", "isAlpnSupported", "(", ")", ")", "{", "apc", "=", "NPN_AND_ALPN", ";", "}", "else", "{", "apc", "=", "NPN", ";", "}", "return", "builder", ".", "sslProvider", "(", "SslProvider", ".", "OPENSSL", ")", ".", "ciphers", "(", "Http2SecurityUtil", ".", "CIPHERS", ",", "SupportedCipherSuiteFilter", ".", "INSTANCE", ")", ".", "applicationProtocolConfig", "(", "apc", ")", ";", "}", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported provider: \"", "+", "provider", ")", ";", "}", "}" ]
Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if an application requires particular settings it should override the options set here.
[ "Set", "ciphers", "and", "APN", "appropriate", "for", "gRPC", ".", "Precisely", "what", "is", "set", "is", "permitted", "to", "change", "so", "if", "an", "application", "requires", "particular", "settings", "it", "should", "override", "the", "options", "set", "here", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/GrpcSslContexts.java#L178-L207
jqm4gwt/jqm4gwt
library/src/main/java/com/sksamuel/jqm4gwt/list/JQMListItem.java
JQMListItem.addHeaderText
public JQMListItem addHeaderText(int n, String html) { """ Adds a header element containing the given text. @param n - the Hn element to use, e.g. if n is 2 then a {@code <h2>} element is created. @param html - the value to set as the inner html of the {@code <hn>} element. """ Element e = Document.get().createHElement(n); e.setInnerHTML(html); attachChild(e); return this; }
java
public JQMListItem addHeaderText(int n, String html) { Element e = Document.get().createHElement(n); e.setInnerHTML(html); attachChild(e); return this; }
[ "public", "JQMListItem", "addHeaderText", "(", "int", "n", ",", "String", "html", ")", "{", "Element", "e", "=", "Document", ".", "get", "(", ")", ".", "createHElement", "(", "n", ")", ";", "e", ".", "setInnerHTML", "(", "html", ")", ";", "attachChild", "(", "e", ")", ";", "return", "this", ";", "}" ]
Adds a header element containing the given text. @param n - the Hn element to use, e.g. if n is 2 then a {@code <h2>} element is created. @param html - the value to set as the inner html of the {@code <hn>} element.
[ "Adds", "a", "header", "element", "containing", "the", "given", "text", "." ]
train
https://github.com/jqm4gwt/jqm4gwt/blob/cf59958e9ba6d4b70f42507b2c77f10c2465085b/library/src/main/java/com/sksamuel/jqm4gwt/list/JQMListItem.java#L173-L178
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java
ListManagementImagesImpl.addImageWithServiceResponseAsync
public Observable<ServiceResponse<Image>> addImageWithServiceResponseAsync(String listId, AddImageOptionalParameter addImageOptionalParameter) { """ Add an image to the list with list Id equal to list Id passed. @param listId List Id of the image list. @param addImageOptionalParameter 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 Image object """ if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (listId == null) { throw new IllegalArgumentException("Parameter listId is required and cannot be null."); } final Integer tag = addImageOptionalParameter != null ? addImageOptionalParameter.tag() : null; final String label = addImageOptionalParameter != null ? addImageOptionalParameter.label() : null; return addImageWithServiceResponseAsync(listId, tag, label); }
java
public Observable<ServiceResponse<Image>> addImageWithServiceResponseAsync(String listId, AddImageOptionalParameter addImageOptionalParameter) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (listId == null) { throw new IllegalArgumentException("Parameter listId is required and cannot be null."); } final Integer tag = addImageOptionalParameter != null ? addImageOptionalParameter.tag() : null; final String label = addImageOptionalParameter != null ? addImageOptionalParameter.label() : null; return addImageWithServiceResponseAsync(listId, tag, label); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Image", ">", ">", "addImageWithServiceResponseAsync", "(", "String", "listId", ",", "AddImageOptionalParameter", "addImageOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "baseUrl", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.baseUrl() is required and cannot be null.\"", ")", ";", "}", "if", "(", "listId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter listId is required and cannot be null.\"", ")", ";", "}", "final", "Integer", "tag", "=", "addImageOptionalParameter", "!=", "null", "?", "addImageOptionalParameter", ".", "tag", "(", ")", ":", "null", ";", "final", "String", "label", "=", "addImageOptionalParameter", "!=", "null", "?", "addImageOptionalParameter", ".", "label", "(", ")", ":", "null", ";", "return", "addImageWithServiceResponseAsync", "(", "listId", ",", "tag", ",", "label", ")", ";", "}" ]
Add an image to the list with list Id equal to list Id passed. @param listId List Id of the image list. @param addImageOptionalParameter 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 Image object
[ "Add", "an", "image", "to", "the", "list", "with", "list", "Id", "equal", "to", "list", "Id", "passed", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java#L147-L158
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.get_senders
public String get_senders(Map<String, String> data) { """ /* Get Access of created senders information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} option: Options to get senders. Possible options – IP-wise, & Domain-wise ( only for dedicated IP clients ). Example: to get senders with specific IP, use $option=’1.2.3.4′, to get senders with specific domain use, $option=’domain.com’, & to get all senders, use $option="" [Optional] """ String option = data.get("option"); String url; if (EMPTY_STRING.equals(option)) { url = "advanced/"; } else { url = "advanced/option/" + option + "/"; } return get(url, EMPTY_STRING); }
java
public String get_senders(Map<String, String> data) { String option = data.get("option"); String url; if (EMPTY_STRING.equals(option)) { url = "advanced/"; } else { url = "advanced/option/" + option + "/"; } return get(url, EMPTY_STRING); }
[ "public", "String", "get_senders", "(", "Map", "<", "String", ",", "String", ">", "data", ")", "{", "String", "option", "=", "data", ".", "get", "(", "\"option\"", ")", ";", "String", "url", ";", "if", "(", "EMPTY_STRING", ".", "equals", "(", "option", ")", ")", "{", "url", "=", "\"advanced/\"", ";", "}", "else", "{", "url", "=", "\"advanced/option/\"", "+", "option", "+", "\"/\"", ";", "}", "return", "get", "(", "url", ",", "EMPTY_STRING", ")", ";", "}" ]
/* Get Access of created senders information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} option: Options to get senders. Possible options – IP-wise, & Domain-wise ( only for dedicated IP clients ). Example: to get senders with specific IP, use $option=’1.2.3.4′, to get senders with specific domain use, $option=’domain.com’, & to get all senders, use $option="" [Optional]
[ "/", "*", "Get", "Access", "of", "created", "senders", "information", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L1037-L1047
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoGpsLog.java
DaoGpsLog.getEnvelope
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception { """ Get the current data envelope. @param connection the db connection. @return the envelope. @throws Exception """ String query = "SELECT min(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), min(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + ") " + // " FROM " + TABLE_GPSLOG_DATA; try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) { if (rs.next()) { double minX = rs.getDouble(1); double maxX = rs.getDouble(2); double minY = rs.getDouble(3); double maxY = rs.getDouble(4); ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84); return env; } } return null; }
java
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception { String query = "SELECT min(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), min(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + ") " + // " FROM " + TABLE_GPSLOG_DATA; try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) { if (rs.next()) { double minX = rs.getDouble(1); double maxX = rs.getDouble(2); double minY = rs.getDouble(3); double maxY = rs.getDouble(4); ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84); return env; } } return null; }
[ "public", "static", "ReferencedEnvelope", "getEnvelope", "(", "IHMConnection", "connection", ")", "throws", "Exception", "{", "String", "query", "=", "\"SELECT min(\"", "+", "//", "GpsLogsDataTableFields", ".", "COLUMN_DATA_LON", ".", "getFieldName", "(", ")", "+", "\"), max(\"", "+", "//", "GpsLogsDataTableFields", ".", "COLUMN_DATA_LON", ".", "getFieldName", "(", ")", "+", "\"), min(\"", "+", "//", "GpsLogsDataTableFields", ".", "COLUMN_DATA_LAT", ".", "getFieldName", "(", ")", "+", "\"), max(\"", "+", "//", "GpsLogsDataTableFields", ".", "COLUMN_DATA_LAT", ".", "getFieldName", "(", ")", "+", "\") \"", "+", "//", "\" FROM \"", "+", "TABLE_GPSLOG_DATA", ";", "try", "(", "IHMStatement", "statement", "=", "connection", ".", "createStatement", "(", ")", ";", "IHMResultSet", "rs", "=", "statement", ".", "executeQuery", "(", "query", ")", ";", ")", "{", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "double", "minX", "=", "rs", ".", "getDouble", "(", "1", ")", ";", "double", "maxX", "=", "rs", ".", "getDouble", "(", "2", ")", ";", "double", "minY", "=", "rs", ".", "getDouble", "(", "3", ")", ";", "double", "maxY", "=", "rs", ".", "getDouble", "(", "4", ")", ";", "ReferencedEnvelope", "env", "=", "new", "ReferencedEnvelope", "(", "minX", ",", "maxX", ",", "minY", ",", "maxY", ",", "DefaultGeographicCRS", ".", "WGS84", ")", ";", "return", "env", ";", "}", "}", "return", "null", ";", "}" ]
Get the current data envelope. @param connection the db connection. @return the envelope. @throws Exception
[ "Get", "the", "current", "data", "envelope", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoGpsLog.java#L374-L394
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/datamovement/HostAvailabilityListener.java
HostAvailabilityListener.processFailure
public void processFailure(WriteBatch batch, Throwable throwable) { """ This implements the WriteFailureListener interface @param batch the batch of WriteEvents @param throwable the exception """ boolean isHostUnavailableException = processException(batch.getBatcher(), throwable, batch.getClient().getHost()); if ( isHostUnavailableException == true ) { try { logger.warn("Retrying failed batch: {}, results so far: {}, uris: {}", batch.getJobBatchNumber(), batch.getJobWritesSoFar(), Stream.of(batch.getItems()).map(event->event.getTargetUri()).collect(Collectors.toList())); batch.getBatcher().retryWithFailureListeners(batch); } catch (RuntimeException e) { logger.error("Exception during retry", e); processFailure(batch, e); } } }
java
public void processFailure(WriteBatch batch, Throwable throwable) { boolean isHostUnavailableException = processException(batch.getBatcher(), throwable, batch.getClient().getHost()); if ( isHostUnavailableException == true ) { try { logger.warn("Retrying failed batch: {}, results so far: {}, uris: {}", batch.getJobBatchNumber(), batch.getJobWritesSoFar(), Stream.of(batch.getItems()).map(event->event.getTargetUri()).collect(Collectors.toList())); batch.getBatcher().retryWithFailureListeners(batch); } catch (RuntimeException e) { logger.error("Exception during retry", e); processFailure(batch, e); } } }
[ "public", "void", "processFailure", "(", "WriteBatch", "batch", ",", "Throwable", "throwable", ")", "{", "boolean", "isHostUnavailableException", "=", "processException", "(", "batch", ".", "getBatcher", "(", ")", ",", "throwable", ",", "batch", ".", "getClient", "(", ")", ".", "getHost", "(", ")", ")", ";", "if", "(", "isHostUnavailableException", "==", "true", ")", "{", "try", "{", "logger", ".", "warn", "(", "\"Retrying failed batch: {}, results so far: {}, uris: {}\"", ",", "batch", ".", "getJobBatchNumber", "(", ")", ",", "batch", ".", "getJobWritesSoFar", "(", ")", ",", "Stream", ".", "of", "(", "batch", ".", "getItems", "(", ")", ")", ".", "map", "(", "event", "->", "event", ".", "getTargetUri", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "batch", ".", "getBatcher", "(", ")", ".", "retryWithFailureListeners", "(", "batch", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "logger", ".", "error", "(", "\"Exception during retry\"", ",", "e", ")", ";", "processFailure", "(", "batch", ",", "e", ")", ";", "}", "}", "}" ]
This implements the WriteFailureListener interface @param batch the batch of WriteEvents @param throwable the exception
[ "This", "implements", "the", "WriteFailureListener", "interface" ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/datamovement/HostAvailabilityListener.java#L193-L206
notnoop/java-apns
src/main/java/com/notnoop/apns/ApnsServiceBuilder.java
ApnsServiceBuilder.withSocksProxy
public ApnsServiceBuilder withSocksProxy(String host, int port) { """ Specify the address of the SOCKS proxy the connection should use. <p>Read the <a href="http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html"> Java Networking and Proxies</a> guide to understand the proxies complexity. <p>Be aware that this method only handles SOCKS proxies, not HTTPS proxies. Use {@link #withProxy(Proxy)} instead. @param host the hostname of the SOCKS proxy @param port the port of the SOCKS proxy server @return this """ Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(host, port)); return withProxy(proxy); }
java
public ApnsServiceBuilder withSocksProxy(String host, int port) { Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(host, port)); return withProxy(proxy); }
[ "public", "ApnsServiceBuilder", "withSocksProxy", "(", "String", "host", ",", "int", "port", ")", "{", "Proxy", "proxy", "=", "new", "Proxy", "(", "Proxy", ".", "Type", ".", "SOCKS", ",", "new", "InetSocketAddress", "(", "host", ",", "port", ")", ")", ";", "return", "withProxy", "(", "proxy", ")", ";", "}" ]
Specify the address of the SOCKS proxy the connection should use. <p>Read the <a href="http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html"> Java Networking and Proxies</a> guide to understand the proxies complexity. <p>Be aware that this method only handles SOCKS proxies, not HTTPS proxies. Use {@link #withProxy(Proxy)} instead. @param host the hostname of the SOCKS proxy @param port the port of the SOCKS proxy server @return this
[ "Specify", "the", "address", "of", "the", "SOCKS", "proxy", "the", "connection", "should", "use", "." ]
train
https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/ApnsServiceBuilder.java#L469-L473
vznet/mongo-jackson-mapper
src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java
JacksonDBCollection.ensureIndex
public void ensureIndex(DBObject keys, String name, boolean unique) throws MongoException { """ Ensures an index on this collection (that is, the index will be created if it does not exist). @param keys fields to use for index @param name an identifier for the index. If null or empty, the default name will be used. @param unique if the index should be unique @throws MongoException If an error occurred """ dbCollection.ensureIndex(keys, name, unique); }
java
public void ensureIndex(DBObject keys, String name, boolean unique) throws MongoException { dbCollection.ensureIndex(keys, name, unique); }
[ "public", "void", "ensureIndex", "(", "DBObject", "keys", ",", "String", "name", ",", "boolean", "unique", ")", "throws", "MongoException", "{", "dbCollection", ".", "ensureIndex", "(", "keys", ",", "name", ",", "unique", ")", ";", "}" ]
Ensures an index on this collection (that is, the index will be created if it does not exist). @param keys fields to use for index @param name an identifier for the index. If null or empty, the default name will be used. @param unique if the index should be unique @throws MongoException If an error occurred
[ "Ensures", "an", "index", "on", "this", "collection", "(", "that", "is", "the", "index", "will", "be", "created", "if", "it", "does", "not", "exist", ")", "." ]
train
https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java#L722-L724
unbescape/unbescape
src/main/java/org/unbescape/html/HtmlEscapeUtil.java
HtmlEscapeUtil.parseIntFromReference
static int parseIntFromReference(final String text, final int start, final int end, final int radix) { """ /* This methods (the two versions) are used instead of Integer.parseInt(str,radix) in order to avoid the need to create substrings of the text being unescaped to feed such method. - No need to check all chars are within the radix limits - reference parsing code will already have done so. """ int result = 0; for (int i = start; i < end; i++) { final char c = text.charAt(i); int n = -1; for (int j = 0; j < HEXA_CHARS_UPPER.length; j++) { if (c == HEXA_CHARS_UPPER[j] || c == HEXA_CHARS_LOWER[j]) { n = j; break; } } result *= radix; if (result < 0) { return 0xFFFD; } result += n; if (result < 0) { return 0xFFFD; } } return result; }
java
static int parseIntFromReference(final String text, final int start, final int end, final int radix) { int result = 0; for (int i = start; i < end; i++) { final char c = text.charAt(i); int n = -1; for (int j = 0; j < HEXA_CHARS_UPPER.length; j++) { if (c == HEXA_CHARS_UPPER[j] || c == HEXA_CHARS_LOWER[j]) { n = j; break; } } result *= radix; if (result < 0) { return 0xFFFD; } result += n; if (result < 0) { return 0xFFFD; } } return result; }
[ "static", "int", "parseIntFromReference", "(", "final", "String", "text", ",", "final", "int", "start", ",", "final", "int", "end", ",", "final", "int", "radix", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "final", "char", "c", "=", "text", ".", "charAt", "(", "i", ")", ";", "int", "n", "=", "-", "1", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "HEXA_CHARS_UPPER", ".", "length", ";", "j", "++", ")", "{", "if", "(", "c", "==", "HEXA_CHARS_UPPER", "[", "j", "]", "||", "c", "==", "HEXA_CHARS_LOWER", "[", "j", "]", ")", "{", "n", "=", "j", ";", "break", ";", "}", "}", "result", "*=", "radix", ";", "if", "(", "result", "<", "0", ")", "{", "return", "0xFFFD", ";", "}", "result", "+=", "n", ";", "if", "(", "result", "<", "0", ")", "{", "return", "0xFFFD", ";", "}", "}", "return", "result", ";", "}" ]
/* This methods (the two versions) are used instead of Integer.parseInt(str,radix) in order to avoid the need to create substrings of the text being unescaped to feed such method. - No need to check all chars are within the radix limits - reference parsing code will already have done so.
[ "/", "*", "This", "methods", "(", "the", "two", "versions", ")", "are", "used", "instead", "of", "Integer", ".", "parseInt", "(", "str", "radix", ")", "in", "order", "to", "avoid", "the", "need", "to", "create", "substrings", "of", "the", "text", "being", "unescaped", "to", "feed", "such", "method", ".", "-", "No", "need", "to", "check", "all", "chars", "are", "within", "the", "radix", "limits", "-", "reference", "parsing", "code", "will", "already", "have", "done", "so", "." ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscapeUtil.java#L557-L578
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureFromHomographies.java
ProjectiveStructureFromHomographies.constructLinearSystem
void constructLinearSystem(List<DMatrixRMaj> homographies, List<List<PointIndex2D_F64>> observations) { """ Constructs the linear systems. Unknowns are sorted in index order. structure (3D points) are first followed by unknown t from projective. """ // parameters are encoded points first then the int startView = totalFeatures*3; A.reshape(numEquations,numUnknown); DMatrixRMaj H = new DMatrixRMaj(3,3); Point2D_F64 p = new Point2D_F64(); int row = 0; for (int viewIdx = 0; viewIdx < homographies.size(); viewIdx++) { N.apply(homographies.get(viewIdx),H); int colView = startView + viewIdx*3; List<PointIndex2D_F64> obs = observations.get(viewIdx); for (int i = 0; i < obs.size(); i++) { PointIndex2D_F64 p_pixel = obs.get(i); N.apply(p_pixel,p); // column this feature is at int col = p_pixel.index*3; // x component of pixel // A(row,colView) = ... A.data[row*A.numCols + col ] = p.x*H.get(2,0) - H.get(0,0); A.data[row*A.numCols + col + 1] = p.x*H.get(2,1) - H.get(0,1); A.data[row*A.numCols + col + 2] = p.x*H.get(2,2) - H.get(0,2); A.data[row*A.numCols + colView ] = -1; A.data[row*A.numCols + colView + 1 ] = 0; A.data[row*A.numCols + colView + 2 ] = p.x; // y component of pixel row += 1; A.data[row*A.numCols + col ] = p.y*H.get(2,0) - H.get(1,0); A.data[row*A.numCols + col + 1] = p.y*H.get(2,1) - H.get(1,1); A.data[row*A.numCols + col + 2] = p.y*H.get(2,2) - H.get(1,2); A.data[row*A.numCols + colView ] = 0; A.data[row*A.numCols + colView + 1 ] = -1; A.data[row*A.numCols + colView + 2 ] = p.y; row += 1; } } }
java
void constructLinearSystem(List<DMatrixRMaj> homographies, List<List<PointIndex2D_F64>> observations) { // parameters are encoded points first then the int startView = totalFeatures*3; A.reshape(numEquations,numUnknown); DMatrixRMaj H = new DMatrixRMaj(3,3); Point2D_F64 p = new Point2D_F64(); int row = 0; for (int viewIdx = 0; viewIdx < homographies.size(); viewIdx++) { N.apply(homographies.get(viewIdx),H); int colView = startView + viewIdx*3; List<PointIndex2D_F64> obs = observations.get(viewIdx); for (int i = 0; i < obs.size(); i++) { PointIndex2D_F64 p_pixel = obs.get(i); N.apply(p_pixel,p); // column this feature is at int col = p_pixel.index*3; // x component of pixel // A(row,colView) = ... A.data[row*A.numCols + col ] = p.x*H.get(2,0) - H.get(0,0); A.data[row*A.numCols + col + 1] = p.x*H.get(2,1) - H.get(0,1); A.data[row*A.numCols + col + 2] = p.x*H.get(2,2) - H.get(0,2); A.data[row*A.numCols + colView ] = -1; A.data[row*A.numCols + colView + 1 ] = 0; A.data[row*A.numCols + colView + 2 ] = p.x; // y component of pixel row += 1; A.data[row*A.numCols + col ] = p.y*H.get(2,0) - H.get(1,0); A.data[row*A.numCols + col + 1] = p.y*H.get(2,1) - H.get(1,1); A.data[row*A.numCols + col + 2] = p.y*H.get(2,2) - H.get(1,2); A.data[row*A.numCols + colView ] = 0; A.data[row*A.numCols + colView + 1 ] = -1; A.data[row*A.numCols + colView + 2 ] = p.y; row += 1; } } }
[ "void", "constructLinearSystem", "(", "List", "<", "DMatrixRMaj", ">", "homographies", ",", "List", "<", "List", "<", "PointIndex2D_F64", ">", ">", "observations", ")", "{", "// parameters are encoded points first then the", "int", "startView", "=", "totalFeatures", "*", "3", ";", "A", ".", "reshape", "(", "numEquations", ",", "numUnknown", ")", ";", "DMatrixRMaj", "H", "=", "new", "DMatrixRMaj", "(", "3", ",", "3", ")", ";", "Point2D_F64", "p", "=", "new", "Point2D_F64", "(", ")", ";", "int", "row", "=", "0", ";", "for", "(", "int", "viewIdx", "=", "0", ";", "viewIdx", "<", "homographies", ".", "size", "(", ")", ";", "viewIdx", "++", ")", "{", "N", ".", "apply", "(", "homographies", ".", "get", "(", "viewIdx", ")", ",", "H", ")", ";", "int", "colView", "=", "startView", "+", "viewIdx", "*", "3", ";", "List", "<", "PointIndex2D_F64", ">", "obs", "=", "observations", ".", "get", "(", "viewIdx", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "obs", ".", "size", "(", ")", ";", "i", "++", ")", "{", "PointIndex2D_F64", "p_pixel", "=", "obs", ".", "get", "(", "i", ")", ";", "N", ".", "apply", "(", "p_pixel", ",", "p", ")", ";", "// column this feature is at", "int", "col", "=", "p_pixel", ".", "index", "*", "3", ";", "// x component of pixel", "// A(row,colView) = ...", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "]", "=", "p", ".", "x", "*", "H", ".", "get", "(", "2", ",", "0", ")", "-", "H", ".", "get", "(", "0", ",", "0", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "+", "1", "]", "=", "p", ".", "x", "*", "H", ".", "get", "(", "2", ",", "1", ")", "-", "H", ".", "get", "(", "0", ",", "1", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "+", "2", "]", "=", "p", ".", "x", "*", "H", ".", "get", "(", "2", ",", "2", ")", "-", "H", ".", "get", "(", "0", ",", "2", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "]", "=", "-", "1", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "+", "1", "]", "=", "0", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "+", "2", "]", "=", "p", ".", "x", ";", "// y component of pixel", "row", "+=", "1", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "]", "=", "p", ".", "y", "*", "H", ".", "get", "(", "2", ",", "0", ")", "-", "H", ".", "get", "(", "1", ",", "0", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "+", "1", "]", "=", "p", ".", "y", "*", "H", ".", "get", "(", "2", ",", "1", ")", "-", "H", ".", "get", "(", "1", ",", "1", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "col", "+", "2", "]", "=", "p", ".", "y", "*", "H", ".", "get", "(", "2", ",", "2", ")", "-", "H", ".", "get", "(", "1", ",", "2", ")", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "]", "=", "0", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "+", "1", "]", "=", "-", "1", ";", "A", ".", "data", "[", "row", "*", "A", ".", "numCols", "+", "colView", "+", "2", "]", "=", "p", ".", "y", ";", "row", "+=", "1", ";", "}", "}", "}" ]
Constructs the linear systems. Unknowns are sorted in index order. structure (3D points) are first followed by unknown t from projective.
[ "Constructs", "the", "linear", "systems", ".", "Unknowns", "are", "sorted", "in", "index", "order", ".", "structure", "(", "3D", "points", ")", "are", "first", "followed", "by", "unknown", "t", "from", "projective", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureFromHomographies.java#L156-L204
ZieIony/Carbon
carbon/src/main/java/carbon/drawable/ripple/LollipopDrawablesCompat.java
LollipopDrawablesCompat.applyTheme
public static void applyTheme(Drawable d, Resources.Theme t) { """ Applies the specified theme to this Drawable and its children. """ IMPL.applyTheme(d, t); }
java
public static void applyTheme(Drawable d, Resources.Theme t) { IMPL.applyTheme(d, t); }
[ "public", "static", "void", "applyTheme", "(", "Drawable", "d", ",", "Resources", ".", "Theme", "t", ")", "{", "IMPL", ".", "applyTheme", "(", "d", ",", "t", ")", ";", "}" ]
Applies the specified theme to this Drawable and its children.
[ "Applies", "the", "specified", "theme", "to", "this", "Drawable", "and", "its", "children", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LollipopDrawablesCompat.java#L62-L64
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/filter/PerfFilter.java
PerfFilter.doFilter
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { """ Updates performance counters using the Argus monitoring service. @param request The HTTP request. @param response The HTTP response. @param chain The filter chain to execute. @throws IOException If an I/O error occurs. @throws ServletException If an unknown error occurs. """ HttpServletRequest req = HttpServletRequest.class.cast(request); long start = System.currentTimeMillis(); try { chain.doFilter(request, response); } finally { long delta = System.currentTimeMillis() - start; HttpServletResponse resp = HttpServletResponse.class.cast(response); updateCounters(req, resp, delta); } }
java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = HttpServletRequest.class.cast(request); long start = System.currentTimeMillis(); try { chain.doFilter(request, response); } finally { long delta = System.currentTimeMillis() - start; HttpServletResponse resp = HttpServletResponse.class.cast(response); updateCounters(req, resp, delta); } }
[ "@", "Override", "public", "void", "doFilter", "(", "ServletRequest", "request", ",", "ServletResponse", "response", ",", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "req", "=", "HttpServletRequest", ".", "class", ".", "cast", "(", "request", ")", ";", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "try", "{", "chain", ".", "doFilter", "(", "request", ",", "response", ")", ";", "}", "finally", "{", "long", "delta", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "HttpServletResponse", "resp", "=", "HttpServletResponse", ".", "class", ".", "cast", "(", "response", ")", ";", "updateCounters", "(", "req", ",", "resp", ",", "delta", ")", ";", "}", "}" ]
Updates performance counters using the Argus monitoring service. @param request The HTTP request. @param response The HTTP response. @param chain The filter chain to execute. @throws IOException If an I/O error occurs. @throws ServletException If an unknown error occurs.
[ "Updates", "performance", "counters", "using", "the", "Argus", "monitoring", "service", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/filter/PerfFilter.java#L97-L110
h2oai/h2o-3
h2o-extensions/xgboost/src/main/java/ml/dmlc/xgboost4j/java/XGBoostSetupTask.java
XGBoostSetupTask.findFrameNodes
public static FrameNodes findFrameNodes(Frame fr) { """ Finds what nodes actually do carry some of data of a given Frame @param fr frame to find nodes for @return FrameNodes """ // Count on how many nodes the data resides boolean[] nodesHoldingFrame = new boolean[H2O.CLOUD.size()]; Vec vec = fr.anyVec(); for(int chunkNr = 0; chunkNr < vec.nChunks(); chunkNr++) { int home = vec.chunkKey(chunkNr).home_node().index(); if (! nodesHoldingFrame[home]) nodesHoldingFrame[home] = true; } return new FrameNodes(fr, nodesHoldingFrame); }
java
public static FrameNodes findFrameNodes(Frame fr) { // Count on how many nodes the data resides boolean[] nodesHoldingFrame = new boolean[H2O.CLOUD.size()]; Vec vec = fr.anyVec(); for(int chunkNr = 0; chunkNr < vec.nChunks(); chunkNr++) { int home = vec.chunkKey(chunkNr).home_node().index(); if (! nodesHoldingFrame[home]) nodesHoldingFrame[home] = true; } return new FrameNodes(fr, nodesHoldingFrame); }
[ "public", "static", "FrameNodes", "findFrameNodes", "(", "Frame", "fr", ")", "{", "// Count on how many nodes the data resides", "boolean", "[", "]", "nodesHoldingFrame", "=", "new", "boolean", "[", "H2O", ".", "CLOUD", ".", "size", "(", ")", "]", ";", "Vec", "vec", "=", "fr", ".", "anyVec", "(", ")", ";", "for", "(", "int", "chunkNr", "=", "0", ";", "chunkNr", "<", "vec", ".", "nChunks", "(", ")", ";", "chunkNr", "++", ")", "{", "int", "home", "=", "vec", ".", "chunkKey", "(", "chunkNr", ")", ".", "home_node", "(", ")", ".", "index", "(", ")", ";", "if", "(", "!", "nodesHoldingFrame", "[", "home", "]", ")", "nodesHoldingFrame", "[", "home", "]", "=", "true", ";", "}", "return", "new", "FrameNodes", "(", "fr", ",", "nodesHoldingFrame", ")", ";", "}" ]
Finds what nodes actually do carry some of data of a given Frame @param fr frame to find nodes for @return FrameNodes
[ "Finds", "what", "nodes", "actually", "do", "carry", "some", "of", "data", "of", "a", "given", "Frame" ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-extensions/xgboost/src/main/java/ml/dmlc/xgboost4j/java/XGBoostSetupTask.java#L82-L92
paypal/SeLion
client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java
AbstractBaseLocalServerComponent.checkPort
void checkPort(int port, String msg) { """ Check the port availability @param port the port to check @param msg the text to append to the end of the error message displayed when the port is not available. @throws IllegalArgumentException when the port is not available. """ StringBuilder message = new StringBuilder().append(" ").append(msg); String portInUseError = String.format("Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different port%s.", port, message); boolean free = false; try { free = PortProber.pollPort(port); } catch (RuntimeException e) { throw new IllegalArgumentException(portInUseError, e); } finally { if (!free) { throw new IllegalArgumentException(portInUseError); } } }
java
void checkPort(int port, String msg) { StringBuilder message = new StringBuilder().append(" ").append(msg); String portInUseError = String.format("Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different port%s.", port, message); boolean free = false; try { free = PortProber.pollPort(port); } catch (RuntimeException e) { throw new IllegalArgumentException(portInUseError, e); } finally { if (!free) { throw new IllegalArgumentException(portInUseError); } } }
[ "void", "checkPort", "(", "int", "port", ",", "String", "msg", ")", "{", "StringBuilder", "message", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "msg", ")", ";", "String", "portInUseError", "=", "String", ".", "format", "(", "\"Port %d is already in use. Please shutdown the service \"", "+", "\"listening on this port or configure a different port%s.\"", ",", "port", ",", "message", ")", ";", "boolean", "free", "=", "false", ";", "try", "{", "free", "=", "PortProber", ".", "pollPort", "(", "port", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "portInUseError", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "!", "free", ")", "{", "throw", "new", "IllegalArgumentException", "(", "portInUseError", ")", ";", "}", "}", "}" ]
Check the port availability @param port the port to check @param msg the text to append to the end of the error message displayed when the port is not available. @throws IllegalArgumentException when the port is not available.
[ "Check", "the", "port", "availability" ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java#L112-L126
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/XSLTAttributeDef.java
XSLTAttributeDef.processCHAR
Object processCHAR( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { """ Process an attribute string of type T_CHAR into a Character value. @param handler non-null reference to current StylesheetHandler that is constructing the Templates. @param uri The Namespace URI, or an empty string. @param name The local name (without prefix), or empty string if not namespace processing. @param rawName The qualified name (with prefix). @param value Should be a string with a length of 1. @return Character object. @throws org.xml.sax.SAXException if the string is not a length of 1. """ if (getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); // If an AVT wasn't used, validate the value if ((avt.isSimple()) && (value.length() != 1)) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return avt; } catch (TransformerException te) { throw new org.xml.sax.SAXException(te); } } else { if (value.length() != 1) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return new Character(value.charAt(0)); } }
java
Object processCHAR( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { if (getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); // If an AVT wasn't used, validate the value if ((avt.isSimple()) && (value.length() != 1)) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return avt; } catch (TransformerException te) { throw new org.xml.sax.SAXException(te); } } else { if (value.length() != 1) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return new Character(value.charAt(0)); } }
[ "Object", "processCHAR", "(", "StylesheetHandler", "handler", ",", "String", "uri", ",", "String", "name", ",", "String", "rawName", ",", "String", "value", ",", "ElemTemplateElement", "owner", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "if", "(", "getSupportsAVT", "(", ")", ")", "{", "try", "{", "AVT", "avt", "=", "new", "AVT", "(", "handler", ",", "uri", ",", "name", ",", "rawName", ",", "value", ",", "owner", ")", ";", "// If an AVT wasn't used, validate the value", "if", "(", "(", "avt", ".", "isSimple", "(", ")", ")", "&&", "(", "value", ".", "length", "(", ")", "!=", "1", ")", ")", "{", "handleError", "(", "handler", ",", "XSLTErrorResources", ".", "INVALID_TCHAR", ",", "new", "Object", "[", "]", "{", "name", ",", "value", "}", ",", "null", ")", ";", "return", "null", ";", "}", "return", "avt", ";", "}", "catch", "(", "TransformerException", "te", ")", "{", "throw", "new", "org", ".", "xml", ".", "sax", ".", "SAXException", "(", "te", ")", ";", "}", "}", "else", "{", "if", "(", "value", ".", "length", "(", ")", "!=", "1", ")", "{", "handleError", "(", "handler", ",", "XSLTErrorResources", ".", "INVALID_TCHAR", ",", "new", "Object", "[", "]", "{", "name", ",", "value", "}", ",", "null", ")", ";", "return", "null", ";", "}", "return", "new", "Character", "(", "value", ".", "charAt", "(", "0", ")", ")", ";", "}", "}" ]
Process an attribute string of type T_CHAR into a Character value. @param handler non-null reference to current StylesheetHandler that is constructing the Templates. @param uri The Namespace URI, or an empty string. @param name The local name (without prefix), or empty string if not namespace processing. @param rawName The qualified name (with prefix). @param value Should be a string with a length of 1. @return Character object. @throws org.xml.sax.SAXException if the string is not a length of 1.
[ "Process", "an", "attribute", "string", "of", "type", "T_CHAR", "into", "a", "Character", "value", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/XSLTAttributeDef.java#L577-L606
OpenLiberty/open-liberty
dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPATokenizer.java
LTPATokenizer.addAttributes
private static void addAttributes(String data, Map<String, ArrayList<String>> attribs) { """ Given a specified String, parse to find attributes and add to specified Map. @param data String to parse attribtues from @param attribs Target map to add attributes """ String key; String value; int keyIndex = 0; int dataLen = data.length(); for (keyIndex = 0; keyIndex < dataLen; keyIndex++) { if ((data.charAt(keyIndex) == USER_ATTRIB_DELIM) && (data.charAt(keyIndex - 1) != '\\')) { key = data.substring(0, keyIndex); value = data.substring(keyIndex + 1, dataLen); ArrayList<String> list = convertStringToArrayList(value); if (list != null) { attribs.put(key, list); } } } }
java
private static void addAttributes(String data, Map<String, ArrayList<String>> attribs) { String key; String value; int keyIndex = 0; int dataLen = data.length(); for (keyIndex = 0; keyIndex < dataLen; keyIndex++) { if ((data.charAt(keyIndex) == USER_ATTRIB_DELIM) && (data.charAt(keyIndex - 1) != '\\')) { key = data.substring(0, keyIndex); value = data.substring(keyIndex + 1, dataLen); ArrayList<String> list = convertStringToArrayList(value); if (list != null) { attribs.put(key, list); } } } }
[ "private", "static", "void", "addAttributes", "(", "String", "data", ",", "Map", "<", "String", ",", "ArrayList", "<", "String", ">", ">", "attribs", ")", "{", "String", "key", ";", "String", "value", ";", "int", "keyIndex", "=", "0", ";", "int", "dataLen", "=", "data", ".", "length", "(", ")", ";", "for", "(", "keyIndex", "=", "0", ";", "keyIndex", "<", "dataLen", ";", "keyIndex", "++", ")", "{", "if", "(", "(", "data", ".", "charAt", "(", "keyIndex", ")", "==", "USER_ATTRIB_DELIM", ")", "&&", "(", "data", ".", "charAt", "(", "keyIndex", "-", "1", ")", "!=", "'", "'", ")", ")", "{", "key", "=", "data", ".", "substring", "(", "0", ",", "keyIndex", ")", ";", "value", "=", "data", ".", "substring", "(", "keyIndex", "+", "1", ",", "dataLen", ")", ";", "ArrayList", "<", "String", ">", "list", "=", "convertStringToArrayList", "(", "value", ")", ";", "if", "(", "list", "!=", "null", ")", "{", "attribs", ".", "put", "(", "key", ",", "list", ")", ";", "}", "}", "}", "}" ]
Given a specified String, parse to find attributes and add to specified Map. @param data String to parse attribtues from @param attribs Target map to add attributes
[ "Given", "a", "specified", "String", "parse", "to", "find", "attributes", "and", "add", "to", "specified", "Map", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPATokenizer.java#L130-L145
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/Main.java
Main.initializeLogging
protected static boolean initializeLogging() { """ Initializes logging, specifically by looking for log4j.xml or log4j.properties file in DataCleaner's home directory. @return true if a logging configuration file was found, or false otherwise """ try { // initial logging config, used before anything else { final URL url = Main.class.getResource("log4j-initial.xml"); assert url != null; DOMConfigurator.configure(url); } if (ClassLoaderUtils.IS_WEB_START) { final URL url = Main.class.getResource("log4j-jnlp.xml"); assert url != null; println("Using JNLP log configuration: " + url); DOMConfigurator.configure(url); return true; } final File dataCleanerHome = DataCleanerHome.getAsFile(); if (initializeLoggingFromDirectory(dataCleanerHome)) { return true; } if (initializeLoggingFromDirectory(new File("."))) { return true; } // fall back to default log4j.xml file in classpath final URL url = Main.class.getResource("log4j-default.xml"); assert url != null; println("Using default log configuration: " + url); DOMConfigurator.configure(url); return false; } catch (final NoClassDefFoundError e) { // can happen if log4j is not on the classpath println("Failed to initialize logging, class not found: " + e.getMessage()); return false; } }
java
protected static boolean initializeLogging() { try { // initial logging config, used before anything else { final URL url = Main.class.getResource("log4j-initial.xml"); assert url != null; DOMConfigurator.configure(url); } if (ClassLoaderUtils.IS_WEB_START) { final URL url = Main.class.getResource("log4j-jnlp.xml"); assert url != null; println("Using JNLP log configuration: " + url); DOMConfigurator.configure(url); return true; } final File dataCleanerHome = DataCleanerHome.getAsFile(); if (initializeLoggingFromDirectory(dataCleanerHome)) { return true; } if (initializeLoggingFromDirectory(new File("."))) { return true; } // fall back to default log4j.xml file in classpath final URL url = Main.class.getResource("log4j-default.xml"); assert url != null; println("Using default log configuration: " + url); DOMConfigurator.configure(url); return false; } catch (final NoClassDefFoundError e) { // can happen if log4j is not on the classpath println("Failed to initialize logging, class not found: " + e.getMessage()); return false; } }
[ "protected", "static", "boolean", "initializeLogging", "(", ")", "{", "try", "{", "// initial logging config, used before anything else", "{", "final", "URL", "url", "=", "Main", ".", "class", ".", "getResource", "(", "\"log4j-initial.xml\"", ")", ";", "assert", "url", "!=", "null", ";", "DOMConfigurator", ".", "configure", "(", "url", ")", ";", "}", "if", "(", "ClassLoaderUtils", ".", "IS_WEB_START", ")", "{", "final", "URL", "url", "=", "Main", ".", "class", ".", "getResource", "(", "\"log4j-jnlp.xml\"", ")", ";", "assert", "url", "!=", "null", ";", "println", "(", "\"Using JNLP log configuration: \"", "+", "url", ")", ";", "DOMConfigurator", ".", "configure", "(", "url", ")", ";", "return", "true", ";", "}", "final", "File", "dataCleanerHome", "=", "DataCleanerHome", ".", "getAsFile", "(", ")", ";", "if", "(", "initializeLoggingFromDirectory", "(", "dataCleanerHome", ")", ")", "{", "return", "true", ";", "}", "if", "(", "initializeLoggingFromDirectory", "(", "new", "File", "(", "\".\"", ")", ")", ")", "{", "return", "true", ";", "}", "// fall back to default log4j.xml file in classpath", "final", "URL", "url", "=", "Main", ".", "class", ".", "getResource", "(", "\"log4j-default.xml\"", ")", ";", "assert", "url", "!=", "null", ";", "println", "(", "\"Using default log configuration: \"", "+", "url", ")", ";", "DOMConfigurator", ".", "configure", "(", "url", ")", ";", "return", "false", ";", "}", "catch", "(", "final", "NoClassDefFoundError", "e", ")", "{", "// can happen if log4j is not on the classpath", "println", "(", "\"Failed to initialize logging, class not found: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "}" ]
Initializes logging, specifically by looking for log4j.xml or log4j.properties file in DataCleaner's home directory. @return true if a logging configuration file was found, or false otherwise
[ "Initializes", "logging", "specifically", "by", "looking", "for", "log4j", ".", "xml", "or", "log4j", ".", "properties", "file", "in", "DataCleaner", "s", "home", "directory", "." ]
train
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/Main.java#L73-L112
alkacon/opencms-core
src/org/opencms/workplace/galleries/A_CmsAjaxGallery.java
A_CmsAjaxGallery.buildJsonItemObject
protected JSONObject buildJsonItemObject(CmsResource res) { """ Returns a JSON object containing information of the given resource for usage in the gallery.<p> The content of the JSON object consists of a common and a specific part of the given resource.<p> @param res the resource to create the object from @return the JSON object containing information from the given resource """ // create a new JSON object JSONObject jsonObj = new JSONObject(); String sitePath = getCms().getRequestContext().getSitePath(res); // fill JSON object with common information buildJsonItemCommonPart(jsonObj, res, sitePath); // fill JSON object with specific information buildJsonItemSpecificPart(jsonObj, res, sitePath); return jsonObj; }
java
protected JSONObject buildJsonItemObject(CmsResource res) { // create a new JSON object JSONObject jsonObj = new JSONObject(); String sitePath = getCms().getRequestContext().getSitePath(res); // fill JSON object with common information buildJsonItemCommonPart(jsonObj, res, sitePath); // fill JSON object with specific information buildJsonItemSpecificPart(jsonObj, res, sitePath); return jsonObj; }
[ "protected", "JSONObject", "buildJsonItemObject", "(", "CmsResource", "res", ")", "{", "// create a new JSON object", "JSONObject", "jsonObj", "=", "new", "JSONObject", "(", ")", ";", "String", "sitePath", "=", "getCms", "(", ")", ".", "getRequestContext", "(", ")", ".", "getSitePath", "(", "res", ")", ";", "// fill JSON object with common information", "buildJsonItemCommonPart", "(", "jsonObj", ",", "res", ",", "sitePath", ")", ";", "// fill JSON object with specific information", "buildJsonItemSpecificPart", "(", "jsonObj", ",", "res", ",", "sitePath", ")", ";", "return", "jsonObj", ";", "}" ]
Returns a JSON object containing information of the given resource for usage in the gallery.<p> The content of the JSON object consists of a common and a specific part of the given resource.<p> @param res the resource to create the object from @return the JSON object containing information from the given resource
[ "Returns", "a", "JSON", "object", "containing", "information", "of", "the", "given", "resource", "for", "usage", "in", "the", "gallery", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/galleries/A_CmsAjaxGallery.java#L977-L988
google/Accessibility-Test-Framework-for-Android
src/main/java/com/googlecode/eyesfree/utils/AccessibilityNodeInfoUtils.java
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor
public static AccessibilityNodeInfoCompat getSelfOrMatchingAncestor( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { """ Returns the {@code node} if it matches the {@code filter}, or the first matching ancestor. Returns {@code null} if no nodes match. """ if (node == null) { return null; } if (filter.accept(context, node)) { return AccessibilityNodeInfoCompat.obtain(node); } return getMatchingAncestor(context, node, filter); }
java
public static AccessibilityNodeInfoCompat getSelfOrMatchingAncestor( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return null; } if (filter.accept(context, node)) { return AccessibilityNodeInfoCompat.obtain(node); } return getMatchingAncestor(context, node, filter); }
[ "public", "static", "AccessibilityNodeInfoCompat", "getSelfOrMatchingAncestor", "(", "Context", "context", ",", "AccessibilityNodeInfoCompat", "node", ",", "NodeFilter", "filter", ")", "{", "if", "(", "node", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "filter", ".", "accept", "(", "context", ",", "node", ")", ")", "{", "return", "AccessibilityNodeInfoCompat", ".", "obtain", "(", "node", ")", ";", "}", "return", "getMatchingAncestor", "(", "context", ",", "node", ",", "filter", ")", ";", "}" ]
Returns the {@code node} if it matches the {@code filter}, or the first matching ancestor. Returns {@code null} if no nodes match.
[ "Returns", "the", "{" ]
train
https://github.com/google/Accessibility-Test-Framework-for-Android/blob/a6117fe0059c82dd764fa628d3817d724570f69e/src/main/java/com/googlecode/eyesfree/utils/AccessibilityNodeInfoUtils.java#L424-L435
ThreeTen/threetenbp
src/main/java/org/threeten/bp/Period.java
Period.plusMonths
public Period plusMonths(long monthsToAdd) { """ Returns a copy of this period with the specified months added. <p> This adds the amount to the months unit in a copy of this period. The years and days units are unaffected. For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days". <p> This instance is immutable and unaffected by this method call. @param monthsToAdd the months to add, positive or negative @return a {@code Period} based on this period with the specified months added, not null @throws ArithmeticException if numeric overflow occurs """ if (monthsToAdd == 0) { return this; } return create(years, Jdk8Methods.safeToInt(Jdk8Methods.safeAdd(months, monthsToAdd)), days); }
java
public Period plusMonths(long monthsToAdd) { if (monthsToAdd == 0) { return this; } return create(years, Jdk8Methods.safeToInt(Jdk8Methods.safeAdd(months, monthsToAdd)), days); }
[ "public", "Period", "plusMonths", "(", "long", "monthsToAdd", ")", "{", "if", "(", "monthsToAdd", "==", "0", ")", "{", "return", "this", ";", "}", "return", "create", "(", "years", ",", "Jdk8Methods", ".", "safeToInt", "(", "Jdk8Methods", ".", "safeAdd", "(", "months", ",", "monthsToAdd", ")", ")", ",", "days", ")", ";", "}" ]
Returns a copy of this period with the specified months added. <p> This adds the amount to the months unit in a copy of this period. The years and days units are unaffected. For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days". <p> This instance is immutable and unaffected by this method call. @param monthsToAdd the months to add, positive or negative @return a {@code Period} based on this period with the specified months added, not null @throws ArithmeticException if numeric overflow occurs
[ "Returns", "a", "copy", "of", "this", "period", "with", "the", "specified", "months", "added", ".", "<p", ">", "This", "adds", "the", "amount", "to", "the", "months", "unit", "in", "a", "copy", "of", "this", "period", ".", "The", "years", "and", "days", "units", "are", "unaffected", ".", "For", "example", "1", "year", "6", "months", "and", "3", "days", "plus", "2", "months", "returns", "1", "year", "8", "months", "and", "3", "days", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "call", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/Period.java#L589-L594
alkacon/opencms-core
src/org/opencms/ui/components/CmsBasicDialog.java
CmsBasicDialog.createResourceListPanel
protected Panel createResourceListPanel(String caption, List<CmsResource> resources) { """ Creates a resource list panel.<p> @param caption the caption to use @param resources the resources @return the panel """ Panel result = null; if (CmsStringUtil.isEmptyOrWhitespaceOnly(caption)) { result = new Panel(); } else { result = new Panel(caption); } result.addStyleName("v-scrollable"); result.setSizeFull(); VerticalLayout resourcePanel = new VerticalLayout(); result.setContent(resourcePanel); resourcePanel.addStyleName(OpenCmsTheme.REDUCED_MARGIN); resourcePanel.addStyleName(OpenCmsTheme.REDUCED_SPACING); resourcePanel.setSpacing(true); resourcePanel.setMargin(true); for (CmsResource resource : resources) { resourcePanel.addComponent(new CmsResourceInfo(resource)); } return result; }
java
protected Panel createResourceListPanel(String caption, List<CmsResource> resources) { Panel result = null; if (CmsStringUtil.isEmptyOrWhitespaceOnly(caption)) { result = new Panel(); } else { result = new Panel(caption); } result.addStyleName("v-scrollable"); result.setSizeFull(); VerticalLayout resourcePanel = new VerticalLayout(); result.setContent(resourcePanel); resourcePanel.addStyleName(OpenCmsTheme.REDUCED_MARGIN); resourcePanel.addStyleName(OpenCmsTheme.REDUCED_SPACING); resourcePanel.setSpacing(true); resourcePanel.setMargin(true); for (CmsResource resource : resources) { resourcePanel.addComponent(new CmsResourceInfo(resource)); } return result; }
[ "protected", "Panel", "createResourceListPanel", "(", "String", "caption", ",", "List", "<", "CmsResource", ">", "resources", ")", "{", "Panel", "result", "=", "null", ";", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "caption", ")", ")", "{", "result", "=", "new", "Panel", "(", ")", ";", "}", "else", "{", "result", "=", "new", "Panel", "(", "caption", ")", ";", "}", "result", ".", "addStyleName", "(", "\"v-scrollable\"", ")", ";", "result", ".", "setSizeFull", "(", ")", ";", "VerticalLayout", "resourcePanel", "=", "new", "VerticalLayout", "(", ")", ";", "result", ".", "setContent", "(", "resourcePanel", ")", ";", "resourcePanel", ".", "addStyleName", "(", "OpenCmsTheme", ".", "REDUCED_MARGIN", ")", ";", "resourcePanel", ".", "addStyleName", "(", "OpenCmsTheme", ".", "REDUCED_SPACING", ")", ";", "resourcePanel", ".", "setSpacing", "(", "true", ")", ";", "resourcePanel", ".", "setMargin", "(", "true", ")", ";", "for", "(", "CmsResource", "resource", ":", "resources", ")", "{", "resourcePanel", ".", "addComponent", "(", "new", "CmsResourceInfo", "(", "resource", ")", ")", ";", "}", "return", "result", ";", "}" ]
Creates a resource list panel.<p> @param caption the caption to use @param resources the resources @return the panel
[ "Creates", "a", "resource", "list", "panel", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsBasicDialog.java#L514-L534
santhosh-tekuri/jlibs
swing/src/main/java/jlibs/swing/SwingUtil.java
SwingUtil.doAction
public static void doAction(JTextField textField) { """ Programmatically perform action on textfield.This does the same thing as if the user had pressed enter key in textfield. @param textField textField on which action to be preformed """ String command = null; if(textField.getAction()!=null) command = (String)textField.getAction().getValue(Action.ACTION_COMMAND_KEY); ActionEvent event = null; for(ActionListener listener: textField.getActionListeners()){ if(event==null) event = new ActionEvent(textField, ActionEvent.ACTION_PERFORMED, command, System.currentTimeMillis(), 0); listener.actionPerformed(event); } }
java
public static void doAction(JTextField textField){ String command = null; if(textField.getAction()!=null) command = (String)textField.getAction().getValue(Action.ACTION_COMMAND_KEY); ActionEvent event = null; for(ActionListener listener: textField.getActionListeners()){ if(event==null) event = new ActionEvent(textField, ActionEvent.ACTION_PERFORMED, command, System.currentTimeMillis(), 0); listener.actionPerformed(event); } }
[ "public", "static", "void", "doAction", "(", "JTextField", "textField", ")", "{", "String", "command", "=", "null", ";", "if", "(", "textField", ".", "getAction", "(", ")", "!=", "null", ")", "command", "=", "(", "String", ")", "textField", ".", "getAction", "(", ")", ".", "getValue", "(", "Action", ".", "ACTION_COMMAND_KEY", ")", ";", "ActionEvent", "event", "=", "null", ";", "for", "(", "ActionListener", "listener", ":", "textField", ".", "getActionListeners", "(", ")", ")", "{", "if", "(", "event", "==", "null", ")", "event", "=", "new", "ActionEvent", "(", "textField", ",", "ActionEvent", ".", "ACTION_PERFORMED", ",", "command", ",", "System", ".", "currentTimeMillis", "(", ")", ",", "0", ")", ";", "listener", ".", "actionPerformed", "(", "event", ")", ";", "}", "}" ]
Programmatically perform action on textfield.This does the same thing as if the user had pressed enter key in textfield. @param textField textField on which action to be preformed
[ "Programmatically", "perform", "action", "on", "textfield", ".", "This", "does", "the", "same", "thing", "as", "if", "the", "user", "had", "pressed", "enter", "key", "in", "textfield", "." ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/swing/src/main/java/jlibs/swing/SwingUtil.java#L56-L67
aws/aws-sdk-java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/InputTemplate.java
InputTemplate.withCaptionSelectors
public InputTemplate withCaptionSelectors(java.util.Map<String, CaptionSelector> captionSelectors) { """ Use Captions selectors (CaptionSelectors) to specify the captions data from the input that you will use in your outputs. You can use mutiple captions selectors per input. @param captionSelectors Use Captions selectors (CaptionSelectors) to specify the captions data from the input that you will use in your outputs. You can use mutiple captions selectors per input. @return Returns a reference to this object so that method calls can be chained together. """ setCaptionSelectors(captionSelectors); return this; }
java
public InputTemplate withCaptionSelectors(java.util.Map<String, CaptionSelector> captionSelectors) { setCaptionSelectors(captionSelectors); return this; }
[ "public", "InputTemplate", "withCaptionSelectors", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "CaptionSelector", ">", "captionSelectors", ")", "{", "setCaptionSelectors", "(", "captionSelectors", ")", ";", "return", "this", ";", "}" ]
Use Captions selectors (CaptionSelectors) to specify the captions data from the input that you will use in your outputs. You can use mutiple captions selectors per input. @param captionSelectors Use Captions selectors (CaptionSelectors) to specify the captions data from the input that you will use in your outputs. You can use mutiple captions selectors per input. @return Returns a reference to this object so that method calls can be chained together.
[ "Use", "Captions", "selectors", "(", "CaptionSelectors", ")", "to", "specify", "the", "captions", "data", "from", "the", "input", "that", "you", "will", "use", "in", "your", "outputs", ".", "You", "can", "use", "mutiple", "captions", "selectors", "per", "input", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/InputTemplate.java#L259-L262
codescape/bitvunit
bitvunit-core/src/main/java/de/codescape/bitvunit/util/io/ClassPathResource.java
ClassPathResource.asString
private String asString() { """ Returns a {@link String} that contains the content of the file. @return {@link String} that contains the content of the file """ try { return IOUtils.toString(asInputStream()); } catch (IOException e) { throw new RuntimeException("Could not read from file '" + path + "'.", e); } }
java
private String asString() { try { return IOUtils.toString(asInputStream()); } catch (IOException e) { throw new RuntimeException("Could not read from file '" + path + "'.", e); } }
[ "private", "String", "asString", "(", ")", "{", "try", "{", "return", "IOUtils", ".", "toString", "(", "asInputStream", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not read from file '\"", "+", "path", "+", "\"'.\"", ",", "e", ")", ";", "}", "}" ]
Returns a {@link String} that contains the content of the file. @return {@link String} that contains the content of the file
[ "Returns", "a", "{", "@link", "String", "}", "that", "contains", "the", "content", "of", "the", "file", "." ]
train
https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/util/io/ClassPathResource.java#L71-L77
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listPreparationAndReleaseTaskStatusWithServiceResponseAsync
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> listPreparationAndReleaseTaskStatusWithServiceResponseAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions) { """ Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run. This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified. @param jobId The ID of the job. @param jobListPreparationAndReleaseTaskStatusOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobPreparationAndReleaseTaskExecutionInformation&gt; object """ return listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions) .concatMap(new Func1<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return Observable.just(page).concatWith(listPreparationAndReleaseTaskStatusNextWithServiceResponseAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions)); } }); }
java
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> listPreparationAndReleaseTaskStatusWithServiceResponseAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions) { return listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions) .concatMap(new Func1<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return Observable.just(page).concatWith(listPreparationAndReleaseTaskStatusNextWithServiceResponseAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions)); } }); }
[ "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", ">", "listPreparationAndReleaseTaskStatusWithServiceResponseAsync", "(", "final", "String", "jobId", ",", "final", "JobListPreparationAndReleaseTaskStatusOptions", "jobListPreparationAndReleaseTaskStatusOptions", ")", "{", "return", "listPreparationAndReleaseTaskStatusSinglePageAsync", "(", "jobId", ",", "jobListPreparationAndReleaseTaskStatusOptions", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", ",", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", ">", "call", "(", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "JobListPreparationAndReleaseTaskStatusNextOptions", "jobListPreparationAndReleaseTaskStatusNextOptions", "=", "null", ";", "if", "(", "jobListPreparationAndReleaseTaskStatusOptions", "!=", "null", ")", "{", "jobListPreparationAndReleaseTaskStatusNextOptions", "=", "new", "JobListPreparationAndReleaseTaskStatusNextOptions", "(", ")", ";", "jobListPreparationAndReleaseTaskStatusNextOptions", ".", "withClientRequestId", "(", "jobListPreparationAndReleaseTaskStatusOptions", ".", "clientRequestId", "(", ")", ")", ";", "jobListPreparationAndReleaseTaskStatusNextOptions", ".", "withReturnClientRequestId", "(", "jobListPreparationAndReleaseTaskStatusOptions", ".", "returnClientRequestId", "(", ")", ")", ";", "jobListPreparationAndReleaseTaskStatusNextOptions", ".", "withOcpDate", "(", "jobListPreparationAndReleaseTaskStatusOptions", ".", "ocpDate", "(", ")", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listPreparationAndReleaseTaskStatusNextWithServiceResponseAsync", "(", "nextPageLink", ",", "jobListPreparationAndReleaseTaskStatusNextOptions", ")", ")", ";", "}", "}", ")", ";", "}" ]
Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run. This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified. @param jobId The ID of the job. @param jobListPreparationAndReleaseTaskStatusOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobPreparationAndReleaseTaskExecutionInformation&gt; object
[ "Lists", "the", "execution", "status", "of", "the", "Job", "Preparation", "and", "Job", "Release", "task", "for", "the", "specified", "job", "across", "the", "compute", "nodes", "where", "the", "job", "has", "run", ".", "This", "API", "returns", "the", "Job", "Preparation", "and", "Job", "Release", "task", "status", "on", "all", "compute", "nodes", "that", "have", "run", "the", "Job", "Preparation", "or", "Job", "Release", "task", ".", "This", "includes", "nodes", "which", "have", "since", "been", "removed", "from", "the", "pool", ".", "If", "this", "API", "is", "invoked", "on", "a", "job", "which", "has", "no", "Job", "Preparation", "or", "Job", "Release", "task", "the", "Batch", "service", "returns", "HTTP", "status", "code", "409", "(", "Conflict", ")", "with", "an", "error", "code", "of", "JobPreparationTaskNotSpecified", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L3015-L3034
Stratio/bdt
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
DatabaseSpec.createTableWithData
@Given("^I create a Cassandra table named '(.+?)' using keyspace '(.+?)' with:$") public void createTableWithData(String table, String keyspace, DataTable datatable) { """ Create table @param table Cassandra table @param datatable datatable used for parsing elements @param keyspace Cassandra keyspace """ try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getPickleRows().get(0).getCells().size(); Map<String, String> columns = new HashMap<String, String>(); ArrayList<String> pk = new ArrayList<String>(); for (int i = 0; i < attrLength; i++) { columns.put(datatable.getPickleRows().get(0).getCells().get(i).getValue(), datatable.getPickleRows().get(1).getCells().get(i).getValue()); if ((datatable.getPickleRows().size() == 3) && datatable.getPickleRows().get(2).getCells().get(i).getValue().equalsIgnoreCase("PK")) { pk.add(datatable.getPickleRows().get(0).getCells().get(i).getValue()); } } if (pk.isEmpty()) { throw new Exception("A PK is needed"); } commonspec.getCassandraClient().createTableWithData(table, columns, pk); } catch (Exception e) { commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } }
java
@Given("^I create a Cassandra table named '(.+?)' using keyspace '(.+?)' with:$") public void createTableWithData(String table, String keyspace, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getPickleRows().get(0).getCells().size(); Map<String, String> columns = new HashMap<String, String>(); ArrayList<String> pk = new ArrayList<String>(); for (int i = 0; i < attrLength; i++) { columns.put(datatable.getPickleRows().get(0).getCells().get(i).getValue(), datatable.getPickleRows().get(1).getCells().get(i).getValue()); if ((datatable.getPickleRows().size() == 3) && datatable.getPickleRows().get(2).getCells().get(i).getValue().equalsIgnoreCase("PK")) { pk.add(datatable.getPickleRows().get(0).getCells().get(i).getValue()); } } if (pk.isEmpty()) { throw new Exception("A PK is needed"); } commonspec.getCassandraClient().createTableWithData(table, columns, pk); } catch (Exception e) { commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } }
[ "@", "Given", "(", "\"^I create a Cassandra table named '(.+?)' using keyspace '(.+?)' with:$\"", ")", "public", "void", "createTableWithData", "(", "String", "table", ",", "String", "keyspace", ",", "DataTable", "datatable", ")", "{", "try", "{", "commonspec", ".", "getCassandraClient", "(", ")", ".", "useKeyspace", "(", "keyspace", ")", ";", "int", "attrLength", "=", "datatable", ".", "getPickleRows", "(", ")", ".", "get", "(", "0", ")", ".", "getCells", "(", ")", ".", "size", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "columns", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "ArrayList", "<", "String", ">", "pk", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "attrLength", ";", "i", "++", ")", "{", "columns", ".", "put", "(", "datatable", ".", "getPickleRows", "(", ")", ".", "get", "(", "0", ")", ".", "getCells", "(", ")", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ",", "datatable", ".", "getPickleRows", "(", ")", ".", "get", "(", "1", ")", ".", "getCells", "(", ")", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "if", "(", "(", "datatable", ".", "getPickleRows", "(", ")", ".", "size", "(", ")", "==", "3", ")", "&&", "datatable", ".", "getPickleRows", "(", ")", ".", "get", "(", "2", ")", ".", "getCells", "(", ")", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ".", "equalsIgnoreCase", "(", "\"PK\"", ")", ")", "{", "pk", ".", "add", "(", "datatable", ".", "getPickleRows", "(", ")", ".", "get", "(", "0", ")", ".", "getCells", "(", ")", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", "if", "(", "pk", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"A PK is needed\"", ")", ";", "}", "commonspec", ".", "getCassandraClient", "(", ")", ".", "createTableWithData", "(", "table", ",", "columns", ",", "pk", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "commonspec", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Exception captured\"", ")", ";", "commonspec", ".", "getLogger", "(", ")", ".", "debug", "(", "e", ".", "toString", "(", ")", ")", ";", "commonspec", ".", "getExceptions", "(", ")", ".", "add", "(", "e", ")", ";", "}", "}" ]
Create table @param table Cassandra table @param datatable datatable used for parsing elements @param keyspace Cassandra keyspace
[ "Create", "table" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L160-L184
jayantk/jklol
src/com/jayantkrish/jklol/cfg/CfgParseTree.java
CfgParseTree.multiplyProbability
public CfgParseTree multiplyProbability(double amount) { """ Gets a new parse tree equivalent to this one, with probability {@code this.probability * amount}. @param amount @return """ if (isTerminal()) { return new CfgParseTree(root, ruleType, terminal, getProbability() * amount, spanStart, spanEnd); } else { return new CfgParseTree(root, ruleType, left, right, getProbability() * amount); } }
java
public CfgParseTree multiplyProbability(double amount) { if (isTerminal()) { return new CfgParseTree(root, ruleType, terminal, getProbability() * amount, spanStart, spanEnd); } else { return new CfgParseTree(root, ruleType, left, right, getProbability() * amount); } }
[ "public", "CfgParseTree", "multiplyProbability", "(", "double", "amount", ")", "{", "if", "(", "isTerminal", "(", ")", ")", "{", "return", "new", "CfgParseTree", "(", "root", ",", "ruleType", ",", "terminal", ",", "getProbability", "(", ")", "*", "amount", ",", "spanStart", ",", "spanEnd", ")", ";", "}", "else", "{", "return", "new", "CfgParseTree", "(", "root", ",", "ruleType", ",", "left", ",", "right", ",", "getProbability", "(", ")", "*", "amount", ")", ";", "}", "}" ]
Gets a new parse tree equivalent to this one, with probability {@code this.probability * amount}. @param amount @return
[ "Gets", "a", "new", "parse", "tree", "equivalent", "to", "this", "one", "with", "probability", "{", "@code", "this", ".", "probability", "*", "amount", "}", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/cfg/CfgParseTree.java#L116-L122
apache/reef
lang/java/reef-io/src/main/java/org/apache/reef/io/network/group/impl/driver/TaskNodeStatusImpl.java
TaskNodeStatusImpl.expectAckFor
@Override public void expectAckFor(final Type msgType, final String srcId) { """ This needs to happen in line rather than in a stage because we need to note. the messages we send to the tasks before we start processing msgs from the nodes.(Acks and Topology msgs) """ LOG.entering("TaskNodeStatusImpl", "expectAckFor", new Object[]{getQualifiedName(), msgType, srcId}); LOG.finest(getQualifiedName() + "Adding " + srcId + " to sources"); statusMap.add(msgType, srcId); LOG.exiting("TaskNodeStatusImpl", "expectAckFor", getQualifiedName() + "Sources from which ACKs for " + msgType + " are expected: " + statusMap.get(msgType)); }
java
@Override public void expectAckFor(final Type msgType, final String srcId) { LOG.entering("TaskNodeStatusImpl", "expectAckFor", new Object[]{getQualifiedName(), msgType, srcId}); LOG.finest(getQualifiedName() + "Adding " + srcId + " to sources"); statusMap.add(msgType, srcId); LOG.exiting("TaskNodeStatusImpl", "expectAckFor", getQualifiedName() + "Sources from which ACKs for " + msgType + " are expected: " + statusMap.get(msgType)); }
[ "@", "Override", "public", "void", "expectAckFor", "(", "final", "Type", "msgType", ",", "final", "String", "srcId", ")", "{", "LOG", ".", "entering", "(", "\"TaskNodeStatusImpl\"", ",", "\"expectAckFor\"", ",", "new", "Object", "[", "]", "{", "getQualifiedName", "(", ")", ",", "msgType", ",", "srcId", "}", ")", ";", "LOG", ".", "finest", "(", "getQualifiedName", "(", ")", "+", "\"Adding \"", "+", "srcId", "+", "\" to sources\"", ")", ";", "statusMap", ".", "add", "(", "msgType", ",", "srcId", ")", ";", "LOG", ".", "exiting", "(", "\"TaskNodeStatusImpl\"", ",", "\"expectAckFor\"", ",", "getQualifiedName", "(", ")", "+", "\"Sources from which ACKs for \"", "+", "msgType", "+", "\" are expected: \"", "+", "statusMap", ".", "get", "(", "msgType", ")", ")", ";", "}" ]
This needs to happen in line rather than in a stage because we need to note. the messages we send to the tasks before we start processing msgs from the nodes.(Acks and Topology msgs)
[ "This", "needs", "to", "happen", "in", "line", "rather", "than", "in", "a", "stage", "because", "we", "need", "to", "note", ".", "the", "messages", "we", "send", "to", "the", "tasks", "before", "we", "start", "processing", "msgs", "from", "the", "nodes", ".", "(", "Acks", "and", "Topology", "msgs", ")" ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-io/src/main/java/org/apache/reef/io/network/group/impl/driver/TaskNodeStatusImpl.java#L115-L122
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java
VirtualMachinesInner.beginRunCommandAsync
public Observable<RunCommandResultInner> beginRunCommandAsync(String resourceGroupName, String vmName, RunCommandInput parameters) { """ Run command on the VM. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @param parameters Parameters supplied to the Run command operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RunCommandResultInner object """ return beginRunCommandWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<RunCommandResultInner>, RunCommandResultInner>() { @Override public RunCommandResultInner call(ServiceResponse<RunCommandResultInner> response) { return response.body(); } }); }
java
public Observable<RunCommandResultInner> beginRunCommandAsync(String resourceGroupName, String vmName, RunCommandInput parameters) { return beginRunCommandWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<RunCommandResultInner>, RunCommandResultInner>() { @Override public RunCommandResultInner call(ServiceResponse<RunCommandResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RunCommandResultInner", ">", "beginRunCommandAsync", "(", "String", "resourceGroupName", ",", "String", "vmName", ",", "RunCommandInput", "parameters", ")", "{", "return", "beginRunCommandWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RunCommandResultInner", ">", ",", "RunCommandResultInner", ">", "(", ")", "{", "@", "Override", "public", "RunCommandResultInner", "call", "(", "ServiceResponse", "<", "RunCommandResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Run command on the VM. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @param parameters Parameters supplied to the Run command operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RunCommandResultInner object
[ "Run", "command", "on", "the", "VM", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java#L2730-L2737
alkacon/opencms-core
src/org/opencms/workflow/CmsExtendedWorkflowManager.java
CmsExtendedWorkflowManager.actionRelease
protected CmsWorkflowResponse actionRelease(CmsObject userCms, List<CmsResource> resources) throws CmsException { """ Implementation of the 'release' workflow action.<p> @param userCms the current user's CMS context @param resources the resources which should be released @return the workflow response for this action @throws CmsException if something goes wrong """ checkNewParentsInList(userCms, resources); String projectName = generateProjectName(userCms); String projectDescription = generateProjectDescription(userCms); CmsObject offlineAdminCms = OpenCms.initCmsObject(m_adminCms); offlineAdminCms.getRequestContext().setCurrentProject(userCms.getRequestContext().getCurrentProject()); String managerGroup = getWorkflowProjectManagerGroup(); String userGroup = getWorkflowProjectUserGroup(); CmsProject workflowProject = m_adminCms.createProject( projectName, projectDescription, userGroup, managerGroup, CmsProject.PROJECT_TYPE_WORKFLOW); CmsObject newProjectCms = OpenCms.initCmsObject(offlineAdminCms); newProjectCms.getRequestContext().setCurrentProject(workflowProject); newProjectCms.getRequestContext().setSiteRoot(""); newProjectCms.copyResourceToProject("/"); CmsUser admin = offlineAdminCms.getRequestContext().getCurrentUser(); clearLocks(userCms.getRequestContext().getCurrentProject(), resources); for (CmsResource resource : resources) { CmsLock lock = offlineAdminCms.getLock(resource); if (lock.isUnlocked()) { offlineAdminCms.lockResource(resource); } else if (!lock.isOwnedBy(admin)) { offlineAdminCms.changeLock(resource); } offlineAdminCms.writeProjectLastModified(resource, workflowProject); offlineAdminCms.unlockResource(resource); } for (CmsUser user : getNotificationMailRecipients()) { sendNotification(userCms, user, workflowProject, resources); } return new CmsWorkflowResponse( true, "", new ArrayList<CmsPublishResource>(), new ArrayList<CmsWorkflowAction>(), workflowProject.getUuid()); }
java
protected CmsWorkflowResponse actionRelease(CmsObject userCms, List<CmsResource> resources) throws CmsException { checkNewParentsInList(userCms, resources); String projectName = generateProjectName(userCms); String projectDescription = generateProjectDescription(userCms); CmsObject offlineAdminCms = OpenCms.initCmsObject(m_adminCms); offlineAdminCms.getRequestContext().setCurrentProject(userCms.getRequestContext().getCurrentProject()); String managerGroup = getWorkflowProjectManagerGroup(); String userGroup = getWorkflowProjectUserGroup(); CmsProject workflowProject = m_adminCms.createProject( projectName, projectDescription, userGroup, managerGroup, CmsProject.PROJECT_TYPE_WORKFLOW); CmsObject newProjectCms = OpenCms.initCmsObject(offlineAdminCms); newProjectCms.getRequestContext().setCurrentProject(workflowProject); newProjectCms.getRequestContext().setSiteRoot(""); newProjectCms.copyResourceToProject("/"); CmsUser admin = offlineAdminCms.getRequestContext().getCurrentUser(); clearLocks(userCms.getRequestContext().getCurrentProject(), resources); for (CmsResource resource : resources) { CmsLock lock = offlineAdminCms.getLock(resource); if (lock.isUnlocked()) { offlineAdminCms.lockResource(resource); } else if (!lock.isOwnedBy(admin)) { offlineAdminCms.changeLock(resource); } offlineAdminCms.writeProjectLastModified(resource, workflowProject); offlineAdminCms.unlockResource(resource); } for (CmsUser user : getNotificationMailRecipients()) { sendNotification(userCms, user, workflowProject, resources); } return new CmsWorkflowResponse( true, "", new ArrayList<CmsPublishResource>(), new ArrayList<CmsWorkflowAction>(), workflowProject.getUuid()); }
[ "protected", "CmsWorkflowResponse", "actionRelease", "(", "CmsObject", "userCms", ",", "List", "<", "CmsResource", ">", "resources", ")", "throws", "CmsException", "{", "checkNewParentsInList", "(", "userCms", ",", "resources", ")", ";", "String", "projectName", "=", "generateProjectName", "(", "userCms", ")", ";", "String", "projectDescription", "=", "generateProjectDescription", "(", "userCms", ")", ";", "CmsObject", "offlineAdminCms", "=", "OpenCms", ".", "initCmsObject", "(", "m_adminCms", ")", ";", "offlineAdminCms", ".", "getRequestContext", "(", ")", ".", "setCurrentProject", "(", "userCms", ".", "getRequestContext", "(", ")", ".", "getCurrentProject", "(", ")", ")", ";", "String", "managerGroup", "=", "getWorkflowProjectManagerGroup", "(", ")", ";", "String", "userGroup", "=", "getWorkflowProjectUserGroup", "(", ")", ";", "CmsProject", "workflowProject", "=", "m_adminCms", ".", "createProject", "(", "projectName", ",", "projectDescription", ",", "userGroup", ",", "managerGroup", ",", "CmsProject", ".", "PROJECT_TYPE_WORKFLOW", ")", ";", "CmsObject", "newProjectCms", "=", "OpenCms", ".", "initCmsObject", "(", "offlineAdminCms", ")", ";", "newProjectCms", ".", "getRequestContext", "(", ")", ".", "setCurrentProject", "(", "workflowProject", ")", ";", "newProjectCms", ".", "getRequestContext", "(", ")", ".", "setSiteRoot", "(", "\"\"", ")", ";", "newProjectCms", ".", "copyResourceToProject", "(", "\"/\"", ")", ";", "CmsUser", "admin", "=", "offlineAdminCms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ";", "clearLocks", "(", "userCms", ".", "getRequestContext", "(", ")", ".", "getCurrentProject", "(", ")", ",", "resources", ")", ";", "for", "(", "CmsResource", "resource", ":", "resources", ")", "{", "CmsLock", "lock", "=", "offlineAdminCms", ".", "getLock", "(", "resource", ")", ";", "if", "(", "lock", ".", "isUnlocked", "(", ")", ")", "{", "offlineAdminCms", ".", "lockResource", "(", "resource", ")", ";", "}", "else", "if", "(", "!", "lock", ".", "isOwnedBy", "(", "admin", ")", ")", "{", "offlineAdminCms", ".", "changeLock", "(", "resource", ")", ";", "}", "offlineAdminCms", ".", "writeProjectLastModified", "(", "resource", ",", "workflowProject", ")", ";", "offlineAdminCms", ".", "unlockResource", "(", "resource", ")", ";", "}", "for", "(", "CmsUser", "user", ":", "getNotificationMailRecipients", "(", ")", ")", "{", "sendNotification", "(", "userCms", ",", "user", ",", "workflowProject", ",", "resources", ")", ";", "}", "return", "new", "CmsWorkflowResponse", "(", "true", ",", "\"\"", ",", "new", "ArrayList", "<", "CmsPublishResource", ">", "(", ")", ",", "new", "ArrayList", "<", "CmsWorkflowAction", ">", "(", ")", ",", "workflowProject", ".", "getUuid", "(", ")", ")", ";", "}" ]
Implementation of the 'release' workflow action.<p> @param userCms the current user's CMS context @param resources the resources which should be released @return the workflow response for this action @throws CmsException if something goes wrong
[ "Implementation", "of", "the", "release", "workflow", "action", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workflow/CmsExtendedWorkflowManager.java#L318-L358
thorntail/thorntail
thorntail-runner/src/main/java/org/wildfly/swarm/runner/FatJarBuilder.java
FatJarBuilder.buildWar
private File buildWar(List<ArtifactOrFile> classPathEntries) { """ builds war with classes inside @param classPathEntries class path entries as ArtifactSpec or URLs @return the war file """ try { List<String> classesUrls = classPathEntries.stream() .map(ArtifactOrFile::file) .filter(this::isDirectory) .filter(url -> url.contains("classes")) .collect(Collectors.toList()); List<File> classpathJars = classPathEntries.stream() .map(ArtifactOrFile::file) .filter(file -> file.endsWith(".jar")) .map(File::new) .collect(Collectors.toList()); return WarBuilder.build(classesUrls, classpathJars); } catch (IOException e) { throw new RuntimeException("failed to build war", e); } }
java
private File buildWar(List<ArtifactOrFile> classPathEntries) { try { List<String> classesUrls = classPathEntries.stream() .map(ArtifactOrFile::file) .filter(this::isDirectory) .filter(url -> url.contains("classes")) .collect(Collectors.toList()); List<File> classpathJars = classPathEntries.stream() .map(ArtifactOrFile::file) .filter(file -> file.endsWith(".jar")) .map(File::new) .collect(Collectors.toList()); return WarBuilder.build(classesUrls, classpathJars); } catch (IOException e) { throw new RuntimeException("failed to build war", e); } }
[ "private", "File", "buildWar", "(", "List", "<", "ArtifactOrFile", ">", "classPathEntries", ")", "{", "try", "{", "List", "<", "String", ">", "classesUrls", "=", "classPathEntries", ".", "stream", "(", ")", ".", "map", "(", "ArtifactOrFile", "::", "file", ")", ".", "filter", "(", "this", "::", "isDirectory", ")", ".", "filter", "(", "url", "->", "url", ".", "contains", "(", "\"classes\"", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "List", "<", "File", ">", "classpathJars", "=", "classPathEntries", ".", "stream", "(", ")", ".", "map", "(", "ArtifactOrFile", "::", "file", ")", ".", "filter", "(", "file", "->", "file", ".", "endsWith", "(", "\".jar\"", ")", ")", ".", "map", "(", "File", "::", "new", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "return", "WarBuilder", ".", "build", "(", "classesUrls", ",", "classpathJars", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"failed to build war\"", ",", "e", ")", ";", "}", "}" ]
builds war with classes inside @param classPathEntries class path entries as ArtifactSpec or URLs @return the war file
[ "builds", "war", "with", "classes", "inside" ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/thorntail-runner/src/main/java/org/wildfly/swarm/runner/FatJarBuilder.java#L151-L169
zaproxy/zaproxy
src/org/parosproxy/paros/core/scanner/VariantAbstractQuery.java
VariantAbstractQuery.setParameters
protected void setParameters(int type, List<org.zaproxy.zap.model.NameValuePair> parameters) { """ Sets the given {@code parameters} of the given {@code type} as the list of parameters handled by this variant. <p> The names and values of the parameters are expected to be in decoded form. @param type the type of parameters @param parameters the actual parameters to add @throws IllegalArgumentException if {@code parameters} is {@code null}. @since 2.5.0 @see #getParamList() @see NameValuePair#TYPE_QUERY_STRING @see NameValuePair#TYPE_POST_DATA """ if (parameters == null) { throw new IllegalArgumentException("Parameter parameters must not be null."); } int size = parameters.isEmpty() ? 1 : parameters.size(); listParam = new ArrayList<>(size); originalNames = new ArrayList<>(size); Map<String, MutableInt> arraysMap = new HashMap<>(); int i = 0; for (org.zaproxy.zap.model.NameValuePair parameter : parameters) { String originalName = nonNullString(parameter.getName()); originalNames.add(originalName); String name = isParamArray(originalName) ? getArrayName(originalName, arraysMap) : originalName; listParam.add(new NameValuePair(type, name, nonNullString(parameter.getValue()), i)); i++; } if (i == 0 && addQueryParam) { String param = "query"; // No query params, lets add one just to make sure listParam.add(new NameValuePair(type, param, param, i)); originalNames.add(param); } }
java
protected void setParameters(int type, List<org.zaproxy.zap.model.NameValuePair> parameters) { if (parameters == null) { throw new IllegalArgumentException("Parameter parameters must not be null."); } int size = parameters.isEmpty() ? 1 : parameters.size(); listParam = new ArrayList<>(size); originalNames = new ArrayList<>(size); Map<String, MutableInt> arraysMap = new HashMap<>(); int i = 0; for (org.zaproxy.zap.model.NameValuePair parameter : parameters) { String originalName = nonNullString(parameter.getName()); originalNames.add(originalName); String name = isParamArray(originalName) ? getArrayName(originalName, arraysMap) : originalName; listParam.add(new NameValuePair(type, name, nonNullString(parameter.getValue()), i)); i++; } if (i == 0 && addQueryParam) { String param = "query"; // No query params, lets add one just to make sure listParam.add(new NameValuePair(type, param, param, i)); originalNames.add(param); } }
[ "protected", "void", "setParameters", "(", "int", "type", ",", "List", "<", "org", ".", "zaproxy", ".", "zap", ".", "model", ".", "NameValuePair", ">", "parameters", ")", "{", "if", "(", "parameters", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter parameters must not be null.\"", ")", ";", "}", "int", "size", "=", "parameters", ".", "isEmpty", "(", ")", "?", "1", ":", "parameters", ".", "size", "(", ")", ";", "listParam", "=", "new", "ArrayList", "<>", "(", "size", ")", ";", "originalNames", "=", "new", "ArrayList", "<>", "(", "size", ")", ";", "Map", "<", "String", ",", "MutableInt", ">", "arraysMap", "=", "new", "HashMap", "<>", "(", ")", ";", "int", "i", "=", "0", ";", "for", "(", "org", ".", "zaproxy", ".", "zap", ".", "model", ".", "NameValuePair", "parameter", ":", "parameters", ")", "{", "String", "originalName", "=", "nonNullString", "(", "parameter", ".", "getName", "(", ")", ")", ";", "originalNames", ".", "add", "(", "originalName", ")", ";", "String", "name", "=", "isParamArray", "(", "originalName", ")", "?", "getArrayName", "(", "originalName", ",", "arraysMap", ")", ":", "originalName", ";", "listParam", ".", "add", "(", "new", "NameValuePair", "(", "type", ",", "name", ",", "nonNullString", "(", "parameter", ".", "getValue", "(", ")", ")", ",", "i", ")", ")", ";", "i", "++", ";", "}", "if", "(", "i", "==", "0", "&&", "addQueryParam", ")", "{", "String", "param", "=", "\"query\"", ";", "// No query params, lets add one just to make sure\r", "listParam", ".", "add", "(", "new", "NameValuePair", "(", "type", ",", "param", ",", "param", ",", "i", ")", ")", ";", "originalNames", ".", "add", "(", "param", ")", ";", "}", "}" ]
Sets the given {@code parameters} of the given {@code type} as the list of parameters handled by this variant. <p> The names and values of the parameters are expected to be in decoded form. @param type the type of parameters @param parameters the actual parameters to add @throws IllegalArgumentException if {@code parameters} is {@code null}. @since 2.5.0 @see #getParamList() @see NameValuePair#TYPE_QUERY_STRING @see NameValuePair#TYPE_POST_DATA
[ "Sets", "the", "given", "{", "@code", "parameters", "}", "of", "the", "given", "{", "@code", "type", "}", "as", "the", "list", "of", "parameters", "handled", "by", "this", "variant", ".", "<p", ">", "The", "names", "and", "values", "of", "the", "parameters", "are", "expected", "to", "be", "in", "decoded", "form", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/VariantAbstractQuery.java#L130-L154
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ShortExtensions.java
ShortExtensions.operator_tripleEquals
@Pure @Inline(value="($1 == $2)", constantExpression=true) public static boolean operator_tripleEquals(short a, long b) { """ The <code>identity equals</code> operator. This is the equivalent to Java's <code>==</code> operator. @param a a short. @param b a long. @return <code>a == b</code> @since 2.4 """ return a == b; }
java
@Pure @Inline(value="($1 == $2)", constantExpression=true) public static boolean operator_tripleEquals(short a, long b) { return a == b; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($1 == $2)\"", ",", "constantExpression", "=", "true", ")", "public", "static", "boolean", "operator_tripleEquals", "(", "short", "a", ",", "long", "b", ")", "{", "return", "a", "==", "b", ";", "}" ]
The <code>identity equals</code> operator. This is the equivalent to Java's <code>==</code> operator. @param a a short. @param b a long. @return <code>a == b</code> @since 2.4
[ "The", "<code", ">", "identity", "equals<", "/", "code", ">", "operator", ".", "This", "is", "the", "equivalent", "to", "Java", "s", "<code", ">", "==", "<", "/", "code", ">", "operator", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ShortExtensions.java#L654-L658
perwendel/spark
src/main/java/spark/TemplateViewRouteImpl.java
TemplateViewRouteImpl.create
public static TemplateViewRouteImpl create(String path, TemplateViewRoute route, TemplateEngine engine) { """ factory method @param path the path @param route the route @param engine the engine @return the wrapper template view route """ return create(path, Service.DEFAULT_ACCEPT_TYPE, route, engine); }
java
public static TemplateViewRouteImpl create(String path, TemplateViewRoute route, TemplateEngine engine) { return create(path, Service.DEFAULT_ACCEPT_TYPE, route, engine); }
[ "public", "static", "TemplateViewRouteImpl", "create", "(", "String", "path", ",", "TemplateViewRoute", "route", ",", "TemplateEngine", "engine", ")", "{", "return", "create", "(", "path", ",", "Service", ".", "DEFAULT_ACCEPT_TYPE", ",", "route", ",", "engine", ")", ";", "}" ]
factory method @param path the path @param route the route @param engine the engine @return the wrapper template view route
[ "factory", "method" ]
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/TemplateViewRouteImpl.java#L37-L42
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/JobConf.java
JobConf.overrideConfiguration
public static void overrideConfiguration(JobConf conf, int instance) { """ Replce the jobtracker configuration with the configuration of 0 or 1 instance. This allows switching two sets of configurations in the command line option. @param conf The jobConf to be overwritten @param instance 0 or 1 instance of the jobtracker """ final String CONFIG_KEYS[] = new String[]{"mapred.job.tracker", "mapred.local.dir", "mapred.fairscheduler.server.address"}; for (String configKey : CONFIG_KEYS) { String value = conf.get(configKey + "-" + instance); if (value != null) { conf.set(configKey, value); } else { LOG.warn("Configuration " + configKey + "-" + instance + " not found."); } } }
java
public static void overrideConfiguration(JobConf conf, int instance) { final String CONFIG_KEYS[] = new String[]{"mapred.job.tracker", "mapred.local.dir", "mapred.fairscheduler.server.address"}; for (String configKey : CONFIG_KEYS) { String value = conf.get(configKey + "-" + instance); if (value != null) { conf.set(configKey, value); } else { LOG.warn("Configuration " + configKey + "-" + instance + " not found."); } } }
[ "public", "static", "void", "overrideConfiguration", "(", "JobConf", "conf", ",", "int", "instance", ")", "{", "final", "String", "CONFIG_KEYS", "[", "]", "=", "new", "String", "[", "]", "{", "\"mapred.job.tracker\"", ",", "\"mapred.local.dir\"", ",", "\"mapred.fairscheduler.server.address\"", "}", ";", "for", "(", "String", "configKey", ":", "CONFIG_KEYS", ")", "{", "String", "value", "=", "conf", ".", "get", "(", "configKey", "+", "\"-\"", "+", "instance", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "conf", ".", "set", "(", "configKey", ",", "value", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"Configuration \"", "+", "configKey", "+", "\"-\"", "+", "instance", "+", "\" not found.\"", ")", ";", "}", "}", "}" ]
Replce the jobtracker configuration with the configuration of 0 or 1 instance. This allows switching two sets of configurations in the command line option. @param conf The jobConf to be overwritten @param instance 0 or 1 instance of the jobtracker
[ "Replce", "the", "jobtracker", "configuration", "with", "the", "configuration", "of", "0", "or", "1", "instance", ".", "This", "allows", "switching", "two", "sets", "of", "configurations", "in", "the", "command", "line", "option", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/JobConf.java#L2142-L2154
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java
ServiceDiscoveryManager.discoverItems
public DiscoverItems discoverItems(Jid entityID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { """ Returns the discovered items of a given XMPP entity addressed by its JID. @param entityID the address of the XMPP entity. @return the discovered information. @throws XMPPErrorException if the operation failed for some reason. @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException """ return discoverItems(entityID, null); }
java
public DiscoverItems discoverItems(Jid entityID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return discoverItems(entityID, null); }
[ "public", "DiscoverItems", "discoverItems", "(", "Jid", "entityID", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "discoverItems", "(", "entityID", ",", "null", ")", ";", "}" ]
Returns the discovered items of a given XMPP entity addressed by its JID. @param entityID the address of the XMPP entity. @return the discovered information. @throws XMPPErrorException if the operation failed for some reason. @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Returns", "the", "discovered", "items", "of", "a", "given", "XMPP", "entity", "addressed", "by", "its", "JID", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java#L546-L548
tvesalainen/util
util/src/main/java/org/vesalainen/util/InterfaceTracer.java
InterfaceTracer.getTracer
protected static <T> T getTracer(Class<T> intf, InterfaceTracer tracer, T ob, Appendable appendable) { """ Creates a tracer for intf. This is meant to be used by subclass. @param <T> @param intf Implemented interface @param ob Class instance for given interface or null @param appendable Output for trace @return """ tracer.setAppendable(appendable); tracer.setObj(ob); return (T) Proxy.newProxyInstance( intf.getClassLoader(), new Class<?>[] {intf}, tracer); }
java
protected static <T> T getTracer(Class<T> intf, InterfaceTracer tracer, T ob, Appendable appendable) { tracer.setAppendable(appendable); tracer.setObj(ob); return (T) Proxy.newProxyInstance( intf.getClassLoader(), new Class<?>[] {intf}, tracer); }
[ "protected", "static", "<", "T", ">", "T", "getTracer", "(", "Class", "<", "T", ">", "intf", ",", "InterfaceTracer", "tracer", ",", "T", "ob", ",", "Appendable", "appendable", ")", "{", "tracer", ".", "setAppendable", "(", "appendable", ")", ";", "tracer", ".", "setObj", "(", "ob", ")", ";", "return", "(", "T", ")", "Proxy", ".", "newProxyInstance", "(", "intf", ".", "getClassLoader", "(", ")", ",", "new", "Class", "<", "?", ">", "[", "]", "{", "intf", "}", ",", "tracer", ")", ";", "}" ]
Creates a tracer for intf. This is meant to be used by subclass. @param <T> @param intf Implemented interface @param ob Class instance for given interface or null @param appendable Output for trace @return
[ "Creates", "a", "tracer", "for", "intf", ".", "This", "is", "meant", "to", "be", "used", "by", "subclass", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/InterfaceTracer.java#L102-L110
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.pluralizeFormat
public static MessageFormat pluralizeFormat(final String template, final Locale locale) { """ <p> Same as {@link #pluralizeFormat(String)} for the specified locale. </p> @param template String of tokens delimited by '::' @param locale Target locale @return Message instance prepared to generate pluralized strings """ return withinLocale(new Callable<MessageFormat>() { public MessageFormat call() throws Exception { return pluralizeFormat(template); }; }, locale); }
java
public static MessageFormat pluralizeFormat(final String template, final Locale locale) { return withinLocale(new Callable<MessageFormat>() { public MessageFormat call() throws Exception { return pluralizeFormat(template); }; }, locale); }
[ "public", "static", "MessageFormat", "pluralizeFormat", "(", "final", "String", "template", ",", "final", "Locale", "locale", ")", "{", "return", "withinLocale", "(", "new", "Callable", "<", "MessageFormat", ">", "(", ")", "{", "public", "MessageFormat", "call", "(", ")", "throws", "Exception", "{", "return", "pluralizeFormat", "(", "template", ")", ";", "}", ";", "}", ",", "locale", ")", ";", "}" ]
<p> Same as {@link #pluralizeFormat(String)} for the specified locale. </p> @param template String of tokens delimited by '::' @param locale Target locale @return Message instance prepared to generate pluralized strings
[ "<p", ">", "Same", "as", "{", "@link", "#pluralizeFormat", "(", "String", ")", "}", "for", "the", "specified", "locale", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2407-L2416
cubedtear/aritzh
aritzh-core/src/main/java/io/github/aritzhack/aritzh/collections/Matrix.java
Matrix.get
public E get(int x, int y) { """ Returns the element in column {@code x} and y {@code y} @param x The column of the element @param y The row of the element @return the element at (x, y) """ if (columns.size() < x) { columns.set(x, new ArrayList<>()); } ArrayList<E> columnList = columns.get(x); if (columnList.size() < y) { columnList.set(y, this.defaultElement); } return columnList.get(y); }
java
public E get(int x, int y) { if (columns.size() < x) { columns.set(x, new ArrayList<>()); } ArrayList<E> columnList = columns.get(x); if (columnList.size() < y) { columnList.set(y, this.defaultElement); } return columnList.get(y); }
[ "public", "E", "get", "(", "int", "x", ",", "int", "y", ")", "{", "if", "(", "columns", ".", "size", "(", ")", "<", "x", ")", "{", "columns", ".", "set", "(", "x", ",", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "ArrayList", "<", "E", ">", "columnList", "=", "columns", ".", "get", "(", "x", ")", ";", "if", "(", "columnList", ".", "size", "(", ")", "<", "y", ")", "{", "columnList", ".", "set", "(", "y", ",", "this", ".", "defaultElement", ")", ";", "}", "return", "columnList", ".", "get", "(", "y", ")", ";", "}" ]
Returns the element in column {@code x} and y {@code y} @param x The column of the element @param y The row of the element @return the element at (x, y)
[ "Returns", "the", "element", "in", "column", "{", "@code", "x", "}", "and", "y", "{", "@code", "y", "}" ]
train
https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/collections/Matrix.java#L126-L135
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokHandler.java
GrokHandler.endElement
@Override public void endElement(String uri, String localName, String qName) throws SAXException { """ Handles the end element event. @param uri the URI of the element @param localName the local name of the element @param qName the qName of the element @throws SAXException thrown if there is an exception processing """ if (null != qName) { switch (qName) { case COMPANY_NAME: data.setCompanyName(currentText.toString()); break; case PRODUCT_NAME: data.setProductName(currentText.toString()); break; case PRODUCT_VERSION: data.setProductVersion(currentText.toString()); break; case COMMENTS: data.setComments(currentText.toString()); break; case FILE_DESCRIPTION: data.setFileDescription(currentText.toString()); break; case FILE_NAME: data.setFileName(currentText.toString()); break; case FILE_VERSION: data.setFileVersion(currentText.toString()); break; case INTERNAL_NAME: data.setInternalName(currentText.toString()); break; case ORIGINAL_FILE_NAME: data.setOriginalFilename(currentText.toString()); break; case FULLNAME: data.setFullName(currentText.toString()); break; case NAMESPACE: data.addNamespace(currentText.toString()); break; case ERROR: data.setError(currentText.toString()); break; case WARNING: data.setWarning(currentText.toString()); break; default: break; } } }
java
@Override public void endElement(String uri, String localName, String qName) throws SAXException { if (null != qName) { switch (qName) { case COMPANY_NAME: data.setCompanyName(currentText.toString()); break; case PRODUCT_NAME: data.setProductName(currentText.toString()); break; case PRODUCT_VERSION: data.setProductVersion(currentText.toString()); break; case COMMENTS: data.setComments(currentText.toString()); break; case FILE_DESCRIPTION: data.setFileDescription(currentText.toString()); break; case FILE_NAME: data.setFileName(currentText.toString()); break; case FILE_VERSION: data.setFileVersion(currentText.toString()); break; case INTERNAL_NAME: data.setInternalName(currentText.toString()); break; case ORIGINAL_FILE_NAME: data.setOriginalFilename(currentText.toString()); break; case FULLNAME: data.setFullName(currentText.toString()); break; case NAMESPACE: data.addNamespace(currentText.toString()); break; case ERROR: data.setError(currentText.toString()); break; case WARNING: data.setWarning(currentText.toString()); break; default: break; } } }
[ "@", "Override", "public", "void", "endElement", "(", "String", "uri", ",", "String", "localName", ",", "String", "qName", ")", "throws", "SAXException", "{", "if", "(", "null", "!=", "qName", ")", "{", "switch", "(", "qName", ")", "{", "case", "COMPANY_NAME", ":", "data", ".", "setCompanyName", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "PRODUCT_NAME", ":", "data", ".", "setProductName", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "PRODUCT_VERSION", ":", "data", ".", "setProductVersion", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "COMMENTS", ":", "data", ".", "setComments", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "FILE_DESCRIPTION", ":", "data", ".", "setFileDescription", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "FILE_NAME", ":", "data", ".", "setFileName", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "FILE_VERSION", ":", "data", ".", "setFileVersion", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "INTERNAL_NAME", ":", "data", ".", "setInternalName", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "ORIGINAL_FILE_NAME", ":", "data", ".", "setOriginalFilename", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "FULLNAME", ":", "data", ".", "setFullName", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "NAMESPACE", ":", "data", ".", "addNamespace", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "ERROR", ":", "data", ".", "setError", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "WARNING", ":", "data", ".", "setWarning", "(", "currentText", ".", "toString", "(", ")", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}", "}" ]
Handles the end element event. @param uri the URI of the element @param localName the local name of the element @param qName the qName of the element @throws SAXException thrown if there is an exception processing
[ "Handles", "the", "end", "element", "event", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokHandler.java#L117-L164
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/randomizers/range/SqlDateRangeRandomizer.java
SqlDateRangeRandomizer.aNewSqlDateRangeRandomizer
public static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed) { """ Create a new {@link SqlDateRangeRandomizer}. @param min min value @param max max value @param seed initial seed @return a new {@link SqlDateRangeRandomizer}. """ return new SqlDateRangeRandomizer(min, max, seed); }
java
public static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed) { return new SqlDateRangeRandomizer(min, max, seed); }
[ "public", "static", "SqlDateRangeRandomizer", "aNewSqlDateRangeRandomizer", "(", "final", "Date", "min", ",", "final", "Date", "max", ",", "final", "long", "seed", ")", "{", "return", "new", "SqlDateRangeRandomizer", "(", "min", ",", "max", ",", "seed", ")", ";", "}" ]
Create a new {@link SqlDateRangeRandomizer}. @param min min value @param max max value @param seed initial seed @return a new {@link SqlDateRangeRandomizer}.
[ "Create", "a", "new", "{", "@link", "SqlDateRangeRandomizer", "}", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/range/SqlDateRangeRandomizer.java#L75-L77
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_download_policy.java
ns_conf_download_policy.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ ns_conf_download_policy_responses result = (ns_conf_download_policy_responses) service.get_payload_formatter().string_to_resource(ns_conf_download_policy_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_download_policy_response_array); } ns_conf_download_policy[] result_ns_conf_download_policy = new ns_conf_download_policy[result.ns_conf_download_policy_response_array.length]; for(int i = 0; i < result.ns_conf_download_policy_response_array.length; i++) { result_ns_conf_download_policy[i] = result.ns_conf_download_policy_response_array[i].ns_conf_download_policy[0]; } return result_ns_conf_download_policy; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_conf_download_policy_responses result = (ns_conf_download_policy_responses) service.get_payload_formatter().string_to_resource(ns_conf_download_policy_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_download_policy_response_array); } ns_conf_download_policy[] result_ns_conf_download_policy = new ns_conf_download_policy[result.ns_conf_download_policy_response_array.length]; for(int i = 0; i < result.ns_conf_download_policy_response_array.length; i++) { result_ns_conf_download_policy[i] = result.ns_conf_download_policy_response_array[i].ns_conf_download_policy[0]; } return result_ns_conf_download_policy; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_conf_download_policy_responses", "result", "=", "(", "ns_conf_download_policy_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "ns_conf_download_policy_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "ns_conf_download_policy_response_array", ")", ";", "}", "ns_conf_download_policy", "[", "]", "result_ns_conf_download_policy", "=", "new", "ns_conf_download_policy", "[", "result", ".", "ns_conf_download_policy_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "ns_conf_download_policy_response_array", ".", "length", ";", "i", "++", ")", "{", "result_ns_conf_download_policy", "[", "i", "]", "=", "result", ".", "ns_conf_download_policy_response_array", "[", "i", "]", ".", "ns_conf_download_policy", "[", "0", "]", ";", "}", "return", "result_ns_conf_download_policy", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_download_policy.java#L234-L251
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.updateAsync
public Observable<RedisResourceInner> updateAsync(String resourceGroupName, String name, RedisUpdateParameters parameters) { """ Update an existing Redis cache. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @param parameters Parameters supplied to the Update Redis operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RedisResourceInner object """ return updateWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() { @Override public RedisResourceInner call(ServiceResponse<RedisResourceInner> response) { return response.body(); } }); }
java
public Observable<RedisResourceInner> updateAsync(String resourceGroupName, String name, RedisUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() { @Override public RedisResourceInner call(ServiceResponse<RedisResourceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RedisResourceInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "name", ",", "RedisUpdateParameters", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RedisResourceInner", ">", ",", "RedisResourceInner", ">", "(", ")", "{", "@", "Override", "public", "RedisResourceInner", "call", "(", "ServiceResponse", "<", "RedisResourceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Update an existing Redis cache. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @param parameters Parameters supplied to the Update Redis operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RedisResourceInner object
[ "Update", "an", "existing", "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#L534-L541
Prototik/HoloEverywhere
library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java
RadialPickerLayout.setItem
private void setItem(int index, int value) { """ Set either the hour or the minute. Will set the internal value, and set the selection. """ if (index == HOUR_INDEX) { setValueForItem(HOUR_INDEX, value); int hourDegrees = (value % 12) * HOUR_VALUE_TO_DEGREES_STEP_SIZE; mHourRadialSelectorView.setSelection(hourDegrees, isHourInnerCircle(value), false); mHourRadialSelectorView.invalidate(); } else if (index == MINUTE_INDEX) { setValueForItem(MINUTE_INDEX, value); int minuteDegrees = value * MINUTE_VALUE_TO_DEGREES_STEP_SIZE; mMinuteRadialSelectorView.setSelection(minuteDegrees, false, false); mMinuteRadialSelectorView.invalidate(); } }
java
private void setItem(int index, int value) { if (index == HOUR_INDEX) { setValueForItem(HOUR_INDEX, value); int hourDegrees = (value % 12) * HOUR_VALUE_TO_DEGREES_STEP_SIZE; mHourRadialSelectorView.setSelection(hourDegrees, isHourInnerCircle(value), false); mHourRadialSelectorView.invalidate(); } else if (index == MINUTE_INDEX) { setValueForItem(MINUTE_INDEX, value); int minuteDegrees = value * MINUTE_VALUE_TO_DEGREES_STEP_SIZE; mMinuteRadialSelectorView.setSelection(minuteDegrees, false, false); mMinuteRadialSelectorView.invalidate(); } }
[ "private", "void", "setItem", "(", "int", "index", ",", "int", "value", ")", "{", "if", "(", "index", "==", "HOUR_INDEX", ")", "{", "setValueForItem", "(", "HOUR_INDEX", ",", "value", ")", ";", "int", "hourDegrees", "=", "(", "value", "%", "12", ")", "*", "HOUR_VALUE_TO_DEGREES_STEP_SIZE", ";", "mHourRadialSelectorView", ".", "setSelection", "(", "hourDegrees", ",", "isHourInnerCircle", "(", "value", ")", ",", "false", ")", ";", "mHourRadialSelectorView", ".", "invalidate", "(", ")", ";", "}", "else", "if", "(", "index", "==", "MINUTE_INDEX", ")", "{", "setValueForItem", "(", "MINUTE_INDEX", ",", "value", ")", ";", "int", "minuteDegrees", "=", "value", "*", "MINUTE_VALUE_TO_DEGREES_STEP_SIZE", ";", "mMinuteRadialSelectorView", ".", "setSelection", "(", "minuteDegrees", ",", "false", ",", "false", ")", ";", "mMinuteRadialSelectorView", ".", "invalidate", "(", ")", ";", "}", "}" ]
Set either the hour or the minute. Will set the internal value, and set the selection.
[ "Set", "either", "the", "hour", "or", "the", "minute", ".", "Will", "set", "the", "internal", "value", "and", "set", "the", "selection", "." ]
train
https://github.com/Prototik/HoloEverywhere/blob/b870abb5ab009a5a6dbab3fb855ec2854e35e125/library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java#L225-L237
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/handlers/ResponseHandler.java
ResponseHandler.handleBinaryResponse
protected void handleBinaryResponse(HttpServerExchange exchange, Response response) { """ Handles a binary response to the client by sending the binary content from the response to the undertow output stream @param exchange The Undertow HttpServerExchange @param response The response object @throws IOException """ exchange.dispatch(exchange.getDispatchExecutor(), Application.getInstance(BinaryHandler.class).withResponse(response)); }
java
protected void handleBinaryResponse(HttpServerExchange exchange, Response response) { exchange.dispatch(exchange.getDispatchExecutor(), Application.getInstance(BinaryHandler.class).withResponse(response)); }
[ "protected", "void", "handleBinaryResponse", "(", "HttpServerExchange", "exchange", ",", "Response", "response", ")", "{", "exchange", ".", "dispatch", "(", "exchange", ".", "getDispatchExecutor", "(", ")", ",", "Application", ".", "getInstance", "(", "BinaryHandler", ".", "class", ")", ".", "withResponse", "(", "response", ")", ")", ";", "}" ]
Handles a binary response to the client by sending the binary content from the response to the undertow output stream @param exchange The Undertow HttpServerExchange @param response The response object @throws IOException
[ "Handles", "a", "binary", "response", "to", "the", "client", "by", "sending", "the", "binary", "content", "from", "the", "response", "to", "the", "undertow", "output", "stream" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/ResponseHandler.java#L53-L55
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java
SequenceFunctionRefiner.scoreAbsError
private static double scoreAbsError(Integer pre, Integer image,int minPre,int maxPre) { """ Calculate the score for a residue, specifically the Absolute Error score(x) = |x-f^k(x)| Also includes a small bias based on residue number, for uniqueness.. @param pre x @param image f^k(x) @param minPre lowest possible residue number @param maxPre highest possible residue number @return """ // Use the absolute error score, |x - f^k(x)| double error; if(image == null) { error = Double.POSITIVE_INFINITY; } else { error = Math.abs(pre - image); } //TODO favor lower degree-in // Add fractional portion relative to sequence position, for uniqueness if(error > 0) error += (double)(pre-minPre)/(1+maxPre-minPre); return error; }
java
private static double scoreAbsError(Integer pre, Integer image,int minPre,int maxPre) { // Use the absolute error score, |x - f^k(x)| double error; if(image == null) { error = Double.POSITIVE_INFINITY; } else { error = Math.abs(pre - image); } //TODO favor lower degree-in // Add fractional portion relative to sequence position, for uniqueness if(error > 0) error += (double)(pre-minPre)/(1+maxPre-minPre); return error; }
[ "private", "static", "double", "scoreAbsError", "(", "Integer", "pre", ",", "Integer", "image", ",", "int", "minPre", ",", "int", "maxPre", ")", "{", "// Use the absolute error score, |x - f^k(x)|", "double", "error", ";", "if", "(", "image", "==", "null", ")", "{", "error", "=", "Double", ".", "POSITIVE_INFINITY", ";", "}", "else", "{", "error", "=", "Math", ".", "abs", "(", "pre", "-", "image", ")", ";", "}", "//TODO favor lower degree-in", "// Add fractional portion relative to sequence position, for uniqueness", "if", "(", "error", ">", "0", ")", "error", "+=", "(", "double", ")", "(", "pre", "-", "minPre", ")", "/", "(", "1", "+", "maxPre", "-", "minPre", ")", ";", "return", "error", ";", "}" ]
Calculate the score for a residue, specifically the Absolute Error score(x) = |x-f^k(x)| Also includes a small bias based on residue number, for uniqueness.. @param pre x @param image f^k(x) @param minPre lowest possible residue number @param maxPre highest possible residue number @return
[ "Calculate", "the", "score", "for", "a", "residue", "specifically", "the", "Absolute", "Error", "score", "(", "x", ")", "=", "|x", "-", "f^k", "(", "x", ")", "|" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java#L412-L428
apache/incubator-druid
extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java
ApproximateHistogram.mergeInsert
protected void mergeInsert(final int mergeAt, int insertAt, final float v, final long c) { """ Merges the bin in the mergeAt position with the bin in position mergeAt+1 and simultaneously inserts the given bin (v,c) as a new bin at position insertAt @param mergeAt index of the bin to be merged @param insertAt index to insert the new bin at @param v bin position @param c bin count """ final long k0 = (bins[mergeAt] & COUNT_BITS); final long k1 = (bins[mergeAt + 1] & COUNT_BITS); final long sum = k0 + k1; // merge bin at given position with the next bin and set approximate flag positions[mergeAt] = (float) (((double) positions[mergeAt] * k0 + (double) positions[mergeAt + 1] * k1) / sum); bins[mergeAt] = sum | APPROX_FLAG_BIT; final int unusedIndex = mergeAt + 1; if (insertAt >= 0) { // use unused slot to shift array left or right and make space for the new bin to insert if (insertAt < unusedIndex) { shiftRight(insertAt, unusedIndex); } else if (insertAt >= unusedIndex) { shiftLeft(unusedIndex, insertAt - 1); insertAt--; } positions[insertAt] = v; bins[insertAt] = c; count++; } else { // simple merging of bins, shift everything left and free up the unused bin shiftLeft(unusedIndex, binCount - 1); binCount--; } }
java
protected void mergeInsert(final int mergeAt, int insertAt, final float v, final long c) { final long k0 = (bins[mergeAt] & COUNT_BITS); final long k1 = (bins[mergeAt + 1] & COUNT_BITS); final long sum = k0 + k1; // merge bin at given position with the next bin and set approximate flag positions[mergeAt] = (float) (((double) positions[mergeAt] * k0 + (double) positions[mergeAt + 1] * k1) / sum); bins[mergeAt] = sum | APPROX_FLAG_BIT; final int unusedIndex = mergeAt + 1; if (insertAt >= 0) { // use unused slot to shift array left or right and make space for the new bin to insert if (insertAt < unusedIndex) { shiftRight(insertAt, unusedIndex); } else if (insertAt >= unusedIndex) { shiftLeft(unusedIndex, insertAt - 1); insertAt--; } positions[insertAt] = v; bins[insertAt] = c; count++; } else { // simple merging of bins, shift everything left and free up the unused bin shiftLeft(unusedIndex, binCount - 1); binCount--; } }
[ "protected", "void", "mergeInsert", "(", "final", "int", "mergeAt", ",", "int", "insertAt", ",", "final", "float", "v", ",", "final", "long", "c", ")", "{", "final", "long", "k0", "=", "(", "bins", "[", "mergeAt", "]", "&", "COUNT_BITS", ")", ";", "final", "long", "k1", "=", "(", "bins", "[", "mergeAt", "+", "1", "]", "&", "COUNT_BITS", ")", ";", "final", "long", "sum", "=", "k0", "+", "k1", ";", "// merge bin at given position with the next bin and set approximate flag", "positions", "[", "mergeAt", "]", "=", "(", "float", ")", "(", "(", "(", "double", ")", "positions", "[", "mergeAt", "]", "*", "k0", "+", "(", "double", ")", "positions", "[", "mergeAt", "+", "1", "]", "*", "k1", ")", "/", "sum", ")", ";", "bins", "[", "mergeAt", "]", "=", "sum", "|", "APPROX_FLAG_BIT", ";", "final", "int", "unusedIndex", "=", "mergeAt", "+", "1", ";", "if", "(", "insertAt", ">=", "0", ")", "{", "// use unused slot to shift array left or right and make space for the new bin to insert", "if", "(", "insertAt", "<", "unusedIndex", ")", "{", "shiftRight", "(", "insertAt", ",", "unusedIndex", ")", ";", "}", "else", "if", "(", "insertAt", ">=", "unusedIndex", ")", "{", "shiftLeft", "(", "unusedIndex", ",", "insertAt", "-", "1", ")", ";", "insertAt", "--", ";", "}", "positions", "[", "insertAt", "]", "=", "v", ";", "bins", "[", "insertAt", "]", "=", "c", ";", "count", "++", ";", "}", "else", "{", "// simple merging of bins, shift everything left and free up the unused bin", "shiftLeft", "(", "unusedIndex", ",", "binCount", "-", "1", ")", ";", "binCount", "--", ";", "}", "}" ]
Merges the bin in the mergeAt position with the bin in position mergeAt+1 and simultaneously inserts the given bin (v,c) as a new bin at position insertAt @param mergeAt index of the bin to be merged @param insertAt index to insert the new bin at @param v bin position @param c bin count
[ "Merges", "the", "bin", "in", "the", "mergeAt", "position", "with", "the", "bin", "in", "position", "mergeAt", "+", "1", "and", "simultaneously", "inserts", "the", "given", "bin", "(", "v", "c", ")", "as", "a", "new", "bin", "at", "position", "insertAt" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java#L406-L434
aol/cyclops
cyclops/src/main/java/com/oath/cyclops/util/box/MutableInt.java
MutableInt.fromExternal
public static MutableInt fromExternal(final IntSupplier s, final IntConsumer c) { """ Construct a MutableInt that gets and sets an external value using the provided Supplier and Consumer e.g. <pre> {@code MutableInt mutable = MutableInt.fromExternal(()->!this.value,val->!this.value); } </pre> @param s Supplier of an external value @param c Consumer that sets an external value @return MutableInt that gets / sets an external (mutable) value """ return new MutableInt() { @Override public int getAsInt() { return s.getAsInt(); } @Override public Integer get() { return getAsInt(); } @Override public MutableInt set(final int value) { c.accept(value); return this; } }; }
java
public static MutableInt fromExternal(final IntSupplier s, final IntConsumer c) { return new MutableInt() { @Override public int getAsInt() { return s.getAsInt(); } @Override public Integer get() { return getAsInt(); } @Override public MutableInt set(final int value) { c.accept(value); return this; } }; }
[ "public", "static", "MutableInt", "fromExternal", "(", "final", "IntSupplier", "s", ",", "final", "IntConsumer", "c", ")", "{", "return", "new", "MutableInt", "(", ")", "{", "@", "Override", "public", "int", "getAsInt", "(", ")", "{", "return", "s", ".", "getAsInt", "(", ")", ";", "}", "@", "Override", "public", "Integer", "get", "(", ")", "{", "return", "getAsInt", "(", ")", ";", "}", "@", "Override", "public", "MutableInt", "set", "(", "final", "int", "value", ")", "{", "c", ".", "accept", "(", "value", ")", ";", "return", "this", ";", "}", "}", ";", "}" ]
Construct a MutableInt that gets and sets an external value using the provided Supplier and Consumer e.g. <pre> {@code MutableInt mutable = MutableInt.fromExternal(()->!this.value,val->!this.value); } </pre> @param s Supplier of an external value @param c Consumer that sets an external value @return MutableInt that gets / sets an external (mutable) value
[ "Construct", "a", "MutableInt", "that", "gets", "and", "sets", "an", "external", "value", "using", "the", "provided", "Supplier", "and", "Consumer" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/com/oath/cyclops/util/box/MutableInt.java#L80-L98
google/auto
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
AutoValueOrOneOfProcessor.checkReturnType
final void checkReturnType(TypeElement autoValueClass, ExecutableElement getter) { """ Checks that the return type of the given property method is allowed. Currently, this means that it cannot be an array, unless it is a primitive array. """ TypeMirror type = getter.getReturnType(); if (type.getKind() == TypeKind.ARRAY) { TypeMirror componentType = ((ArrayType) type).getComponentType(); if (componentType.getKind().isPrimitive()) { warnAboutPrimitiveArrays(autoValueClass, getter); } else { errorReporter.reportError( "An @" + simpleAnnotationName + " class cannot define an array-valued property unless it is a primitive array", getter); } } }
java
final void checkReturnType(TypeElement autoValueClass, ExecutableElement getter) { TypeMirror type = getter.getReturnType(); if (type.getKind() == TypeKind.ARRAY) { TypeMirror componentType = ((ArrayType) type).getComponentType(); if (componentType.getKind().isPrimitive()) { warnAboutPrimitiveArrays(autoValueClass, getter); } else { errorReporter.reportError( "An @" + simpleAnnotationName + " class cannot define an array-valued property unless it is a primitive array", getter); } } }
[ "final", "void", "checkReturnType", "(", "TypeElement", "autoValueClass", ",", "ExecutableElement", "getter", ")", "{", "TypeMirror", "type", "=", "getter", ".", "getReturnType", "(", ")", ";", "if", "(", "type", ".", "getKind", "(", ")", "==", "TypeKind", ".", "ARRAY", ")", "{", "TypeMirror", "componentType", "=", "(", "(", "ArrayType", ")", "type", ")", ".", "getComponentType", "(", ")", ";", "if", "(", "componentType", ".", "getKind", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "warnAboutPrimitiveArrays", "(", "autoValueClass", ",", "getter", ")", ";", "}", "else", "{", "errorReporter", ".", "reportError", "(", "\"An @\"", "+", "simpleAnnotationName", "+", "\" class cannot define an array-valued property unless it is a primitive array\"", ",", "getter", ")", ";", "}", "}", "}" ]
Checks that the return type of the given property method is allowed. Currently, this means that it cannot be an array, unless it is a primitive array.
[ "Checks", "that", "the", "return", "type", "of", "the", "given", "property", "method", "is", "allowed", ".", "Currently", "this", "means", "that", "it", "cannot", "be", "an", "array", "unless", "it", "is", "a", "primitive", "array", "." ]
train
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L738-L752
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java
JRDF.sameResource
public static boolean sameResource(URIReference u1, URIReference u2) { """ Tells whether the given resources are equivalent. <p> Two resources are equivalent if their URIs match. @param u1 first resource. @param u2 second resource. @return true if equivalent, false otherwise. """ return sameResource(u1, u2.getURI().toString()); }
java
public static boolean sameResource(URIReference u1, URIReference u2) { return sameResource(u1, u2.getURI().toString()); }
[ "public", "static", "boolean", "sameResource", "(", "URIReference", "u1", ",", "URIReference", "u2", ")", "{", "return", "sameResource", "(", "u1", ",", "u2", ".", "getURI", "(", ")", ".", "toString", "(", ")", ")", ";", "}" ]
Tells whether the given resources are equivalent. <p> Two resources are equivalent if their URIs match. @param u1 first resource. @param u2 second resource. @return true if equivalent, false otherwise.
[ "Tells", "whether", "the", "given", "resources", "are", "equivalent", ".", "<p", ">", "Two", "resources", "are", "equivalent", "if", "their", "URIs", "match", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java#L56-L58
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/ConnectedStreams.java
ConnectedStreams.flatMap
public <R> SingleOutputStreamOperator<R> flatMap( CoFlatMapFunction<IN1, IN2, R> coFlatMapper) { """ Applies a CoFlatMap transformation on a {@link ConnectedStreams} and maps the output to a common type. The transformation calls a {@link CoFlatMapFunction#flatMap1} for each element of the first input and {@link CoFlatMapFunction#flatMap2} for each element of the second input. Each CoFlatMapFunction call returns any number of elements including none. @param coFlatMapper The CoFlatMapFunction used to jointly transform the two input DataStreams @return The transformed {@link DataStream} """ TypeInformation<R> outTypeInfo = TypeExtractor.getBinaryOperatorReturnType( coFlatMapper, CoFlatMapFunction.class, 0, 1, 2, TypeExtractor.NO_INDEX, getType1(), getType2(), Utils.getCallLocationName(), true); return transform("Co-Flat Map", outTypeInfo, new CoStreamFlatMap<>(inputStream1.clean(coFlatMapper))); }
java
public <R> SingleOutputStreamOperator<R> flatMap( CoFlatMapFunction<IN1, IN2, R> coFlatMapper) { TypeInformation<R> outTypeInfo = TypeExtractor.getBinaryOperatorReturnType( coFlatMapper, CoFlatMapFunction.class, 0, 1, 2, TypeExtractor.NO_INDEX, getType1(), getType2(), Utils.getCallLocationName(), true); return transform("Co-Flat Map", outTypeInfo, new CoStreamFlatMap<>(inputStream1.clean(coFlatMapper))); }
[ "public", "<", "R", ">", "SingleOutputStreamOperator", "<", "R", ">", "flatMap", "(", "CoFlatMapFunction", "<", "IN1", ",", "IN2", ",", "R", ">", "coFlatMapper", ")", "{", "TypeInformation", "<", "R", ">", "outTypeInfo", "=", "TypeExtractor", ".", "getBinaryOperatorReturnType", "(", "coFlatMapper", ",", "CoFlatMapFunction", ".", "class", ",", "0", ",", "1", ",", "2", ",", "TypeExtractor", ".", "NO_INDEX", ",", "getType1", "(", ")", ",", "getType2", "(", ")", ",", "Utils", ".", "getCallLocationName", "(", ")", ",", "true", ")", ";", "return", "transform", "(", "\"Co-Flat Map\"", ",", "outTypeInfo", ",", "new", "CoStreamFlatMap", "<>", "(", "inputStream1", ".", "clean", "(", "coFlatMapper", ")", ")", ")", ";", "}" ]
Applies a CoFlatMap transformation on a {@link ConnectedStreams} and maps the output to a common type. The transformation calls a {@link CoFlatMapFunction#flatMap1} for each element of the first input and {@link CoFlatMapFunction#flatMap2} for each element of the second input. Each CoFlatMapFunction call returns any number of elements including none. @param coFlatMapper The CoFlatMapFunction used to jointly transform the two input DataStreams @return The transformed {@link DataStream}
[ "Applies", "a", "CoFlatMap", "transformation", "on", "a", "{", "@link", "ConnectedStreams", "}", "and", "maps", "the", "output", "to", "a", "common", "type", ".", "The", "transformation", "calls", "a", "{", "@link", "CoFlatMapFunction#flatMap1", "}", "for", "each", "element", "of", "the", "first", "input", "and", "{", "@link", "CoFlatMapFunction#flatMap2", "}", "for", "each", "element", "of", "the", "second", "input", ".", "Each", "CoFlatMapFunction", "call", "returns", "any", "number", "of", "elements", "including", "none", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/ConnectedStreams.java#L257-L273
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java
RedundentExprEliminator.assertIsLocPathIterator
private final void assertIsLocPathIterator(Expression expr1, ExpressionOwner eo) throws RuntimeException { """ Assert that the expression is a LocPathIterator, and, if not, try to give some diagnostic info. """ if(!(expr1 instanceof LocPathIterator)) { String errMsg; if(expr1 instanceof Variable) { errMsg = "Programmer's assertion: expr1 not an iterator: "+ ((Variable)expr1).getQName(); } else { errMsg = "Programmer's assertion: expr1 not an iterator: "+ expr1.getClass().getName(); } throw new RuntimeException(errMsg + ", "+ eo.getClass().getName()+" "+ expr1.exprGetParent()); } }
java
private final void assertIsLocPathIterator(Expression expr1, ExpressionOwner eo) throws RuntimeException { if(!(expr1 instanceof LocPathIterator)) { String errMsg; if(expr1 instanceof Variable) { errMsg = "Programmer's assertion: expr1 not an iterator: "+ ((Variable)expr1).getQName(); } else { errMsg = "Programmer's assertion: expr1 not an iterator: "+ expr1.getClass().getName(); } throw new RuntimeException(errMsg + ", "+ eo.getClass().getName()+" "+ expr1.exprGetParent()); } }
[ "private", "final", "void", "assertIsLocPathIterator", "(", "Expression", "expr1", ",", "ExpressionOwner", "eo", ")", "throws", "RuntimeException", "{", "if", "(", "!", "(", "expr1", "instanceof", "LocPathIterator", ")", ")", "{", "String", "errMsg", ";", "if", "(", "expr1", "instanceof", "Variable", ")", "{", "errMsg", "=", "\"Programmer's assertion: expr1 not an iterator: \"", "+", "(", "(", "Variable", ")", "expr1", ")", ".", "getQName", "(", ")", ";", "}", "else", "{", "errMsg", "=", "\"Programmer's assertion: expr1 not an iterator: \"", "+", "expr1", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "}", "throw", "new", "RuntimeException", "(", "errMsg", "+", "\", \"", "+", "eo", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\" \"", "+", "expr1", ".", "exprGetParent", "(", ")", ")", ";", "}", "}" ]
Assert that the expression is a LocPathIterator, and, if not, try to give some diagnostic info.
[ "Assert", "that", "the", "expression", "is", "a", "LocPathIterator", "and", "if", "not", "try", "to", "give", "some", "diagnostic", "info", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java#L1241-L1261
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_office_new_GET
public ArrayList<String> license_office_new_GET(String giftCode, Long officeBusinessQuantity, Long officeProPlusQuantity) throws IOException { """ Get allowed durations for 'new' option REST: GET /order/license/office/new @param officeProPlusQuantity [required] Number of prepaid office pro plus license @param officeBusinessQuantity [required] Number of prepaid office business license @param giftCode [required] Gift code for office license """ String qPath = "/order/license/office/new"; StringBuilder sb = path(qPath); query(sb, "giftCode", giftCode); query(sb, "officeBusinessQuantity", officeBusinessQuantity); query(sb, "officeProPlusQuantity", officeProPlusQuantity); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> license_office_new_GET(String giftCode, Long officeBusinessQuantity, Long officeProPlusQuantity) throws IOException { String qPath = "/order/license/office/new"; StringBuilder sb = path(qPath); query(sb, "giftCode", giftCode); query(sb, "officeBusinessQuantity", officeBusinessQuantity); query(sb, "officeProPlusQuantity", officeProPlusQuantity); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "license_office_new_GET", "(", "String", "giftCode", ",", "Long", "officeBusinessQuantity", ",", "Long", "officeProPlusQuantity", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/license/office/new\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", ",", "\"giftCode\"", ",", "giftCode", ")", ";", "query", "(", "sb", ",", "\"officeBusinessQuantity\"", ",", "officeBusinessQuantity", ")", ";", "query", "(", "sb", ",", "\"officeProPlusQuantity\"", ",", "officeProPlusQuantity", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t1", ")", ";", "}" ]
Get allowed durations for 'new' option REST: GET /order/license/office/new @param officeProPlusQuantity [required] Number of prepaid office pro plus license @param officeBusinessQuantity [required] Number of prepaid office business license @param giftCode [required] Gift code for office license
[ "Get", "allowed", "durations", "for", "new", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1688-L1696
medallia/Word2VecJava
src/main/java/com/medallia/word2vec/util/IO.java
IO.copyAndCloseOutput
public static long copyAndCloseOutput(InputStream input, OutputStream output) throws IOException { """ Copy input to output and close the output stream before returning """ try (OutputStream outputStream = output) { return copy(input, outputStream); } }
java
public static long copyAndCloseOutput(InputStream input, OutputStream output) throws IOException { try (OutputStream outputStream = output) { return copy(input, outputStream); } }
[ "public", "static", "long", "copyAndCloseOutput", "(", "InputStream", "input", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "try", "(", "OutputStream", "outputStream", "=", "output", ")", "{", "return", "copy", "(", "input", ",", "outputStream", ")", ";", "}", "}" ]
Copy input to output and close the output stream before returning
[ "Copy", "input", "to", "output", "and", "close", "the", "output", "stream", "before", "returning" ]
train
https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/IO.java#L51-L55
hankcs/HanLP
src/main/java/com/hankcs/hanlp/dependency/perceptron/transition/features/FeatureExtractor.java
FeatureExtractor.extractAllParseFeatures
public static Object[] extractAllParseFeatures(Configuration configuration, int length) { """ Given a list of templates, extracts all features for the given state @param configuration @return @throws Exception """ if (length == 26) return extractBasicFeatures(configuration, length); else if (length == 72) return extractExtendedFeatures(configuration, length); else return extractExtendedFeaturesWithBrownClusters(configuration, length); }
java
public static Object[] extractAllParseFeatures(Configuration configuration, int length) { if (length == 26) return extractBasicFeatures(configuration, length); else if (length == 72) return extractExtendedFeatures(configuration, length); else return extractExtendedFeaturesWithBrownClusters(configuration, length); }
[ "public", "static", "Object", "[", "]", "extractAllParseFeatures", "(", "Configuration", "configuration", ",", "int", "length", ")", "{", "if", "(", "length", "==", "26", ")", "return", "extractBasicFeatures", "(", "configuration", ",", "length", ")", ";", "else", "if", "(", "length", "==", "72", ")", "return", "extractExtendedFeatures", "(", "configuration", ",", "length", ")", ";", "else", "return", "extractExtendedFeaturesWithBrownClusters", "(", "configuration", ",", "length", ")", ";", "}" ]
Given a list of templates, extracts all features for the given state @param configuration @return @throws Exception
[ "Given", "a", "list", "of", "templates", "extracts", "all", "features", "for", "the", "given", "state" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/perceptron/transition/features/FeatureExtractor.java#L21-L29
apache/flink
flink-clients/src/main/java/org/apache/flink/client/program/rest/RestClusterClient.java
RestClusterClient.submitJob
@Override public CompletableFuture<JobSubmissionResult> submitJob(@Nonnull JobGraph jobGraph) { """ Submits the given {@link JobGraph} to the dispatcher. @param jobGraph to submit @return Future which is completed with the submission response """ // we have to enable queued scheduling because slot will be allocated lazily jobGraph.setAllowQueuedScheduling(true); CompletableFuture<java.nio.file.Path> jobGraphFileFuture = CompletableFuture.supplyAsync(() -> { try { final java.nio.file.Path jobGraphFile = Files.createTempFile("flink-jobgraph", ".bin"); try (ObjectOutputStream objectOut = new ObjectOutputStream(Files.newOutputStream(jobGraphFile))) { objectOut.writeObject(jobGraph); } return jobGraphFile; } catch (IOException e) { throw new CompletionException(new FlinkException("Failed to serialize JobGraph.", e)); } }, executorService); CompletableFuture<Tuple2<JobSubmitRequestBody, Collection<FileUpload>>> requestFuture = jobGraphFileFuture.thenApply(jobGraphFile -> { List<String> jarFileNames = new ArrayList<>(8); List<JobSubmitRequestBody.DistributedCacheFile> artifactFileNames = new ArrayList<>(8); Collection<FileUpload> filesToUpload = new ArrayList<>(8); filesToUpload.add(new FileUpload(jobGraphFile, RestConstants.CONTENT_TYPE_BINARY)); for (Path jar : jobGraph.getUserJars()) { jarFileNames.add(jar.getName()); filesToUpload.add(new FileUpload(Paths.get(jar.toUri()), RestConstants.CONTENT_TYPE_JAR)); } for (Map.Entry<String, DistributedCache.DistributedCacheEntry> artifacts : jobGraph.getUserArtifacts().entrySet()) { artifactFileNames.add(new JobSubmitRequestBody.DistributedCacheFile(artifacts.getKey(), new Path(artifacts.getValue().filePath).getName())); filesToUpload.add(new FileUpload(Paths.get(artifacts.getValue().filePath), RestConstants.CONTENT_TYPE_BINARY)); } final JobSubmitRequestBody requestBody = new JobSubmitRequestBody( jobGraphFile.getFileName().toString(), jarFileNames, artifactFileNames); return Tuple2.of(requestBody, Collections.unmodifiableCollection(filesToUpload)); }); final CompletableFuture<JobSubmitResponseBody> submissionFuture = requestFuture.thenCompose( requestAndFileUploads -> sendRetriableRequest( JobSubmitHeaders.getInstance(), EmptyMessageParameters.getInstance(), requestAndFileUploads.f0, requestAndFileUploads.f1, isConnectionProblemOrServiceUnavailable()) ); submissionFuture .thenCombine(jobGraphFileFuture, (ignored, jobGraphFile) -> jobGraphFile) .thenAccept(jobGraphFile -> { try { Files.delete(jobGraphFile); } catch (IOException e) { log.warn("Could not delete temporary file {}.", jobGraphFile, e); } }); return submissionFuture .thenApply( (JobSubmitResponseBody jobSubmitResponseBody) -> new JobSubmissionResult(jobGraph.getJobID())) .exceptionally( (Throwable throwable) -> { throw new CompletionException(new JobSubmissionException(jobGraph.getJobID(), "Failed to submit JobGraph.", ExceptionUtils.stripCompletionException(throwable))); }); }
java
@Override public CompletableFuture<JobSubmissionResult> submitJob(@Nonnull JobGraph jobGraph) { // we have to enable queued scheduling because slot will be allocated lazily jobGraph.setAllowQueuedScheduling(true); CompletableFuture<java.nio.file.Path> jobGraphFileFuture = CompletableFuture.supplyAsync(() -> { try { final java.nio.file.Path jobGraphFile = Files.createTempFile("flink-jobgraph", ".bin"); try (ObjectOutputStream objectOut = new ObjectOutputStream(Files.newOutputStream(jobGraphFile))) { objectOut.writeObject(jobGraph); } return jobGraphFile; } catch (IOException e) { throw new CompletionException(new FlinkException("Failed to serialize JobGraph.", e)); } }, executorService); CompletableFuture<Tuple2<JobSubmitRequestBody, Collection<FileUpload>>> requestFuture = jobGraphFileFuture.thenApply(jobGraphFile -> { List<String> jarFileNames = new ArrayList<>(8); List<JobSubmitRequestBody.DistributedCacheFile> artifactFileNames = new ArrayList<>(8); Collection<FileUpload> filesToUpload = new ArrayList<>(8); filesToUpload.add(new FileUpload(jobGraphFile, RestConstants.CONTENT_TYPE_BINARY)); for (Path jar : jobGraph.getUserJars()) { jarFileNames.add(jar.getName()); filesToUpload.add(new FileUpload(Paths.get(jar.toUri()), RestConstants.CONTENT_TYPE_JAR)); } for (Map.Entry<String, DistributedCache.DistributedCacheEntry> artifacts : jobGraph.getUserArtifacts().entrySet()) { artifactFileNames.add(new JobSubmitRequestBody.DistributedCacheFile(artifacts.getKey(), new Path(artifacts.getValue().filePath).getName())); filesToUpload.add(new FileUpload(Paths.get(artifacts.getValue().filePath), RestConstants.CONTENT_TYPE_BINARY)); } final JobSubmitRequestBody requestBody = new JobSubmitRequestBody( jobGraphFile.getFileName().toString(), jarFileNames, artifactFileNames); return Tuple2.of(requestBody, Collections.unmodifiableCollection(filesToUpload)); }); final CompletableFuture<JobSubmitResponseBody> submissionFuture = requestFuture.thenCompose( requestAndFileUploads -> sendRetriableRequest( JobSubmitHeaders.getInstance(), EmptyMessageParameters.getInstance(), requestAndFileUploads.f0, requestAndFileUploads.f1, isConnectionProblemOrServiceUnavailable()) ); submissionFuture .thenCombine(jobGraphFileFuture, (ignored, jobGraphFile) -> jobGraphFile) .thenAccept(jobGraphFile -> { try { Files.delete(jobGraphFile); } catch (IOException e) { log.warn("Could not delete temporary file {}.", jobGraphFile, e); } }); return submissionFuture .thenApply( (JobSubmitResponseBody jobSubmitResponseBody) -> new JobSubmissionResult(jobGraph.getJobID())) .exceptionally( (Throwable throwable) -> { throw new CompletionException(new JobSubmissionException(jobGraph.getJobID(), "Failed to submit JobGraph.", ExceptionUtils.stripCompletionException(throwable))); }); }
[ "@", "Override", "public", "CompletableFuture", "<", "JobSubmissionResult", ">", "submitJob", "(", "@", "Nonnull", "JobGraph", "jobGraph", ")", "{", "// we have to enable queued scheduling because slot will be allocated lazily", "jobGraph", ".", "setAllowQueuedScheduling", "(", "true", ")", ";", "CompletableFuture", "<", "java", ".", "nio", ".", "file", ".", "Path", ">", "jobGraphFileFuture", "=", "CompletableFuture", ".", "supplyAsync", "(", "(", ")", "->", "{", "try", "{", "final", "java", ".", "nio", ".", "file", ".", "Path", "jobGraphFile", "=", "Files", ".", "createTempFile", "(", "\"flink-jobgraph\"", ",", "\".bin\"", ")", ";", "try", "(", "ObjectOutputStream", "objectOut", "=", "new", "ObjectOutputStream", "(", "Files", ".", "newOutputStream", "(", "jobGraphFile", ")", ")", ")", "{", "objectOut", ".", "writeObject", "(", "jobGraph", ")", ";", "}", "return", "jobGraphFile", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "CompletionException", "(", "new", "FlinkException", "(", "\"Failed to serialize JobGraph.\"", ",", "e", ")", ")", ";", "}", "}", ",", "executorService", ")", ";", "CompletableFuture", "<", "Tuple2", "<", "JobSubmitRequestBody", ",", "Collection", "<", "FileUpload", ">", ">", ">", "requestFuture", "=", "jobGraphFileFuture", ".", "thenApply", "(", "jobGraphFile", "->", "{", "List", "<", "String", ">", "jarFileNames", "=", "new", "ArrayList", "<>", "(", "8", ")", ";", "List", "<", "JobSubmitRequestBody", ".", "DistributedCacheFile", ">", "artifactFileNames", "=", "new", "ArrayList", "<>", "(", "8", ")", ";", "Collection", "<", "FileUpload", ">", "filesToUpload", "=", "new", "ArrayList", "<>", "(", "8", ")", ";", "filesToUpload", ".", "add", "(", "new", "FileUpload", "(", "jobGraphFile", ",", "RestConstants", ".", "CONTENT_TYPE_BINARY", ")", ")", ";", "for", "(", "Path", "jar", ":", "jobGraph", ".", "getUserJars", "(", ")", ")", "{", "jarFileNames", ".", "add", "(", "jar", ".", "getName", "(", ")", ")", ";", "filesToUpload", ".", "add", "(", "new", "FileUpload", "(", "Paths", ".", "get", "(", "jar", ".", "toUri", "(", ")", ")", ",", "RestConstants", ".", "CONTENT_TYPE_JAR", ")", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DistributedCache", ".", "DistributedCacheEntry", ">", "artifacts", ":", "jobGraph", ".", "getUserArtifacts", "(", ")", ".", "entrySet", "(", ")", ")", "{", "artifactFileNames", ".", "add", "(", "new", "JobSubmitRequestBody", ".", "DistributedCacheFile", "(", "artifacts", ".", "getKey", "(", ")", ",", "new", "Path", "(", "artifacts", ".", "getValue", "(", ")", ".", "filePath", ")", ".", "getName", "(", ")", ")", ")", ";", "filesToUpload", ".", "add", "(", "new", "FileUpload", "(", "Paths", ".", "get", "(", "artifacts", ".", "getValue", "(", ")", ".", "filePath", ")", ",", "RestConstants", ".", "CONTENT_TYPE_BINARY", ")", ")", ";", "}", "final", "JobSubmitRequestBody", "requestBody", "=", "new", "JobSubmitRequestBody", "(", "jobGraphFile", ".", "getFileName", "(", ")", ".", "toString", "(", ")", ",", "jarFileNames", ",", "artifactFileNames", ")", ";", "return", "Tuple2", ".", "of", "(", "requestBody", ",", "Collections", ".", "unmodifiableCollection", "(", "filesToUpload", ")", ")", ";", "}", ")", ";", "final", "CompletableFuture", "<", "JobSubmitResponseBody", ">", "submissionFuture", "=", "requestFuture", ".", "thenCompose", "(", "requestAndFileUploads", "->", "sendRetriableRequest", "(", "JobSubmitHeaders", ".", "getInstance", "(", ")", ",", "EmptyMessageParameters", ".", "getInstance", "(", ")", ",", "requestAndFileUploads", ".", "f0", ",", "requestAndFileUploads", ".", "f1", ",", "isConnectionProblemOrServiceUnavailable", "(", ")", ")", ")", ";", "submissionFuture", ".", "thenCombine", "(", "jobGraphFileFuture", ",", "(", "ignored", ",", "jobGraphFile", ")", "->", "jobGraphFile", ")", ".", "thenAccept", "(", "jobGraphFile", "->", "{", "try", "{", "Files", ".", "delete", "(", "jobGraphFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "warn", "(", "\"Could not delete temporary file {}.\"", ",", "jobGraphFile", ",", "e", ")", ";", "}", "}", ")", ";", "return", "submissionFuture", ".", "thenApply", "(", "(", "JobSubmitResponseBody", "jobSubmitResponseBody", ")", "->", "new", "JobSubmissionResult", "(", "jobGraph", ".", "getJobID", "(", ")", ")", ")", ".", "exceptionally", "(", "(", "Throwable", "throwable", ")", "->", "{", "throw", "new", "CompletionException", "(", "new", "JobSubmissionException", "(", "jobGraph", ".", "getJobID", "(", ")", ",", "\"Failed to submit JobGraph.\"", ",", "ExceptionUtils", ".", "stripCompletionException", "(", "throwable", ")", ")", ")", ";", "}", ")", ";", "}" ]
Submits the given {@link JobGraph} to the dispatcher. @param jobGraph to submit @return Future which is completed with the submission response
[ "Submits", "the", "given", "{", "@link", "JobGraph", "}", "to", "the", "dispatcher", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-clients/src/main/java/org/apache/flink/client/program/rest/RestClusterClient.java#L316-L384
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/XPathCheckResult.java
XPathCheckResult.addMisMatch
public void addMisMatch(String name, String expected, String actual) { """ Adds a mismatch to this result. @param name name of value. @param expected expected value. @param actual value of XPath expression. """ result = "NOK"; Mismatch mismatch = new Mismatch(); mismatch.name = name; mismatch.expected = expected; mismatch.actual = actual; mismatches.add(mismatch); }
java
public void addMisMatch(String name, String expected, String actual) { result = "NOK"; Mismatch mismatch = new Mismatch(); mismatch.name = name; mismatch.expected = expected; mismatch.actual = actual; mismatches.add(mismatch); }
[ "public", "void", "addMisMatch", "(", "String", "name", ",", "String", "expected", ",", "String", "actual", ")", "{", "result", "=", "\"NOK\"", ";", "Mismatch", "mismatch", "=", "new", "Mismatch", "(", ")", ";", "mismatch", ".", "name", "=", "name", ";", "mismatch", ".", "expected", "=", "expected", ";", "mismatch", ".", "actual", "=", "actual", ";", "mismatches", ".", "add", "(", "mismatch", ")", ";", "}" ]
Adds a mismatch to this result. @param name name of value. @param expected expected value. @param actual value of XPath expression.
[ "Adds", "a", "mismatch", "to", "this", "result", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/XPathCheckResult.java#L43-L50
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/optics/ClusterOrder.java
ClusterOrder.getPredecessor
public void getPredecessor(DBIDRef id, DBIDVar out) { """ Get the predecessor. @param id Current id. @param out Output variable to store the predecessor. """ if(predecessor == null) { out.unset(); return; } predecessor.assignVar(id, out); }
java
public void getPredecessor(DBIDRef id, DBIDVar out) { if(predecessor == null) { out.unset(); return; } predecessor.assignVar(id, out); }
[ "public", "void", "getPredecessor", "(", "DBIDRef", "id", ",", "DBIDVar", "out", ")", "{", "if", "(", "predecessor", "==", "null", ")", "{", "out", ".", "unset", "(", ")", ";", "return", ";", "}", "predecessor", ".", "assignVar", "(", "id", ",", "out", ")", ";", "}" ]
Get the predecessor. @param id Current id. @param out Output variable to store the predecessor.
[ "Get", "the", "predecessor", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/optics/ClusterOrder.java#L173-L179
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java
ContextManager.checkWritePermission
public void checkWritePermission(TimedDirContext ctx) throws OperationNotSupportedException { """ Check whether we can write on the LDAP server the context is currently connected to. It is not permissible to write to a fail-over server if write to secondary is disabled. @param ctx The context with a connection to the current LDAP server. @throws OperationNotSupportedException If write to secondary is disabled and the context is not connected to the primary LDAP server. """ if (!iWriteToSecondary) { String providerURL = getProviderURL(ctx); if (!getPrimaryURL().equalsIgnoreCase(providerURL)) { String msg = Tr.formatMessage(tc, WIMMessageKey.WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED, WIMMessageHelper.generateMsgParms(providerURL)); throw new OperationNotSupportedException(WIMMessageKey.WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED, msg); } } }
java
public void checkWritePermission(TimedDirContext ctx) throws OperationNotSupportedException { if (!iWriteToSecondary) { String providerURL = getProviderURL(ctx); if (!getPrimaryURL().equalsIgnoreCase(providerURL)) { String msg = Tr.formatMessage(tc, WIMMessageKey.WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED, WIMMessageHelper.generateMsgParms(providerURL)); throw new OperationNotSupportedException(WIMMessageKey.WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED, msg); } } }
[ "public", "void", "checkWritePermission", "(", "TimedDirContext", "ctx", ")", "throws", "OperationNotSupportedException", "{", "if", "(", "!", "iWriteToSecondary", ")", "{", "String", "providerURL", "=", "getProviderURL", "(", "ctx", ")", ";", "if", "(", "!", "getPrimaryURL", "(", ")", ".", "equalsIgnoreCase", "(", "providerURL", ")", ")", "{", "String", "msg", "=", "Tr", ".", "formatMessage", "(", "tc", ",", "WIMMessageKey", ".", "WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED", ",", "WIMMessageHelper", ".", "generateMsgParms", "(", "providerURL", ")", ")", ";", "throw", "new", "OperationNotSupportedException", "(", "WIMMessageKey", ".", "WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED", ",", "msg", ")", ";", "}", "}", "}" ]
Check whether we can write on the LDAP server the context is currently connected to. It is not permissible to write to a fail-over server if write to secondary is disabled. @param ctx The context with a connection to the current LDAP server. @throws OperationNotSupportedException If write to secondary is disabled and the context is not connected to the primary LDAP server.
[ "Check", "whether", "we", "can", "write", "on", "the", "LDAP", "server", "the", "context", "is", "currently", "connected", "to", ".", "It", "is", "not", "permissible", "to", "write", "to", "a", "fail", "-", "over", "server", "if", "write", "to", "secondary", "is", "disabled", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java#L248-L256
Azure/azure-sdk-for-java
mixedreality/resource-manager/v2019_02_28_preview/src/main/java/com/microsoft/azure/management/mixedreality/v2019_02_28_preview/implementation/SpatialAnchorsAccountsInner.java
SpatialAnchorsAccountsInner.getByResourceGroup
public SpatialAnchorsAccountInner getByResourceGroup(String resourceGroupName, String spatialAnchorsAccountName) { """ Retrieve a Spatial Anchors Account. @param resourceGroupName Name of an Azure resource group. @param spatialAnchorsAccountName Name of an Mixed Reality Spatial Anchors Account. @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 SpatialAnchorsAccountInner object if successful. """ return getByResourceGroupWithServiceResponseAsync(resourceGroupName, spatialAnchorsAccountName).toBlocking().single().body(); }
java
public SpatialAnchorsAccountInner getByResourceGroup(String resourceGroupName, String spatialAnchorsAccountName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, spatialAnchorsAccountName).toBlocking().single().body(); }
[ "public", "SpatialAnchorsAccountInner", "getByResourceGroup", "(", "String", "resourceGroupName", ",", "String", "spatialAnchorsAccountName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "spatialAnchorsAccountName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve a Spatial Anchors Account. @param resourceGroupName Name of an Azure resource group. @param spatialAnchorsAccountName Name of an Mixed Reality Spatial Anchors Account. @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 SpatialAnchorsAccountInner object if successful.
[ "Retrieve", "a", "Spatial", "Anchors", "Account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mixedreality/resource-manager/v2019_02_28_preview/src/main/java/com/microsoft/azure/management/mixedreality/v2019_02_28_preview/implementation/SpatialAnchorsAccountsInner.java#L430-L432
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
MojoExecutor.executeMojo
public static void executeMojo(Plugin plugin, String goal, Xpp3Dom configuration, ExecutionEnvironment env) throws MojoExecutionException { """ Entry point for executing a mojo @param plugin The plugin to execute @param goal The goal to execute @param configuration The execution configuration @param env The execution environment @throws MojoExecutionException If there are any exceptions locating or executing the mojo """ if (configuration == null) { throw new NullPointerException("configuration may not be null"); } try { String executionId = null; if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) { int pos = goal.indexOf('#'); executionId = goal.substring(pos + 1); goal = goal.substring(0, pos); } MavenSession session = env.getMavenSession(); PluginDescriptor pluginDescriptor = env.getPluginManager().loadPlugin( plugin, env.getMavenProject().getRemotePluginRepositories(), session.getRepositorySession()); MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); if (mojoDescriptor == null) { throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion()); } MojoExecution exec = mojoExecution(mojoDescriptor, executionId, configuration); env.getPluginManager().executeMojo(session, exec); } catch (PluginNotFoundException | PluginResolutionException | PluginDescriptorParsingException | InvalidPluginDescriptorException | MojoExecutionException | MojoFailureException | PluginConfigurationException | PluginManagerException e) { throw new MojoExecutionException("Unable to execute mojo", e); } }
java
public static void executeMojo(Plugin plugin, String goal, Xpp3Dom configuration, ExecutionEnvironment env) throws MojoExecutionException { if (configuration == null) { throw new NullPointerException("configuration may not be null"); } try { String executionId = null; if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) { int pos = goal.indexOf('#'); executionId = goal.substring(pos + 1); goal = goal.substring(0, pos); } MavenSession session = env.getMavenSession(); PluginDescriptor pluginDescriptor = env.getPluginManager().loadPlugin( plugin, env.getMavenProject().getRemotePluginRepositories(), session.getRepositorySession()); MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); if (mojoDescriptor == null) { throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion()); } MojoExecution exec = mojoExecution(mojoDescriptor, executionId, configuration); env.getPluginManager().executeMojo(session, exec); } catch (PluginNotFoundException | PluginResolutionException | PluginDescriptorParsingException | InvalidPluginDescriptorException | MojoExecutionException | MojoFailureException | PluginConfigurationException | PluginManagerException e) { throw new MojoExecutionException("Unable to execute mojo", e); } }
[ "public", "static", "void", "executeMojo", "(", "Plugin", "plugin", ",", "String", "goal", ",", "Xpp3Dom", "configuration", ",", "ExecutionEnvironment", "env", ")", "throws", "MojoExecutionException", "{", "if", "(", "configuration", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"configuration may not be null\"", ")", ";", "}", "try", "{", "String", "executionId", "=", "null", ";", "if", "(", "goal", "!=", "null", "&&", "goal", ".", "length", "(", ")", ">", "0", "&&", "goal", ".", "indexOf", "(", "'", "'", ")", ">", "-", "1", ")", "{", "int", "pos", "=", "goal", ".", "indexOf", "(", "'", "'", ")", ";", "executionId", "=", "goal", ".", "substring", "(", "pos", "+", "1", ")", ";", "goal", "=", "goal", ".", "substring", "(", "0", ",", "pos", ")", ";", "}", "MavenSession", "session", "=", "env", ".", "getMavenSession", "(", ")", ";", "PluginDescriptor", "pluginDescriptor", "=", "env", ".", "getPluginManager", "(", ")", ".", "loadPlugin", "(", "plugin", ",", "env", ".", "getMavenProject", "(", ")", ".", "getRemotePluginRepositories", "(", ")", ",", "session", ".", "getRepositorySession", "(", ")", ")", ";", "MojoDescriptor", "mojoDescriptor", "=", "pluginDescriptor", ".", "getMojo", "(", "goal", ")", ";", "if", "(", "mojoDescriptor", "==", "null", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Could not find goal '\"", "+", "goal", "+", "\"' in plugin \"", "+", "plugin", ".", "getGroupId", "(", ")", "+", "\":\"", "+", "plugin", ".", "getArtifactId", "(", ")", "+", "\":\"", "+", "plugin", ".", "getVersion", "(", ")", ")", ";", "}", "MojoExecution", "exec", "=", "mojoExecution", "(", "mojoDescriptor", ",", "executionId", ",", "configuration", ")", ";", "env", ".", "getPluginManager", "(", ")", ".", "executeMojo", "(", "session", ",", "exec", ")", ";", "}", "catch", "(", "PluginNotFoundException", "|", "PluginResolutionException", "|", "PluginDescriptorParsingException", "|", "InvalidPluginDescriptorException", "|", "MojoExecutionException", "|", "MojoFailureException", "|", "PluginConfigurationException", "|", "PluginManagerException", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Unable to execute mojo\"", ",", "e", ")", ";", "}", "}" ]
Entry point for executing a mojo @param plugin The plugin to execute @param goal The goal to execute @param configuration The execution configuration @param env The execution environment @throws MojoExecutionException If there are any exceptions locating or executing the mojo
[ "Entry", "point", "for", "executing", "a", "mojo" ]
train
https://github.com/lotaris/rox-commons-maven-plugin/blob/e2602d7f1e8c2e6994c0df07cc0003828adfa2af/src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java#L73-L112
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newAuthorizationException
public static AuthorizationException newAuthorizationException(Throwable cause, String message, Object... args) { """ Constructs and initializes a new {@link AuthorizationException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link AuthorizationException} was thrown. @param message {@link String} describing the {@link AuthorizationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link AuthorizationException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.security.AuthorizationException """ return new AuthorizationException(format(message, args), cause); }
java
public static AuthorizationException newAuthorizationException(Throwable cause, String message, Object... args) { return new AuthorizationException(format(message, args), cause); }
[ "public", "static", "AuthorizationException", "newAuthorizationException", "(", "Throwable", "cause", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "new", "AuthorizationException", "(", "format", "(", "message", ",", "args", ")", ",", "cause", ")", ";", "}" ]
Constructs and initializes a new {@link AuthorizationException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link AuthorizationException} was thrown. @param message {@link String} describing the {@link AuthorizationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link AuthorizationException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.security.AuthorizationException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "AuthorizationException", "}", "with", "the", "given", "{", "@link", "Throwable", "cause", "}", "and", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L627-L629
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java
Error.classNotMapped
public static void classNotMapped(Object sourceClass, Class<?> configuredClass) { """ Thrown if the sourceClass isn't mapped in configuredClass. @param sourceClass class absent @param configuredClass class that not contains sourceClass """ String sourceName = sourceClass instanceof Class?((Class<?>)sourceClass).getSimpleName():sourceClass.getClass().getSimpleName(); throw new ClassNotMappedException(MSG.INSTANCE.message(classNotMappedException2,sourceName, configuredClass.getSimpleName())); }
java
public static void classNotMapped(Object sourceClass, Class<?> configuredClass){ String sourceName = sourceClass instanceof Class?((Class<?>)sourceClass).getSimpleName():sourceClass.getClass().getSimpleName(); throw new ClassNotMappedException(MSG.INSTANCE.message(classNotMappedException2,sourceName, configuredClass.getSimpleName())); }
[ "public", "static", "void", "classNotMapped", "(", "Object", "sourceClass", ",", "Class", "<", "?", ">", "configuredClass", ")", "{", "String", "sourceName", "=", "sourceClass", "instanceof", "Class", "?", "(", "(", "Class", "<", "?", ">", ")", "sourceClass", ")", ".", "getSimpleName", "(", ")", ":", "sourceClass", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ";", "throw", "new", "ClassNotMappedException", "(", "MSG", ".", "INSTANCE", ".", "message", "(", "classNotMappedException2", ",", "sourceName", ",", "configuredClass", ".", "getSimpleName", "(", ")", ")", ")", ";", "}" ]
Thrown if the sourceClass isn't mapped in configuredClass. @param sourceClass class absent @param configuredClass class that not contains sourceClass
[ "Thrown", "if", "the", "sourceClass", "isn", "t", "mapped", "in", "configuredClass", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L573-L576
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java
LogRecordBrowser.startRecordsInProcess
private OnePidRecordListImpl startRecordsInProcess(long min, long max, IInternalRecordFilter recFilter) { """ list of the records in the process filtered with <code>recFilter</code> """ // Find first file of this process records File file = fileBrowser.findByMillis(min); if (file == null) { file = fileBrowser.findNext((File)null, max); } return new OnePidRecordListMintimeImpl(file, min, max, recFilter); }
java
private OnePidRecordListImpl startRecordsInProcess(long min, long max, IInternalRecordFilter recFilter) { // Find first file of this process records File file = fileBrowser.findByMillis(min); if (file == null) { file = fileBrowser.findNext((File)null, max); } return new OnePidRecordListMintimeImpl(file, min, max, recFilter); }
[ "private", "OnePidRecordListImpl", "startRecordsInProcess", "(", "long", "min", ",", "long", "max", ",", "IInternalRecordFilter", "recFilter", ")", "{", "// Find first file of this process records", "File", "file", "=", "fileBrowser", ".", "findByMillis", "(", "min", ")", ";", "if", "(", "file", "==", "null", ")", "{", "file", "=", "fileBrowser", ".", "findNext", "(", "(", "File", ")", "null", ",", "max", ")", ";", "}", "return", "new", "OnePidRecordListMintimeImpl", "(", "file", ",", "min", ",", "max", ",", "recFilter", ")", ";", "}" ]
list of the records in the process filtered with <code>recFilter</code>
[ "list", "of", "the", "records", "in", "the", "process", "filtered", "with", "<code", ">", "recFilter<", "/", "code", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java#L162-L169
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/PoolGroupSchedulable.java
PoolGroupSchedulable.getPool
public PoolSchedulable getPool(PoolInfo poolInfo) { """ Get a pool, creating it if it does not exist. Note that these pools are never removed. @param poolInfo Pool info used @return Pool that existed or was created """ PoolSchedulable pool = nameToMap.get(poolInfo); if (pool == null) { pool = new PoolSchedulable(poolInfo, getType(), configManager); PoolSchedulable prevPool = nameToMap.putIfAbsent(poolInfo, pool); if (prevPool != null) { pool = prevPool; } } return pool; }
java
public PoolSchedulable getPool(PoolInfo poolInfo) { PoolSchedulable pool = nameToMap.get(poolInfo); if (pool == null) { pool = new PoolSchedulable(poolInfo, getType(), configManager); PoolSchedulable prevPool = nameToMap.putIfAbsent(poolInfo, pool); if (prevPool != null) { pool = prevPool; } } return pool; }
[ "public", "PoolSchedulable", "getPool", "(", "PoolInfo", "poolInfo", ")", "{", "PoolSchedulable", "pool", "=", "nameToMap", ".", "get", "(", "poolInfo", ")", ";", "if", "(", "pool", "==", "null", ")", "{", "pool", "=", "new", "PoolSchedulable", "(", "poolInfo", ",", "getType", "(", ")", ",", "configManager", ")", ";", "PoolSchedulable", "prevPool", "=", "nameToMap", ".", "putIfAbsent", "(", "poolInfo", ",", "pool", ")", ";", "if", "(", "prevPool", "!=", "null", ")", "{", "pool", "=", "prevPool", ";", "}", "}", "return", "pool", ";", "}" ]
Get a pool, creating it if it does not exist. Note that these pools are never removed. @param poolInfo Pool info used @return Pool that existed or was created
[ "Get", "a", "pool", "creating", "it", "if", "it", "does", "not", "exist", ".", "Note", "that", "these", "pools", "are", "never", "removed", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/PoolGroupSchedulable.java#L193-L203
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java
AvatarNode.isPrimaryAlive
private static void isPrimaryAlive(String zkRegistry) throws IOException { """ Tries to bind to the address specified in ZooKeeper, this will always fail if the primary is alive either on the same machine or on a remote machine. """ String parts[] = zkRegistry.split(":"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid Address : " + zkRegistry); } String host = parts[0]; int port = Integer.parseInt(parts[1]); InetSocketAddress clientSocket = new InetSocketAddress(host, port); ServerSocket socket = new ServerSocket(); socket.bind(clientSocket); socket.close(); }
java
private static void isPrimaryAlive(String zkRegistry) throws IOException { String parts[] = zkRegistry.split(":"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid Address : " + zkRegistry); } String host = parts[0]; int port = Integer.parseInt(parts[1]); InetSocketAddress clientSocket = new InetSocketAddress(host, port); ServerSocket socket = new ServerSocket(); socket.bind(clientSocket); socket.close(); }
[ "private", "static", "void", "isPrimaryAlive", "(", "String", "zkRegistry", ")", "throws", "IOException", "{", "String", "parts", "[", "]", "=", "zkRegistry", ".", "split", "(", "\":\"", ")", ";", "if", "(", "parts", ".", "length", "!=", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid Address : \"", "+", "zkRegistry", ")", ";", "}", "String", "host", "=", "parts", "[", "0", "]", ";", "int", "port", "=", "Integer", ".", "parseInt", "(", "parts", "[", "1", "]", ")", ";", "InetSocketAddress", "clientSocket", "=", "new", "InetSocketAddress", "(", "host", ",", "port", ")", ";", "ServerSocket", "socket", "=", "new", "ServerSocket", "(", ")", ";", "socket", ".", "bind", "(", "clientSocket", ")", ";", "socket", ".", "close", "(", ")", ";", "}" ]
Tries to bind to the address specified in ZooKeeper, this will always fail if the primary is alive either on the same machine or on a remote machine.
[ "Tries", "to", "bind", "to", "the", "address", "specified", "in", "ZooKeeper", "this", "will", "always", "fail", "if", "the", "primary", "is", "alive", "either", "on", "the", "same", "machine", "or", "on", "a", "remote", "machine", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java#L1641-L1652
aws/aws-sdk-java
aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/Resource.java
Resource.withTags
public Resource withTags(java.util.Map<String, String> tags) { """ <p> A list of AWS tags associated with a resource at the time the finding was processed. </p> @param tags A list of AWS tags associated with a resource at the time the finding was processed. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public Resource withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "Resource", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> A list of AWS tags associated with a resource at the time the finding was processed. </p> @param tags A list of AWS tags associated with a resource at the time the finding was processed. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "list", "of", "AWS", "tags", "associated", "with", "a", "resource", "at", "the", "time", "the", "finding", "was", "processed", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/Resource.java#L282-L285
nikkiii/embedhttp
src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java
HttpResponse.addHeader
public void addHeader(String key, Object value) { """ Add a header to the response @param key The header name @param value The header value """ List<Object> values = headers.get(key); if (values == null) { headers.put(key, values = new ArrayList<Object>()); } values.add(value); }
java
public void addHeader(String key, Object value) { List<Object> values = headers.get(key); if (values == null) { headers.put(key, values = new ArrayList<Object>()); } values.add(value); }
[ "public", "void", "addHeader", "(", "String", "key", ",", "Object", "value", ")", "{", "List", "<", "Object", ">", "values", "=", "headers", ".", "get", "(", "key", ")", ";", "if", "(", "values", "==", "null", ")", "{", "headers", ".", "put", "(", "key", ",", "values", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ")", ";", "}", "values", ".", "add", "(", "value", ")", ";", "}" ]
Add a header to the response @param key The header name @param value The header value
[ "Add", "a", "header", "to", "the", "response" ]
train
https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java#L135-L141
JodaOrg/joda-time
src/main/java/org/joda/time/convert/DateConverter.java
DateConverter.getInstantMillis
public long getInstantMillis(Object object, Chronology chrono) { """ Gets the millis, which is the Date millis value. @param object the Date to convert, must not be null @param chrono the non-null result of getChronology @return the millisecond value @throws NullPointerException if the object is null @throws ClassCastException if the object is an invalid type """ Date date = (Date) object; return date.getTime(); }
java
public long getInstantMillis(Object object, Chronology chrono) { Date date = (Date) object; return date.getTime(); }
[ "public", "long", "getInstantMillis", "(", "Object", "object", ",", "Chronology", "chrono", ")", "{", "Date", "date", "=", "(", "Date", ")", "object", ";", "return", "date", ".", "getTime", "(", ")", ";", "}" ]
Gets the millis, which is the Date millis value. @param object the Date to convert, must not be null @param chrono the non-null result of getChronology @return the millisecond value @throws NullPointerException if the object is null @throws ClassCastException if the object is an invalid type
[ "Gets", "the", "millis", "which", "is", "the", "Date", "millis", "value", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/convert/DateConverter.java#L54-L57
alkacon/opencms-core
src/org/opencms/workplace/editors/CmsEditor.java
CmsEditor.decodeParamValue
@Override protected String decodeParamValue(String paramName, String paramValue) { """ Decodes an individual parameter value, ensuring the content is always decoded in UTF-8.<p> For editors the content is always encoded using the JavaScript encodeURIComponent() method on the client, which always encodes in UTF-8.<p> @param paramName the name of the parameter @param paramValue the unencoded value of the parameter @return the encoded value of the parameter """ if ((paramName != null) && (paramValue != null)) { if (PARAM_CONTENT.equals(paramName)) { // content will be always encoded in UTF-8 unicode by the editor client return CmsEncoder.decode(paramValue, CmsEncoder.ENCODING_UTF_8); } else if (PARAM_RESOURCE.equals(paramName) || PARAM_TEMPFILE.equals(paramName)) { String filename = CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding()); if (PARAM_TEMPFILE.equals(paramName) || CmsStringUtil.isEmpty(getParamTempfile())) { // always use value from temp file if it is available setFileEncoding(getFileEncoding(getCms(), filename)); } return filename; } else { return CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding()); } } else { return null; } }
java
@Override protected String decodeParamValue(String paramName, String paramValue) { if ((paramName != null) && (paramValue != null)) { if (PARAM_CONTENT.equals(paramName)) { // content will be always encoded in UTF-8 unicode by the editor client return CmsEncoder.decode(paramValue, CmsEncoder.ENCODING_UTF_8); } else if (PARAM_RESOURCE.equals(paramName) || PARAM_TEMPFILE.equals(paramName)) { String filename = CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding()); if (PARAM_TEMPFILE.equals(paramName) || CmsStringUtil.isEmpty(getParamTempfile())) { // always use value from temp file if it is available setFileEncoding(getFileEncoding(getCms(), filename)); } return filename; } else { return CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding()); } } else { return null; } }
[ "@", "Override", "protected", "String", "decodeParamValue", "(", "String", "paramName", ",", "String", "paramValue", ")", "{", "if", "(", "(", "paramName", "!=", "null", ")", "&&", "(", "paramValue", "!=", "null", ")", ")", "{", "if", "(", "PARAM_CONTENT", ".", "equals", "(", "paramName", ")", ")", "{", "// content will be always encoded in UTF-8 unicode by the editor client", "return", "CmsEncoder", ".", "decode", "(", "paramValue", ",", "CmsEncoder", ".", "ENCODING_UTF_8", ")", ";", "}", "else", "if", "(", "PARAM_RESOURCE", ".", "equals", "(", "paramName", ")", "||", "PARAM_TEMPFILE", ".", "equals", "(", "paramName", ")", ")", "{", "String", "filename", "=", "CmsEncoder", ".", "decode", "(", "paramValue", ",", "getCms", "(", ")", ".", "getRequestContext", "(", ")", ".", "getEncoding", "(", ")", ")", ";", "if", "(", "PARAM_TEMPFILE", ".", "equals", "(", "paramName", ")", "||", "CmsStringUtil", ".", "isEmpty", "(", "getParamTempfile", "(", ")", ")", ")", "{", "// always use value from temp file if it is available", "setFileEncoding", "(", "getFileEncoding", "(", "getCms", "(", ")", ",", "filename", ")", ")", ";", "}", "return", "filename", ";", "}", "else", "{", "return", "CmsEncoder", ".", "decode", "(", "paramValue", ",", "getCms", "(", ")", ".", "getRequestContext", "(", ")", ".", "getEncoding", "(", ")", ")", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Decodes an individual parameter value, ensuring the content is always decoded in UTF-8.<p> For editors the content is always encoded using the JavaScript encodeURIComponent() method on the client, which always encodes in UTF-8.<p> @param paramName the name of the parameter @param paramValue the unencoded value of the parameter @return the encoded value of the parameter
[ "Decodes", "an", "individual", "parameter", "value", "ensuring", "the", "content", "is", "always", "decoded", "in", "UTF", "-", "8", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsEditor.java#L876-L896
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/MapOutputFile.java
MapOutputFile.getInputFile
public Path getInputFile(int mapId, TaskAttemptID reduceTaskId) throws IOException { """ Return a local reduce input file created earlier @param mapTaskId a map task id @param reduceTaskId a reduce task id """ // TODO *oom* should use a format here return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir( jobId.toString(), reduceTaskId.toString()) + "/map_" + mapId + ".out", conf); }
java
public Path getInputFile(int mapId, TaskAttemptID reduceTaskId) throws IOException { // TODO *oom* should use a format here return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir( jobId.toString(), reduceTaskId.toString()) + "/map_" + mapId + ".out", conf); }
[ "public", "Path", "getInputFile", "(", "int", "mapId", ",", "TaskAttemptID", "reduceTaskId", ")", "throws", "IOException", "{", "// TODO *oom* should use a format here", "return", "lDirAlloc", ".", "getLocalPathToRead", "(", "TaskTracker", ".", "getIntermediateOutputDir", "(", "jobId", ".", "toString", "(", ")", ",", "reduceTaskId", ".", "toString", "(", ")", ")", "+", "\"/map_\"", "+", "mapId", "+", "\".out\"", ",", "conf", ")", ";", "}" ]
Return a local reduce input file created earlier @param mapTaskId a map task id @param reduceTaskId a reduce task id
[ "Return", "a", "local", "reduce", "input", "file", "created", "earlier" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/MapOutputFile.java#L154-L161
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/trees/GrammaticalStructure.java
GrammaticalStructure.getDependencyPath
public List<String> getDependencyPath(int nodeIndex, int rootIndex) { """ Returns the dependency path as a list of String, from node to root, it is assumed that that root is an ancestor of node @return A list of dependency labels """ TreeGraphNode node = getNodeByIndex(nodeIndex); TreeGraphNode rootTree = getNodeByIndex(rootIndex); return getDependencyPath(node, rootTree); }
java
public List<String> getDependencyPath(int nodeIndex, int rootIndex) { TreeGraphNode node = getNodeByIndex(nodeIndex); TreeGraphNode rootTree = getNodeByIndex(rootIndex); return getDependencyPath(node, rootTree); }
[ "public", "List", "<", "String", ">", "getDependencyPath", "(", "int", "nodeIndex", ",", "int", "rootIndex", ")", "{", "TreeGraphNode", "node", "=", "getNodeByIndex", "(", "nodeIndex", ")", ";", "TreeGraphNode", "rootTree", "=", "getNodeByIndex", "(", "rootIndex", ")", ";", "return", "getDependencyPath", "(", "node", ",", "rootTree", ")", ";", "}" ]
Returns the dependency path as a list of String, from node to root, it is assumed that that root is an ancestor of node @return A list of dependency labels
[ "Returns", "the", "dependency", "path", "as", "a", "list", "of", "String", "from", "node", "to", "root", "it", "is", "assumed", "that", "that", "root", "is", "an", "ancestor", "of", "node" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/GrammaticalStructure.java#L736-L740
meertensinstituut/mtas
src/main/java/mtas/parser/cql/util/MtasCQLParserSentenceCondition.java
MtasCQLParserSentenceCondition.createQuery
private MtasSpanQuery createQuery( List<MtasCQLParserSentenceCondition> sentenceSequence) throws ParseException { """ Creates the query. @param sentenceSequence the sentence sequence @return the mtas span query @throws ParseException the parse exception """ if (sentenceSequence.size() == 1) { if (maximumOccurence > 1) { return new MtasSpanRecurrenceQuery(sentenceSequence.get(0).getQuery(), minimumOccurence, maximumOccurence, ignore, maximumIgnoreLength); } else { return sentenceSequence.get(0).getQuery(); } } else { List<MtasSpanSequenceItem> clauses = new ArrayList<MtasSpanSequenceItem>(); for (MtasCQLParserSentenceCondition sentence : sentenceSequence) { clauses.add( new MtasSpanSequenceItem(sentence.getQuery(), sentence.optional)); } if (maximumOccurence > 1) { return new MtasSpanRecurrenceQuery( new MtasSpanSequenceQuery(clauses, ignore, maximumIgnoreLength), minimumOccurence, maximumOccurence, ignore, maximumIgnoreLength); } else { return new MtasSpanSequenceQuery(clauses, ignore, maximumIgnoreLength); } } }
java
private MtasSpanQuery createQuery( List<MtasCQLParserSentenceCondition> sentenceSequence) throws ParseException { if (sentenceSequence.size() == 1) { if (maximumOccurence > 1) { return new MtasSpanRecurrenceQuery(sentenceSequence.get(0).getQuery(), minimumOccurence, maximumOccurence, ignore, maximumIgnoreLength); } else { return sentenceSequence.get(0).getQuery(); } } else { List<MtasSpanSequenceItem> clauses = new ArrayList<MtasSpanSequenceItem>(); for (MtasCQLParserSentenceCondition sentence : sentenceSequence) { clauses.add( new MtasSpanSequenceItem(sentence.getQuery(), sentence.optional)); } if (maximumOccurence > 1) { return new MtasSpanRecurrenceQuery( new MtasSpanSequenceQuery(clauses, ignore, maximumIgnoreLength), minimumOccurence, maximumOccurence, ignore, maximumIgnoreLength); } else { return new MtasSpanSequenceQuery(clauses, ignore, maximumIgnoreLength); } } }
[ "private", "MtasSpanQuery", "createQuery", "(", "List", "<", "MtasCQLParserSentenceCondition", ">", "sentenceSequence", ")", "throws", "ParseException", "{", "if", "(", "sentenceSequence", ".", "size", "(", ")", "==", "1", ")", "{", "if", "(", "maximumOccurence", ">", "1", ")", "{", "return", "new", "MtasSpanRecurrenceQuery", "(", "sentenceSequence", ".", "get", "(", "0", ")", ".", "getQuery", "(", ")", ",", "minimumOccurence", ",", "maximumOccurence", ",", "ignore", ",", "maximumIgnoreLength", ")", ";", "}", "else", "{", "return", "sentenceSequence", ".", "get", "(", "0", ")", ".", "getQuery", "(", ")", ";", "}", "}", "else", "{", "List", "<", "MtasSpanSequenceItem", ">", "clauses", "=", "new", "ArrayList", "<", "MtasSpanSequenceItem", ">", "(", ")", ";", "for", "(", "MtasCQLParserSentenceCondition", "sentence", ":", "sentenceSequence", ")", "{", "clauses", ".", "add", "(", "new", "MtasSpanSequenceItem", "(", "sentence", ".", "getQuery", "(", ")", ",", "sentence", ".", "optional", ")", ")", ";", "}", "if", "(", "maximumOccurence", ">", "1", ")", "{", "return", "new", "MtasSpanRecurrenceQuery", "(", "new", "MtasSpanSequenceQuery", "(", "clauses", ",", "ignore", ",", "maximumIgnoreLength", ")", ",", "minimumOccurence", ",", "maximumOccurence", ",", "ignore", ",", "maximumIgnoreLength", ")", ";", "}", "else", "{", "return", "new", "MtasSpanSequenceQuery", "(", "clauses", ",", "ignore", ",", "maximumIgnoreLength", ")", ";", "}", "}", "}" ]
Creates the query. @param sentenceSequence the sentence sequence @return the mtas span query @throws ParseException the parse exception
[ "Creates", "the", "query", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/parser/cql/util/MtasCQLParserSentenceCondition.java#L552-L576
wkgcass/Style
src/main/java/net/cassite/style/aggregation/ListFuncSup.java
ListFuncSup.forEach
public <R> R forEach(RFunc1<R, T> func, int index) { """ define a function to deal with each element in the list with given start index @param func a function takes in each element from list and returns last loop value @param index the index where to start iteration @return return 'last loop value'.<br> check <a href="https://github.com/wkgcass/Style/">tutorial</a> for more info about 'last loop value' """ return forEach($(func), index); }
java
public <R> R forEach(RFunc1<R, T> func, int index) { return forEach($(func), index); }
[ "public", "<", "R", ">", "R", "forEach", "(", "RFunc1", "<", "R", ",", "T", ">", "func", ",", "int", "index", ")", "{", "return", "forEach", "(", "$", "(", "func", ")", ",", "index", ")", ";", "}" ]
define a function to deal with each element in the list with given start index @param func a function takes in each element from list and returns last loop value @param index the index where to start iteration @return return 'last loop value'.<br> check <a href="https://github.com/wkgcass/Style/">tutorial</a> for more info about 'last loop value'
[ "define", "a", "function", "to", "deal", "with", "each", "element", "in", "the", "list", "with", "given", "start", "index" ]
train
https://github.com/wkgcass/Style/blob/db3ea64337251f46f734279480e365293bececbd/src/main/java/net/cassite/style/aggregation/ListFuncSup.java#L103-L105
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.asTime
public static <T extends Comparable<?>> TimeExpression<T> asTime(Expression<T> expr) { """ Create a new TimeExpression @param expr the time Expression @return new TimeExpression """ Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new TimePath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new TimeOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new TimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new TimeExpression<T>(underlyingMixin) { private static final long serialVersionUID = -2402288239000668173L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
java
public static <T extends Comparable<?>> TimeExpression<T> asTime(Expression<T> expr) { Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new TimePath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new TimeOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new TimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new TimeExpression<T>(underlyingMixin) { private static final long serialVersionUID = -2402288239000668173L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", ">", ">", "TimeExpression", "<", "T", ">", "asTime", "(", "Expression", "<", "T", ">", "expr", ")", "{", "Expression", "<", "T", ">", "underlyingMixin", "=", "ExpressionUtils", ".", "extract", "(", "expr", ")", ";", "if", "(", "underlyingMixin", "instanceof", "PathImpl", ")", "{", "return", "new", "TimePath", "<", "T", ">", "(", "(", "PathImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "if", "(", "underlyingMixin", "instanceof", "OperationImpl", ")", "{", "return", "new", "TimeOperation", "<", "T", ">", "(", "(", "OperationImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "if", "(", "underlyingMixin", "instanceof", "TemplateExpressionImpl", ")", "{", "return", "new", "TimeTemplate", "<", "T", ">", "(", "(", "TemplateExpressionImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "{", "return", "new", "TimeExpression", "<", "T", ">", "(", "underlyingMixin", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "2402288239000668173L", ";", "@", "Override", "public", "<", "R", ",", "C", ">", "R", "accept", "(", "Visitor", "<", "R", ",", "C", ">", "v", ",", "C", "context", ")", "{", "return", "this", ".", "mixin", ".", "accept", "(", "v", ",", "context", ")", ";", "}", "}", ";", "}", "}" ]
Create a new TimeExpression @param expr the time Expression @return new TimeExpression
[ "Create", "a", "new", "TimeExpression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L2016-L2036
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/LargestBlobCropTransform.java
LargestBlobCropTransform.doTransform
@Override protected ImageWritable doTransform(ImageWritable image, Random random) { """ Takes an image and returns a cropped image based on it's largest blob. @param image to transform, null == end of stream @param random object to use (or null for deterministic) @return transformed image """ if (image == null) { return null; } //Convert image to gray and blur Mat original = converter.convert(image.getFrame()); Mat grayed = new Mat(); cvtColor(original, grayed, CV_BGR2GRAY); if (blurWidth > 0 && blurHeight > 0) blur(grayed, grayed, new Size(blurWidth, blurHeight)); //Get edges from Canny edge detector Mat edgeOut = new Mat(); if (isCanny) Canny(grayed, edgeOut, lowerThresh, upperThresh); else threshold(grayed, edgeOut, lowerThresh, upperThresh, 0); double largestArea = 0; Rect boundingRect = new Rect(); MatVector contours = new MatVector(); Mat hierarchy = new Mat(); findContours(edgeOut, contours, hierarchy, this.mode, this.method); for (int i = 0; i < contours.size(); i++) { // Find the area of contour double area = contourArea(contours.get(i), false); if (area > largestArea) { // Find the bounding rectangle for biggest contour boundingRect = boundingRect(contours.get(i)); } } //Apply crop and return result x = boundingRect.x(); y = boundingRect.y(); Mat result = original.apply(boundingRect); return new ImageWritable(converter.convert(result)); }
java
@Override protected ImageWritable doTransform(ImageWritable image, Random random) { if (image == null) { return null; } //Convert image to gray and blur Mat original = converter.convert(image.getFrame()); Mat grayed = new Mat(); cvtColor(original, grayed, CV_BGR2GRAY); if (blurWidth > 0 && blurHeight > 0) blur(grayed, grayed, new Size(blurWidth, blurHeight)); //Get edges from Canny edge detector Mat edgeOut = new Mat(); if (isCanny) Canny(grayed, edgeOut, lowerThresh, upperThresh); else threshold(grayed, edgeOut, lowerThresh, upperThresh, 0); double largestArea = 0; Rect boundingRect = new Rect(); MatVector contours = new MatVector(); Mat hierarchy = new Mat(); findContours(edgeOut, contours, hierarchy, this.mode, this.method); for (int i = 0; i < contours.size(); i++) { // Find the area of contour double area = contourArea(contours.get(i), false); if (area > largestArea) { // Find the bounding rectangle for biggest contour boundingRect = boundingRect(contours.get(i)); } } //Apply crop and return result x = boundingRect.x(); y = boundingRect.y(); Mat result = original.apply(boundingRect); return new ImageWritable(converter.convert(result)); }
[ "@", "Override", "protected", "ImageWritable", "doTransform", "(", "ImageWritable", "image", ",", "Random", "random", ")", "{", "if", "(", "image", "==", "null", ")", "{", "return", "null", ";", "}", "//Convert image to gray and blur", "Mat", "original", "=", "converter", ".", "convert", "(", "image", ".", "getFrame", "(", ")", ")", ";", "Mat", "grayed", "=", "new", "Mat", "(", ")", ";", "cvtColor", "(", "original", ",", "grayed", ",", "CV_BGR2GRAY", ")", ";", "if", "(", "blurWidth", ">", "0", "&&", "blurHeight", ">", "0", ")", "blur", "(", "grayed", ",", "grayed", ",", "new", "Size", "(", "blurWidth", ",", "blurHeight", ")", ")", ";", "//Get edges from Canny edge detector", "Mat", "edgeOut", "=", "new", "Mat", "(", ")", ";", "if", "(", "isCanny", ")", "Canny", "(", "grayed", ",", "edgeOut", ",", "lowerThresh", ",", "upperThresh", ")", ";", "else", "threshold", "(", "grayed", ",", "edgeOut", ",", "lowerThresh", ",", "upperThresh", ",", "0", ")", ";", "double", "largestArea", "=", "0", ";", "Rect", "boundingRect", "=", "new", "Rect", "(", ")", ";", "MatVector", "contours", "=", "new", "MatVector", "(", ")", ";", "Mat", "hierarchy", "=", "new", "Mat", "(", ")", ";", "findContours", "(", "edgeOut", ",", "contours", ",", "hierarchy", ",", "this", ".", "mode", ",", "this", ".", "method", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "contours", ".", "size", "(", ")", ";", "i", "++", ")", "{", "// Find the area of contour", "double", "area", "=", "contourArea", "(", "contours", ".", "get", "(", "i", ")", ",", "false", ")", ";", "if", "(", "area", ">", "largestArea", ")", "{", "// Find the bounding rectangle for biggest contour", "boundingRect", "=", "boundingRect", "(", "contours", ".", "get", "(", "i", ")", ")", ";", "}", "}", "//Apply crop and return result", "x", "=", "boundingRect", ".", "x", "(", ")", ";", "y", "=", "boundingRect", ".", "y", "(", ")", ";", "Mat", "result", "=", "original", ".", "apply", "(", "boundingRect", ")", ";", "return", "new", "ImageWritable", "(", "converter", ".", "convert", "(", "result", ")", ")", ";", "}" ]
Takes an image and returns a cropped image based on it's largest blob. @param image to transform, null == end of stream @param random object to use (or null for deterministic) @return transformed image
[ "Takes", "an", "image", "and", "returns", "a", "cropped", "image", "based", "on", "it", "s", "largest", "blob", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/LargestBlobCropTransform.java#L94-L137
thorinii/lct
src/main/java/me/lachlanap/lct/data/ClassInspector.java
ClassInspector.processField
protected ConstantField processField(Class<?> aClass, Field field) { """ Converts a field/potential-constant into a ConstantField. Returns null if the field cannot be constant. Override this to change how fields are processed. @param aClass the class the field came from @param field the field @return a ConstantField or null """ Constant annot = field.getAnnotation(Constant.class); if (annot != null) { return factory.createConstantField(aClass, field.getName(), annot); } return null; }
java
protected ConstantField processField(Class<?> aClass, Field field) { Constant annot = field.getAnnotation(Constant.class); if (annot != null) { return factory.createConstantField(aClass, field.getName(), annot); } return null; }
[ "protected", "ConstantField", "processField", "(", "Class", "<", "?", ">", "aClass", ",", "Field", "field", ")", "{", "Constant", "annot", "=", "field", ".", "getAnnotation", "(", "Constant", ".", "class", ")", ";", "if", "(", "annot", "!=", "null", ")", "{", "return", "factory", ".", "createConstantField", "(", "aClass", ",", "field", ".", "getName", "(", ")", ",", "annot", ")", ";", "}", "return", "null", ";", "}" ]
Converts a field/potential-constant into a ConstantField. Returns null if the field cannot be constant. Override this to change how fields are processed. @param aClass the class the field came from @param field the field @return a ConstantField or null
[ "Converts", "a", "field", "/", "potential", "-", "constant", "into", "a", "ConstantField", ".", "Returns", "null", "if", "the", "field", "cannot", "be", "constant", ".", "Override", "this", "to", "change", "how", "fields", "are", "processed", "." ]
train
https://github.com/thorinii/lct/blob/83d9dd94aac1efec4815b5658faa395a081592dc/src/main/java/me/lachlanap/lct/data/ClassInspector.java#L69-L76
Azure/azure-sdk-for-java
cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java
BingCustomInstancesImpl.imageSearch
public Images imageSearch(long customConfig, String query, ImageSearchOptionalParameter imageSearchOptionalParameter) { """ The Custom Image Search API lets you send an image search query to Bing and get image results found in your custom view of the web. @param customConfig The identifier for the custom search configuration @param query The user's search query term. The term cannot be empty. The term may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help improve relevance of an insights query (see [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)), you should always include the user's query term. Use this parameter only with the Image Search API.Do not specify this parameter when calling the Trending Images API. @param imageSearchOptionalParameter the object representing the optional parameters to be set before calling this API @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 Images object if successful. """ return imageSearchWithServiceResponseAsync(customConfig, query, imageSearchOptionalParameter).toBlocking().single().body(); }
java
public Images imageSearch(long customConfig, String query, ImageSearchOptionalParameter imageSearchOptionalParameter) { return imageSearchWithServiceResponseAsync(customConfig, query, imageSearchOptionalParameter).toBlocking().single().body(); }
[ "public", "Images", "imageSearch", "(", "long", "customConfig", ",", "String", "query", ",", "ImageSearchOptionalParameter", "imageSearchOptionalParameter", ")", "{", "return", "imageSearchWithServiceResponseAsync", "(", "customConfig", ",", "query", ",", "imageSearchOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
The Custom Image Search API lets you send an image search query to Bing and get image results found in your custom view of the web. @param customConfig The identifier for the custom search configuration @param query The user's search query term. The term cannot be empty. The term may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help improve relevance of an insights query (see [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)), you should always include the user's query term. Use this parameter only with the Image Search API.Do not specify this parameter when calling the Trending Images API. @param imageSearchOptionalParameter the object representing the optional parameters to be set before calling this API @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 Images object if successful.
[ "The", "Custom", "Image", "Search", "API", "lets", "you", "send", "an", "image", "search", "query", "to", "Bing", "and", "get", "image", "results", "found", "in", "your", "custom", "view", "of", "the", "web", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java#L82-L84
allengeorge/libraft
libraft-agent/src/main/java/io/libraft/agent/RaftAgent.java
RaftAgent.fromConfigurationFile
public static RaftAgent fromConfigurationFile(String configFile, RaftListener raftListener) throws IOException { """ Create an instance of {@code RaftAgent} from a configuration file. @param configFile location of the JSON configuration file. The configuration in this file will be validated. See the project README.md for more on the configuration file @param raftListener instance of {@code RaftListener} that will be notified of events from the Raft cluster @return valid {@code RaftAgent} that can be used to connect to, and (if leader), replicate {@link Command} instances to the Raft cluster @throws IOException if the configuration file cannot be loaded or processed (i.e. contains invalid JSON) """ RaftConfiguration configuration = RaftConfigurationLoader.loadFromFile(configFile); return fromConfigurationObject(configuration, raftListener); }
java
public static RaftAgent fromConfigurationFile(String configFile, RaftListener raftListener) throws IOException { RaftConfiguration configuration = RaftConfigurationLoader.loadFromFile(configFile); return fromConfigurationObject(configuration, raftListener); }
[ "public", "static", "RaftAgent", "fromConfigurationFile", "(", "String", "configFile", ",", "RaftListener", "raftListener", ")", "throws", "IOException", "{", "RaftConfiguration", "configuration", "=", "RaftConfigurationLoader", ".", "loadFromFile", "(", "configFile", ")", ";", "return", "fromConfigurationObject", "(", "configuration", ",", "raftListener", ")", ";", "}" ]
Create an instance of {@code RaftAgent} from a configuration file. @param configFile location of the JSON configuration file. The configuration in this file will be validated. See the project README.md for more on the configuration file @param raftListener instance of {@code RaftListener} that will be notified of events from the Raft cluster @return valid {@code RaftAgent} that can be used to connect to, and (if leader), replicate {@link Command} instances to the Raft cluster @throws IOException if the configuration file cannot be loaded or processed (i.e. contains invalid JSON)
[ "Create", "an", "instance", "of", "{", "@code", "RaftAgent", "}", "from", "a", "configuration", "file", "." ]
train
https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-agent/src/main/java/io/libraft/agent/RaftAgent.java#L141-L144
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/converters/StringToClassInstance.java
StringToClassInstance.decode
@Override public T decode(final String s) { """ Constructs a new instance of {@code T} by invoking its single-string constructor. @param s the string to convert from @return a new instance of {@code T}, instantiated as though {@code new T(s)} had been invoked @throws ConversionException if the constructor isn't accessible, {@code T} isn't a concrete type, an exception is thrown by {@code T}'s constructor, or an exception is thrown when loading {@code T} or one of its dependency classes @throws NullPointerException if {@code s} is null """ checkNotNull(s); try { return constructor.newInstance(s); } catch (final IllegalAccessException iae) { throw new ConversionException("Cannot access a single-string constructor for type " + type, iae); } catch (final InstantiationException ie) { throw new ConversionException( "Cannot instantiate " + type + ", probably because it is not concrete", ie); } catch (final InvocationTargetException ite) { throw new ConversionException("Exception thrown in constructor for " + type, ite); } catch (final ExceptionInInitializerError eiie) { throw new ConversionException( "Exception thrown when initializing classes for construction of " + type, eiie); } }
java
@Override public T decode(final String s) { checkNotNull(s); try { return constructor.newInstance(s); } catch (final IllegalAccessException iae) { throw new ConversionException("Cannot access a single-string constructor for type " + type, iae); } catch (final InstantiationException ie) { throw new ConversionException( "Cannot instantiate " + type + ", probably because it is not concrete", ie); } catch (final InvocationTargetException ite) { throw new ConversionException("Exception thrown in constructor for " + type, ite); } catch (final ExceptionInInitializerError eiie) { throw new ConversionException( "Exception thrown when initializing classes for construction of " + type, eiie); } }
[ "@", "Override", "public", "T", "decode", "(", "final", "String", "s", ")", "{", "checkNotNull", "(", "s", ")", ";", "try", "{", "return", "constructor", ".", "newInstance", "(", "s", ")", ";", "}", "catch", "(", "final", "IllegalAccessException", "iae", ")", "{", "throw", "new", "ConversionException", "(", "\"Cannot access a single-string constructor for type \"", "+", "type", ",", "iae", ")", ";", "}", "catch", "(", "final", "InstantiationException", "ie", ")", "{", "throw", "new", "ConversionException", "(", "\"Cannot instantiate \"", "+", "type", "+", "\", probably because it is not concrete\"", ",", "ie", ")", ";", "}", "catch", "(", "final", "InvocationTargetException", "ite", ")", "{", "throw", "new", "ConversionException", "(", "\"Exception thrown in constructor for \"", "+", "type", ",", "ite", ")", ";", "}", "catch", "(", "final", "ExceptionInInitializerError", "eiie", ")", "{", "throw", "new", "ConversionException", "(", "\"Exception thrown when initializing classes for construction of \"", "+", "type", ",", "eiie", ")", ";", "}", "}" ]
Constructs a new instance of {@code T} by invoking its single-string constructor. @param s the string to convert from @return a new instance of {@code T}, instantiated as though {@code new T(s)} had been invoked @throws ConversionException if the constructor isn't accessible, {@code T} isn't a concrete type, an exception is thrown by {@code T}'s constructor, or an exception is thrown when loading {@code T} or one of its dependency classes @throws NullPointerException if {@code s} is null
[ "Constructs", "a", "new", "instance", "of", "{", "@code", "T", "}", "by", "invoking", "its", "single", "-", "string", "constructor", "." ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/converters/StringToClassInstance.java#L58-L75
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/MethodUtils.java
MethodUtils.invokeSetter
public static void invokeSetter(Object object, String setterName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { """ Sets the value of a bean property to an Object. @param object the bean to change @param setterName the property name or setter method name @param args use this arguments @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception """ int index = setterName.indexOf('.'); if (index > 0) { String getterName = setterName.substring(0, index); Object o = invokeGetter(object, getterName); invokeSetter(o, setterName.substring(index + 1), args); } else { if (!setterName.startsWith("set")) { setterName = "set" + setterName.substring(0, 1).toUpperCase(Locale.US) + setterName.substring(1); } invokeMethod(object, setterName, args); } }
java
public static void invokeSetter(Object object, String setterName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { int index = setterName.indexOf('.'); if (index > 0) { String getterName = setterName.substring(0, index); Object o = invokeGetter(object, getterName); invokeSetter(o, setterName.substring(index + 1), args); } else { if (!setterName.startsWith("set")) { setterName = "set" + setterName.substring(0, 1).toUpperCase(Locale.US) + setterName.substring(1); } invokeMethod(object, setterName, args); } }
[ "public", "static", "void", "invokeSetter", "(", "Object", "object", ",", "String", "setterName", ",", "Object", "[", "]", "args", ")", "throws", "NoSuchMethodException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "int", "index", "=", "setterName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "index", ">", "0", ")", "{", "String", "getterName", "=", "setterName", ".", "substring", "(", "0", ",", "index", ")", ";", "Object", "o", "=", "invokeGetter", "(", "object", ",", "getterName", ")", ";", "invokeSetter", "(", "o", ",", "setterName", ".", "substring", "(", "index", "+", "1", ")", ",", "args", ")", ";", "}", "else", "{", "if", "(", "!", "setterName", ".", "startsWith", "(", "\"set\"", ")", ")", "{", "setterName", "=", "\"set\"", "+", "setterName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", "Locale", ".", "US", ")", "+", "setterName", ".", "substring", "(", "1", ")", ";", "}", "invokeMethod", "(", "object", ",", "setterName", ",", "args", ")", ";", "}", "}" ]
Sets the value of a bean property to an Object. @param object the bean to change @param setterName the property name or setter method name @param args use this arguments @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception
[ "Sets", "the", "value", "of", "a", "bean", "property", "to", "an", "Object", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L69-L82
phax/ph-masterdata
ph-masterdata/src/main/java/com/helger/masterdata/price/Price.java
Price.createFromGrossAmount
@Nonnull public static Price createFromGrossAmount (@Nonnull final ICurrencyValue aGrossAmount, @Nonnull final IVATItem aVATItem, @Nonnegative final int nScale, @Nonnull final RoundingMode eRoundingMode) { """ Create a price from a gross amount. @param aGrossAmount The gross amount to use. May not be <code>null</code>. @param aVATItem The VAT item to use. May not be <code>null</code>. @param nScale The scaling to be used for the resulting amount, in case <code>grossAmount / (1 + perc/100)</code> delivery an inexact result. @param eRoundingMode The rounding mode to be used to create a valid result. @return The created {@link Price} """ ValueEnforcer.notNull (aVATItem, "VATItem"); final BigDecimal aFactor = aVATItem.getMultiplicationFactorNetToGross (); if (MathHelper.isEQ1 (aFactor)) { // Shortcut for no VAT (net == gross) return new Price (aGrossAmount, aVATItem); } return new Price (aGrossAmount.getCurrency (), aGrossAmount.getValue ().divide (aFactor, nScale, eRoundingMode), aVATItem); }
java
@Nonnull public static Price createFromGrossAmount (@Nonnull final ICurrencyValue aGrossAmount, @Nonnull final IVATItem aVATItem, @Nonnegative final int nScale, @Nonnull final RoundingMode eRoundingMode) { ValueEnforcer.notNull (aVATItem, "VATItem"); final BigDecimal aFactor = aVATItem.getMultiplicationFactorNetToGross (); if (MathHelper.isEQ1 (aFactor)) { // Shortcut for no VAT (net == gross) return new Price (aGrossAmount, aVATItem); } return new Price (aGrossAmount.getCurrency (), aGrossAmount.getValue ().divide (aFactor, nScale, eRoundingMode), aVATItem); }
[ "@", "Nonnull", "public", "static", "Price", "createFromGrossAmount", "(", "@", "Nonnull", "final", "ICurrencyValue", "aGrossAmount", ",", "@", "Nonnull", "final", "IVATItem", "aVATItem", ",", "@", "Nonnegative", "final", "int", "nScale", ",", "@", "Nonnull", "final", "RoundingMode", "eRoundingMode", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aVATItem", ",", "\"VATItem\"", ")", ";", "final", "BigDecimal", "aFactor", "=", "aVATItem", ".", "getMultiplicationFactorNetToGross", "(", ")", ";", "if", "(", "MathHelper", ".", "isEQ1", "(", "aFactor", ")", ")", "{", "// Shortcut for no VAT (net == gross)", "return", "new", "Price", "(", "aGrossAmount", ",", "aVATItem", ")", ";", "}", "return", "new", "Price", "(", "aGrossAmount", ".", "getCurrency", "(", ")", ",", "aGrossAmount", ".", "getValue", "(", ")", ".", "divide", "(", "aFactor", ",", "nScale", ",", "eRoundingMode", ")", ",", "aVATItem", ")", ";", "}" ]
Create a price from a gross amount. @param aGrossAmount The gross amount to use. May not be <code>null</code>. @param aVATItem The VAT item to use. May not be <code>null</code>. @param nScale The scaling to be used for the resulting amount, in case <code>grossAmount / (1 + perc/100)</code> delivery an inexact result. @param eRoundingMode The rounding mode to be used to create a valid result. @return The created {@link Price}
[ "Create", "a", "price", "from", "a", "gross", "amount", "." ]
train
https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/price/Price.java#L344-L362
peholmst/vaadin4spring
extensions/core/src/main/java/org/vaadin/spring/util/ClassUtils.java
ClassUtils.visitClassHierarchy
public static void visitClassHierarchy(ClassVisitor visitor, Class<?> subClass) { """ Visits the entire class hierarchy from {@code subClass} to {@code Object}. @param visitor the visitor to use, must not be {@code null}. @param subClass the class whose hierarchy is to be visited, must not be {@code null}. """ Class<?> visitedClass = subClass; while (visitedClass.getSuperclass() != null) { visitor.visit(visitedClass); visitedClass = visitedClass.getSuperclass(); } }
java
public static void visitClassHierarchy(ClassVisitor visitor, Class<?> subClass) { Class<?> visitedClass = subClass; while (visitedClass.getSuperclass() != null) { visitor.visit(visitedClass); visitedClass = visitedClass.getSuperclass(); } }
[ "public", "static", "void", "visitClassHierarchy", "(", "ClassVisitor", "visitor", ",", "Class", "<", "?", ">", "subClass", ")", "{", "Class", "<", "?", ">", "visitedClass", "=", "subClass", ";", "while", "(", "visitedClass", ".", "getSuperclass", "(", ")", "!=", "null", ")", "{", "visitor", ".", "visit", "(", "visitedClass", ")", ";", "visitedClass", "=", "visitedClass", ".", "getSuperclass", "(", ")", ";", "}", "}" ]
Visits the entire class hierarchy from {@code subClass} to {@code Object}. @param visitor the visitor to use, must not be {@code null}. @param subClass the class whose hierarchy is to be visited, must not be {@code null}.
[ "Visits", "the", "entire", "class", "hierarchy", "from", "{", "@code", "subClass", "}", "to", "{", "@code", "Object", "}", "." ]
train
https://github.com/peholmst/vaadin4spring/blob/ea896012f15d6abea6e6391def9a0001113a1f7a/extensions/core/src/main/java/org/vaadin/spring/util/ClassUtils.java#L41-L47
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/ResponseHandler.java
ResponseHandler.scheduleForRetry
private void scheduleForRetry(final CouchbaseRequest request, final boolean isNotMyVbucket) { """ Helper method which schedules the given {@link CouchbaseRequest} with a delay for further retry. @param request the request to retry. """ CoreEnvironment env = environment; long delayTime; TimeUnit delayUnit; if (request.retryDelay() != null) { Delay delay = request.retryDelay(); if (request.retryCount() == 0) { delayTime = request.retryAfter(); request.incrementRetryCount(); } else { delayTime = delay.calculate(request.incrementRetryCount()); } delayUnit = delay.unit(); if (request.maxRetryDuration() != 0 && ((System.currentTimeMillis()) + delayTime) > request.maxRetryDuration()) { request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling " + "instead of retrying as the maximum retry duration specified by Server has been exceeded")); return; } } else { Delay delay = env.retryDelay(); if (isNotMyVbucket) { boolean hasFastForward = bucketHasFastForwardMap(request.bucket(), configurationProvider.config()); delayTime = request.incrementRetryCount() == 0 && hasFastForward ? 0 : nmvbRetryDelay; delayUnit = TimeUnit.MILLISECONDS; } else { delayTime = delay.calculate(request.incrementRetryCount()); delayUnit = delay.unit(); } } if (traceLoggingEnabled) { LOGGER.trace("Retrying {} with a delay of {} {}", request, delayTime, delayUnit); } final Scheduler.Worker worker = env.scheduler().createWorker(); worker.schedule(new Action0() { @Override public void call() { try { cluster.send(request); } finally { worker.unsubscribe(); } } }, delayTime, delayUnit); }
java
private void scheduleForRetry(final CouchbaseRequest request, final boolean isNotMyVbucket) { CoreEnvironment env = environment; long delayTime; TimeUnit delayUnit; if (request.retryDelay() != null) { Delay delay = request.retryDelay(); if (request.retryCount() == 0) { delayTime = request.retryAfter(); request.incrementRetryCount(); } else { delayTime = delay.calculate(request.incrementRetryCount()); } delayUnit = delay.unit(); if (request.maxRetryDuration() != 0 && ((System.currentTimeMillis()) + delayTime) > request.maxRetryDuration()) { request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling " + "instead of retrying as the maximum retry duration specified by Server has been exceeded")); return; } } else { Delay delay = env.retryDelay(); if (isNotMyVbucket) { boolean hasFastForward = bucketHasFastForwardMap(request.bucket(), configurationProvider.config()); delayTime = request.incrementRetryCount() == 0 && hasFastForward ? 0 : nmvbRetryDelay; delayUnit = TimeUnit.MILLISECONDS; } else { delayTime = delay.calculate(request.incrementRetryCount()); delayUnit = delay.unit(); } } if (traceLoggingEnabled) { LOGGER.trace("Retrying {} with a delay of {} {}", request, delayTime, delayUnit); } final Scheduler.Worker worker = env.scheduler().createWorker(); worker.schedule(new Action0() { @Override public void call() { try { cluster.send(request); } finally { worker.unsubscribe(); } } }, delayTime, delayUnit); }
[ "private", "void", "scheduleForRetry", "(", "final", "CouchbaseRequest", "request", ",", "final", "boolean", "isNotMyVbucket", ")", "{", "CoreEnvironment", "env", "=", "environment", ";", "long", "delayTime", ";", "TimeUnit", "delayUnit", ";", "if", "(", "request", ".", "retryDelay", "(", ")", "!=", "null", ")", "{", "Delay", "delay", "=", "request", ".", "retryDelay", "(", ")", ";", "if", "(", "request", ".", "retryCount", "(", ")", "==", "0", ")", "{", "delayTime", "=", "request", ".", "retryAfter", "(", ")", ";", "request", ".", "incrementRetryCount", "(", ")", ";", "}", "else", "{", "delayTime", "=", "delay", ".", "calculate", "(", "request", ".", "incrementRetryCount", "(", ")", ")", ";", "}", "delayUnit", "=", "delay", ".", "unit", "(", ")", ";", "if", "(", "request", ".", "maxRetryDuration", "(", ")", "!=", "0", "&&", "(", "(", "System", ".", "currentTimeMillis", "(", ")", ")", "+", "delayTime", ")", ">", "request", ".", "maxRetryDuration", "(", ")", ")", "{", "request", ".", "observable", "(", ")", ".", "onError", "(", "new", "RequestCancelledException", "(", "\"Could not dispatch request, cancelling \"", "+", "\"instead of retrying as the maximum retry duration specified by Server has been exceeded\"", ")", ")", ";", "return", ";", "}", "}", "else", "{", "Delay", "delay", "=", "env", ".", "retryDelay", "(", ")", ";", "if", "(", "isNotMyVbucket", ")", "{", "boolean", "hasFastForward", "=", "bucketHasFastForwardMap", "(", "request", ".", "bucket", "(", ")", ",", "configurationProvider", ".", "config", "(", ")", ")", ";", "delayTime", "=", "request", ".", "incrementRetryCount", "(", ")", "==", "0", "&&", "hasFastForward", "?", "0", ":", "nmvbRetryDelay", ";", "delayUnit", "=", "TimeUnit", ".", "MILLISECONDS", ";", "}", "else", "{", "delayTime", "=", "delay", ".", "calculate", "(", "request", ".", "incrementRetryCount", "(", ")", ")", ";", "delayUnit", "=", "delay", ".", "unit", "(", ")", ";", "}", "}", "if", "(", "traceLoggingEnabled", ")", "{", "LOGGER", ".", "trace", "(", "\"Retrying {} with a delay of {} {}\"", ",", "request", ",", "delayTime", ",", "delayUnit", ")", ";", "}", "final", "Scheduler", ".", "Worker", "worker", "=", "env", ".", "scheduler", "(", ")", ".", "createWorker", "(", ")", ";", "worker", ".", "schedule", "(", "new", "Action0", "(", ")", "{", "@", "Override", "public", "void", "call", "(", ")", "{", "try", "{", "cluster", ".", "send", "(", "request", ")", ";", "}", "finally", "{", "worker", ".", "unsubscribe", "(", ")", ";", "}", "}", "}", ",", "delayTime", ",", "delayUnit", ")", ";", "}" ]
Helper method which schedules the given {@link CouchbaseRequest} with a delay for further retry. @param request the request to retry.
[ "Helper", "method", "which", "schedules", "the", "given", "{", "@link", "CouchbaseRequest", "}", "with", "a", "delay", "for", "further", "retry", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/ResponseHandler.java#L175-L221
landawn/AbacusUtil
src/com/landawn/abacus/util/SQLExecutor.java
SQLExecutor.streamAll
@SafeVarargs public final <T> Stream<T> streamAll(final Class<T> targetClass, final List<String> sqls, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { """ Remember to close the returned <code>Stream</code> list to close the underlying <code>ResultSet</code> list. {@code stream} operation won't be part of transaction or use the connection created by {@code Transaction} even it's in transaction block/range. @param sqls @param statementSetter @param jdbcSettings @param parameters @return """ final JdbcUtil.BiRecordGetter<T, RuntimeException> biRecordGetter = BiRecordGetter.to(targetClass); return streamAll(sqls, statementSetter, biRecordGetter, jdbcSettings, parameters); }
java
@SafeVarargs public final <T> Stream<T> streamAll(final Class<T> targetClass, final List<String> sqls, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { final JdbcUtil.BiRecordGetter<T, RuntimeException> biRecordGetter = BiRecordGetter.to(targetClass); return streamAll(sqls, statementSetter, biRecordGetter, jdbcSettings, parameters); }
[ "@", "SafeVarargs", "public", "final", "<", "T", ">", "Stream", "<", "T", ">", "streamAll", "(", "final", "Class", "<", "T", ">", "targetClass", ",", "final", "List", "<", "String", ">", "sqls", ",", "final", "StatementSetter", "statementSetter", ",", "final", "JdbcSettings", "jdbcSettings", ",", "final", "Object", "...", "parameters", ")", "{", "final", "JdbcUtil", ".", "BiRecordGetter", "<", "T", ",", "RuntimeException", ">", "biRecordGetter", "=", "BiRecordGetter", ".", "to", "(", "targetClass", ")", ";", "return", "streamAll", "(", "sqls", ",", "statementSetter", ",", "biRecordGetter", ",", "jdbcSettings", ",", "parameters", ")", ";", "}" ]
Remember to close the returned <code>Stream</code> list to close the underlying <code>ResultSet</code> list. {@code stream} operation won't be part of transaction or use the connection created by {@code Transaction} even it's in transaction block/range. @param sqls @param statementSetter @param jdbcSettings @param parameters @return
[ "Remember", "to", "close", "the", "returned", "<code", ">", "Stream<", "/", "code", ">", "list", "to", "close", "the", "underlying", "<code", ">", "ResultSet<", "/", "code", ">", "list", ".", "{", "@code", "stream", "}", "operation", "won", "t", "be", "part", "of", "transaction", "or", "use", "the", "connection", "created", "by", "{", "@code", "Transaction", "}", "even", "it", "s", "in", "transaction", "block", "/", "range", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/SQLExecutor.java#L2959-L2965
alkacon/opencms-core
src/org/opencms/ui/components/CmsResourceInfo.java
CmsResourceInfo.createSitemapResourceInfo
public static CmsResourceInfo createSitemapResourceInfo(CmsResource resource, CmsSite baseSite) { """ Creates a resource info widget for a resource that looks like the sitemap entry for that resource.<p> @param resource the resource @param baseSite the base site @return the resource info widget """ String title = resource.getName(); String path = resource.getRootPath(); CmsResourceInfo info = new CmsResourceInfo(); CmsResourceUtil resUtil = new CmsResourceUtil(A_CmsUI.getCmsObject(), resource); CmsObject cms = A_CmsUI.getCmsObject(); try { Map<String, CmsProperty> props = CmsProperty.toObjectMap(cms.readPropertyObjects(resource, false)); CmsProperty navtextProp = props.get(CmsPropertyDefinition.PROPERTY_NAVTEXT); CmsProperty titleProp = props.get(CmsPropertyDefinition.PROPERTY_TITLE); if ((navtextProp != null) && (navtextProp.getValue() != null)) { title = navtextProp.getValue(); } else if ((titleProp != null) && (titleProp.getValue() != null)) { title = titleProp.getValue(); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } info.getTopLine().setValue(title); if (baseSite != null) { String siteRoot = baseSite.getSiteRoot(); if (path.startsWith(siteRoot)) { path = path.substring(siteRoot.length()); path = CmsStringUtil.joinPaths("/", path); } } info.getBottomLine().setValue(path); Resource icon = CmsResourceIcon.getSitemapResourceIcon( A_CmsUI.getCmsObject(), resUtil.getResource(), IconMode.localeCompare); info.getResourceIcon().initContent(resUtil, icon, null, true, false); return info; }
java
public static CmsResourceInfo createSitemapResourceInfo(CmsResource resource, CmsSite baseSite) { String title = resource.getName(); String path = resource.getRootPath(); CmsResourceInfo info = new CmsResourceInfo(); CmsResourceUtil resUtil = new CmsResourceUtil(A_CmsUI.getCmsObject(), resource); CmsObject cms = A_CmsUI.getCmsObject(); try { Map<String, CmsProperty> props = CmsProperty.toObjectMap(cms.readPropertyObjects(resource, false)); CmsProperty navtextProp = props.get(CmsPropertyDefinition.PROPERTY_NAVTEXT); CmsProperty titleProp = props.get(CmsPropertyDefinition.PROPERTY_TITLE); if ((navtextProp != null) && (navtextProp.getValue() != null)) { title = navtextProp.getValue(); } else if ((titleProp != null) && (titleProp.getValue() != null)) { title = titleProp.getValue(); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } info.getTopLine().setValue(title); if (baseSite != null) { String siteRoot = baseSite.getSiteRoot(); if (path.startsWith(siteRoot)) { path = path.substring(siteRoot.length()); path = CmsStringUtil.joinPaths("/", path); } } info.getBottomLine().setValue(path); Resource icon = CmsResourceIcon.getSitemapResourceIcon( A_CmsUI.getCmsObject(), resUtil.getResource(), IconMode.localeCompare); info.getResourceIcon().initContent(resUtil, icon, null, true, false); return info; }
[ "public", "static", "CmsResourceInfo", "createSitemapResourceInfo", "(", "CmsResource", "resource", ",", "CmsSite", "baseSite", ")", "{", "String", "title", "=", "resource", ".", "getName", "(", ")", ";", "String", "path", "=", "resource", ".", "getRootPath", "(", ")", ";", "CmsResourceInfo", "info", "=", "new", "CmsResourceInfo", "(", ")", ";", "CmsResourceUtil", "resUtil", "=", "new", "CmsResourceUtil", "(", "A_CmsUI", ".", "getCmsObject", "(", ")", ",", "resource", ")", ";", "CmsObject", "cms", "=", "A_CmsUI", ".", "getCmsObject", "(", ")", ";", "try", "{", "Map", "<", "String", ",", "CmsProperty", ">", "props", "=", "CmsProperty", ".", "toObjectMap", "(", "cms", ".", "readPropertyObjects", "(", "resource", ",", "false", ")", ")", ";", "CmsProperty", "navtextProp", "=", "props", ".", "get", "(", "CmsPropertyDefinition", ".", "PROPERTY_NAVTEXT", ")", ";", "CmsProperty", "titleProp", "=", "props", ".", "get", "(", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ")", ";", "if", "(", "(", "navtextProp", "!=", "null", ")", "&&", "(", "navtextProp", ".", "getValue", "(", ")", "!=", "null", ")", ")", "{", "title", "=", "navtextProp", ".", "getValue", "(", ")", ";", "}", "else", "if", "(", "(", "titleProp", "!=", "null", ")", "&&", "(", "titleProp", ".", "getValue", "(", ")", "!=", "null", ")", ")", "{", "title", "=", "titleProp", ".", "getValue", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "info", ".", "getTopLine", "(", ")", ".", "setValue", "(", "title", ")", ";", "if", "(", "baseSite", "!=", "null", ")", "{", "String", "siteRoot", "=", "baseSite", ".", "getSiteRoot", "(", ")", ";", "if", "(", "path", ".", "startsWith", "(", "siteRoot", ")", ")", "{", "path", "=", "path", ".", "substring", "(", "siteRoot", ".", "length", "(", ")", ")", ";", "path", "=", "CmsStringUtil", ".", "joinPaths", "(", "\"/\"", ",", "path", ")", ";", "}", "}", "info", ".", "getBottomLine", "(", ")", ".", "setValue", "(", "path", ")", ";", "Resource", "icon", "=", "CmsResourceIcon", ".", "getSitemapResourceIcon", "(", "A_CmsUI", ".", "getCmsObject", "(", ")", ",", "resUtil", ".", "getResource", "(", ")", ",", "IconMode", ".", "localeCompare", ")", ";", "info", ".", "getResourceIcon", "(", ")", ".", "initContent", "(", "resUtil", ",", "icon", ",", "null", ",", "true", ",", "false", ")", ";", "return", "info", ";", "}" ]
Creates a resource info widget for a resource that looks like the sitemap entry for that resource.<p> @param resource the resource @param baseSite the base site @return the resource info widget
[ "Creates", "a", "resource", "info", "widget", "for", "a", "resource", "that", "looks", "like", "the", "sitemap", "entry", "for", "that", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsResourceInfo.java#L164-L201
virgo47/javasimon
javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java
SimonServletFilter.doFilter
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { """ Wraps the HTTP request with Simon measuring. Separate Simons are created for different URIs (parameters ignored). @param servletRequest HTTP servlet request @param servletResponse HTTP servlet response @param filterChain filter chain @throws IOException possibly thrown by other filter/servlet in the chain @throws ServletException possibly thrown by other filter/servlet in the chain """ HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String localPath = request.getRequestURI().substring(request.getContextPath().length()); if (consolePath != null && (localPath.equals(printTreePath) || localPath.startsWith(consolePath))) { consolePage(request, response, localPath); return; } doFilterWithMonitoring(filterChain, request, response); }
java
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String localPath = request.getRequestURI().substring(request.getContextPath().length()); if (consolePath != null && (localPath.equals(printTreePath) || localPath.startsWith(consolePath))) { consolePage(request, response, localPath); return; } doFilterWithMonitoring(filterChain, request, response); }
[ "public", "final", "void", "doFilter", "(", "ServletRequest", "servletRequest", ",", "ServletResponse", "servletResponse", ",", "FilterChain", "filterChain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "request", "=", "(", "HttpServletRequest", ")", "servletRequest", ";", "HttpServletResponse", "response", "=", "(", "HttpServletResponse", ")", "servletResponse", ";", "String", "localPath", "=", "request", ".", "getRequestURI", "(", ")", ".", "substring", "(", "request", ".", "getContextPath", "(", ")", ".", "length", "(", ")", ")", ";", "if", "(", "consolePath", "!=", "null", "&&", "(", "localPath", ".", "equals", "(", "printTreePath", ")", "||", "localPath", ".", "startsWith", "(", "consolePath", ")", ")", ")", "{", "consolePage", "(", "request", ",", "response", ",", "localPath", ")", ";", "return", ";", "}", "doFilterWithMonitoring", "(", "filterChain", ",", "request", ",", "response", ")", ";", "}" ]
Wraps the HTTP request with Simon measuring. Separate Simons are created for different URIs (parameters ignored). @param servletRequest HTTP servlet request @param servletResponse HTTP servlet response @param filterChain filter chain @throws IOException possibly thrown by other filter/servlet in the chain @throws ServletException possibly thrown by other filter/servlet in the chain
[ "Wraps", "the", "HTTP", "request", "with", "Simon", "measuring", ".", "Separate", "Simons", "are", "created", "for", "different", "URIs", "(", "parameters", "ignored", ")", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java#L225-L236
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/UnImplNode.java
UnImplNode.insertBefore
public Node insertBefore(Node newChild, Node refChild) throws DOMException { """ Unimplemented. See org.w3c.dom.Node @param newChild New child node to insert @param refChild Insert in front of this child @return null @throws DOMException """ error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"insertBefore not supported!"); return null; }
java
public Node insertBefore(Node newChild, Node refChild) throws DOMException { error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"insertBefore not supported!"); return null; }
[ "public", "Node", "insertBefore", "(", "Node", "newChild", ",", "Node", "refChild", ")", "throws", "DOMException", "{", "error", "(", "XMLErrorResources", ".", "ER_FUNCTION_NOT_SUPPORTED", ")", ";", "//\"insertBefore not supported!\");", "return", "null", ";", "}" ]
Unimplemented. See org.w3c.dom.Node @param newChild New child node to insert @param refChild Insert in front of this child @return null @throws DOMException
[ "Unimplemented", ".", "See", "org", ".", "w3c", ".", "dom", ".", "Node" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/UnImplNode.java#L656-L662