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
mahjong4j/mahjong4j
src/main/java/org/mahjong4j/yaku/normals/PinfuResolver.java
PinfuResolver.isRyanmen
private boolean isRyanmen(Shuntsu shuntsu, Tile last) { """ 両面待ちだったかを判定するため 一つ一つの順子と最後の牌について判定する @param shuntsu 判定したい順子 @param last 最後の牌 @return 両面待ちだったか """ //ラスト牌と判定したい順子のtypeが違う場合はfalse if (shuntsu.getTile().getType() != last.getType()) { return false; } int shuntsuNum = shuntsu.getTile().getNumber(); int lastNum = last.getNumber(); if (shuntsuNum == 2 && lastNum == 1) { return true; } if (shuntsuNum == 8 && lastNum == 9) { return true; } int i = shuntsuNum - lastNum; if (i == 1 || i == -1) { return true; } return false; }
java
private boolean isRyanmen(Shuntsu shuntsu, Tile last) { //ラスト牌と判定したい順子のtypeが違う場合はfalse if (shuntsu.getTile().getType() != last.getType()) { return false; } int shuntsuNum = shuntsu.getTile().getNumber(); int lastNum = last.getNumber(); if (shuntsuNum == 2 && lastNum == 1) { return true; } if (shuntsuNum == 8 && lastNum == 9) { return true; } int i = shuntsuNum - lastNum; if (i == 1 || i == -1) { return true; } return false; }
[ "private", "boolean", "isRyanmen", "(", "Shuntsu", "shuntsu", ",", "Tile", "last", ")", "{", "//ラスト牌と判定したい順子のtypeが違う場合はfalse", "if", "(", "shuntsu", ".", "getTile", "(", ")", ".", "getType", "(", ")", "!=", "last", ".", "getType", "(", ")", ")", "{", "return", "false", ";", "}", "int", "shuntsuNum", "=", "shuntsu", ".", "getTile", "(", ")", ".", "getNumber", "(", ")", ";", "int", "lastNum", "=", "last", ".", "getNumber", "(", ")", ";", "if", "(", "shuntsuNum", "==", "2", "&&", "lastNum", "==", "1", ")", "{", "return", "true", ";", "}", "if", "(", "shuntsuNum", "==", "8", "&&", "lastNum", "==", "9", ")", "{", "return", "true", ";", "}", "int", "i", "=", "shuntsuNum", "-", "lastNum", ";", "if", "(", "i", "==", "1", "||", "i", "==", "-", "1", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
両面待ちだったかを判定するため 一つ一つの順子と最後の牌について判定する @param shuntsu 判定したい順子 @param last 最後の牌 @return 両面待ちだったか
[ "両面待ちだったかを判定するため", "一つ一つの順子と最後の牌について判定する" ]
train
https://github.com/mahjong4j/mahjong4j/blob/caa75963286b631ad51953d0d8c71cf6bf79b8f4/src/main/java/org/mahjong4j/yaku/normals/PinfuResolver.java#L86-L108
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java
PathResourceManager.getSymlinkBase
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException { """ Returns true is some element of path inside base path is a symlink. """ int nameCount = file.getNameCount(); Path root = fileSystem.getPath(base); int rootCount = root.getNameCount(); Path f = file; for (int i = nameCount - 1; i>=0; i--) { if (Files.isSymbolicLink(f)) { return new SymlinkResult(i+1 > rootCount, f); } f = f.getParent(); } return null; }
java
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException { int nameCount = file.getNameCount(); Path root = fileSystem.getPath(base); int rootCount = root.getNameCount(); Path f = file; for (int i = nameCount - 1; i>=0; i--) { if (Files.isSymbolicLink(f)) { return new SymlinkResult(i+1 > rootCount, f); } f = f.getParent(); } return null; }
[ "private", "SymlinkResult", "getSymlinkBase", "(", "final", "String", "base", ",", "final", "Path", "file", ")", "throws", "IOException", "{", "int", "nameCount", "=", "file", ".", "getNameCount", "(", ")", ";", "Path", "root", "=", "fileSystem", ".", "getPath", "(", "base", ")", ";", "int", "rootCount", "=", "root", ".", "getNameCount", "(", ")", ";", "Path", "f", "=", "file", ";", "for", "(", "int", "i", "=", "nameCount", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "Files", ".", "isSymbolicLink", "(", "f", ")", ")", "{", "return", "new", "SymlinkResult", "(", "i", "+", "1", ">", "rootCount", ",", "f", ")", ";", "}", "f", "=", "f", ".", "getParent", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns true is some element of path inside base path is a symlink.
[ "Returns", "true", "is", "some", "element", "of", "path", "inside", "base", "path", "is", "a", "symlink", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java#L300-L313
jamesagnew/hapi-fhir
hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/validation/BaseValidator.java
BaseValidator.txWarning
protected boolean txWarning(List<ValidationMessage> errors, String txLink, IssueType type, int line, int col, String path, boolean thePass, String msg, Object... theMessageArguments) { """ Test a rule and add a {@link IssueSeverity#WARNING} validation message if the validation fails @param thePass Set this parameter to <code>false</code> if the validation does not pass @return Returns <code>thePass</code> (in other words, returns <code>true</code> if the rule did not fail validation) """ if (!thePass) { msg = formatMessage(msg, theMessageArguments); errors.add(new ValidationMessage(Source.TerminologyEngine, type, line, col, path, msg, IssueSeverity.WARNING).setTxLink(txLink)); } return thePass; }
java
protected boolean txWarning(List<ValidationMessage> errors, String txLink, IssueType type, int line, int col, String path, boolean thePass, String msg, Object... theMessageArguments) { if (!thePass) { msg = formatMessage(msg, theMessageArguments); errors.add(new ValidationMessage(Source.TerminologyEngine, type, line, col, path, msg, IssueSeverity.WARNING).setTxLink(txLink)); } return thePass; }
[ "protected", "boolean", "txWarning", "(", "List", "<", "ValidationMessage", ">", "errors", ",", "String", "txLink", ",", "IssueType", "type", ",", "int", "line", ",", "int", "col", ",", "String", "path", ",", "boolean", "thePass", ",", "String", "msg", ",", "Object", "...", "theMessageArguments", ")", "{", "if", "(", "!", "thePass", ")", "{", "msg", "=", "formatMessage", "(", "msg", ",", "theMessageArguments", ")", ";", "errors", ".", "add", "(", "new", "ValidationMessage", "(", "Source", ".", "TerminologyEngine", ",", "type", ",", "line", ",", "col", ",", "path", ",", "msg", ",", "IssueSeverity", ".", "WARNING", ")", ".", "setTxLink", "(", "txLink", ")", ")", ";", "}", "return", "thePass", ";", "}" ]
Test a rule and add a {@link IssueSeverity#WARNING} validation message if the validation fails @param thePass Set this parameter to <code>false</code> if the validation does not pass @return Returns <code>thePass</code> (in other words, returns <code>true</code> if the rule did not fail validation)
[ "Test", "a", "rule", "and", "add", "a", "{", "@link", "IssueSeverity#WARNING", "}", "validation", "message", "if", "the", "validation", "fails" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-validation/src/main/java/org/hl7/fhir/r4/validation/BaseValidator.java#L338-L345
UrielCh/ovh-java-sdk
ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java
ApiOvhDbaaslogs.serviceName_output_elasticsearch_index_indexId_PUT
public OvhOperation serviceName_output_elasticsearch_index_indexId_PUT(String serviceName, String indexId, Boolean alertNotifyEnabled, String description) throws IOException { """ Update specified elasticsearch index REST: PUT /dbaas/logs/{serviceName}/output/elasticsearch/index/{indexId} @param serviceName [required] Service name @param indexId [required] Index ID @param alertNotifyEnabled [required] Alert notify enabled @param description [required] Description """ String qPath = "/dbaas/logs/{serviceName}/output/elasticsearch/index/{indexId}"; StringBuilder sb = path(qPath, serviceName, indexId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "alertNotifyEnabled", alertNotifyEnabled); addBody(o, "description", description); String resp = exec(qPath, "PUT", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
java
public OvhOperation serviceName_output_elasticsearch_index_indexId_PUT(String serviceName, String indexId, Boolean alertNotifyEnabled, String description) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/elasticsearch/index/{indexId}"; StringBuilder sb = path(qPath, serviceName, indexId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "alertNotifyEnabled", alertNotifyEnabled); addBody(o, "description", description); String resp = exec(qPath, "PUT", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
[ "public", "OvhOperation", "serviceName_output_elasticsearch_index_indexId_PUT", "(", "String", "serviceName", ",", "String", "indexId", ",", "Boolean", "alertNotifyEnabled", ",", "String", "description", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dbaas/logs/{serviceName}/output/elasticsearch/index/{indexId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "indexId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"alertNotifyEnabled\"", ",", "alertNotifyEnabled", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOperation", ".", "class", ")", ";", "}" ]
Update specified elasticsearch index REST: PUT /dbaas/logs/{serviceName}/output/elasticsearch/index/{indexId} @param serviceName [required] Service name @param indexId [required] Index ID @param alertNotifyEnabled [required] Alert notify enabled @param description [required] Description
[ "Update", "specified", "elasticsearch", "index" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L1851-L1859
RallyTools/RallyRestToolkitForJava
src/main/java/com/rallydev/rest/client/BasicAuthClient.java
BasicAuthClient.doRequest
@Override protected String doRequest(HttpRequestBase request) throws IOException { """ Execute a request against the WSAPI @param request the request to be executed @return the JSON encoded string response @throws java.io.IOException if a non-200 response code is returned or if some other problem occurs while executing the request """ if(!request.getMethod().equals(HttpGet.METHOD_NAME) && !this.getWsapiVersion().matches("^1[.]\\d+")) { try { attachSecurityInfo(request); } catch (URISyntaxException e) { throw new IOException("Unable to build URI with security token", e); } } return super.doRequest(request); }
java
@Override protected String doRequest(HttpRequestBase request) throws IOException { if(!request.getMethod().equals(HttpGet.METHOD_NAME) && !this.getWsapiVersion().matches("^1[.]\\d+")) { try { attachSecurityInfo(request); } catch (URISyntaxException e) { throw new IOException("Unable to build URI with security token", e); } } return super.doRequest(request); }
[ "@", "Override", "protected", "String", "doRequest", "(", "HttpRequestBase", "request", ")", "throws", "IOException", "{", "if", "(", "!", "request", ".", "getMethod", "(", ")", ".", "equals", "(", "HttpGet", ".", "METHOD_NAME", ")", "&&", "!", "this", ".", "getWsapiVersion", "(", ")", ".", "matches", "(", "\"^1[.]\\\\d+\"", ")", ")", "{", "try", "{", "attachSecurityInfo", "(", "request", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Unable to build URI with security token\"", ",", "e", ")", ";", "}", "}", "return", "super", ".", "doRequest", "(", "request", ")", ";", "}" ]
Execute a request against the WSAPI @param request the request to be executed @return the JSON encoded string response @throws java.io.IOException if a non-200 response code is returned or if some other problem occurs while executing the request
[ "Execute", "a", "request", "against", "the", "WSAPI" ]
train
https://github.com/RallyTools/RallyRestToolkitForJava/blob/542afa16ea44c9c64cebb0299500dcbbb50b6d7d/src/main/java/com/rallydev/rest/client/BasicAuthClient.java#L46-L57
mikepenz/FastAdapter
library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java
FastAdapter.notifyAdapterItemRangeChanged
public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { """ wraps notifyItemRangeChanged @param position the global position @param itemCount the count of items changed @param payload an additional payload """ // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } }
java
public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } }
[ "public", "void", "notifyAdapterItemRangeChanged", "(", "int", "position", ",", "int", "itemCount", ",", "@", "Nullable", "Object", "payload", ")", "{", "// handle our extensions", "for", "(", "IAdapterExtension", "<", "Item", ">", "ext", ":", "mExtensions", ".", "values", "(", ")", ")", "{", "ext", ".", "notifyAdapterItemRangeChanged", "(", "position", ",", "itemCount", ",", "payload", ")", ";", "}", "if", "(", "payload", "==", "null", ")", "{", "notifyItemRangeChanged", "(", "position", ",", "itemCount", ")", ";", "}", "else", "{", "notifyItemRangeChanged", "(", "position", ",", "itemCount", ",", "payload", ")", ";", "}", "}" ]
wraps notifyItemRangeChanged @param position the global position @param itemCount the count of items changed @param payload an additional payload
[ "wraps", "notifyItemRangeChanged" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1363-L1373
undertow-io/undertow
core/src/main/java/io/undertow/client/http/HttpResponseParser.java
HttpResponseParser.handleReasonPhrase
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { """ Parses the reason phrase. This is called from the generated bytecode. @param buffer The buffer @param state The current state @param builder The exchange builder @return The number of bytes remaining """ StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
java
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "final", "void", "handleReasonPhrase", "(", "ByteBuffer", "buffer", ",", "ResponseParseState", "state", ",", "HttpResponseBuilder", "builder", ")", "{", "StringBuilder", "stringBuilder", "=", "state", ".", "stringBuilder", ";", "while", "(", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "final", "char", "next", "=", "(", "char", ")", "buffer", ".", "get", "(", ")", ";", "if", "(", "next", "==", "'", "'", "||", "next", "==", "'", "'", ")", "{", "builder", ".", "setReasonPhrase", "(", "stringBuilder", ".", "toString", "(", ")", ")", ";", "state", ".", "state", "=", "ResponseParseState", ".", "AFTER_REASON_PHRASE", ";", "state", ".", "stringBuilder", ".", "setLength", "(", "0", ")", ";", "state", ".", "parseState", "=", "0", ";", "state", ".", "leftOver", "=", "(", "byte", ")", "next", ";", "state", ".", "pos", "=", "0", ";", "state", ".", "nextHeader", "=", "null", ";", "return", ";", "}", "else", "{", "stringBuilder", ".", "append", "(", "next", ")", ";", "}", "}", "}" ]
Parses the reason phrase. This is called from the generated bytecode. @param buffer The buffer @param state The current state @param builder The exchange builder @return The number of bytes remaining
[ "Parses", "the", "reason", "phrase", ".", "This", "is", "called", "from", "the", "generated", "bytecode", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L202-L220
lessthanoptimal/ddogleg
src/org/ddogleg/solver/PolynomialSolver.java
PolynomialSolver.cubicRootReal
public static double cubicRootReal(double a, double b, double c, double d) { """ <p> A cubic polynomial of the form "f(x) = a + b*x + c*x<sup>2</sup> + d*x<sup>3</sup>" has three roots. These roots will either be all real or one real and two imaginary. This function will return a root which is always real. </p> <p> WARNING: Not as numerically stable as {@link #polynomialRootsEVD(double...)}, but still fairly stable. </p> @param a polynomial coefficient. @param b polynomial coefficient. @param c polynomial coefficient. @param d polynomial coefficient. @return A real root of the cubic polynomial """ // normalize for numerical stability double norm = Math.max(Math.abs(a), Math.abs(b)); norm = Math.max(norm,Math.abs(c)); norm = Math.max(norm, Math.abs(d)); a /= norm; b /= norm; c /= norm; d /= norm; // proceed with standard algorithm double insideLeft = 2*c*c*c - 9*d*c*b + 27*d*d*a; double temp = c*c-3*d*b; double insideOfSqrt = insideLeft*insideLeft - 4*temp*temp*temp; if( insideOfSqrt >= 0 ) { double insideRight = Math.sqrt(insideOfSqrt ); double ret = c + root3(0.5*(insideLeft+insideRight)) + root3(0.5*(insideLeft-insideRight)); return -ret/(3.0*d); } else { Complex_F64 inside = new Complex_F64(0.5*insideLeft,0.5*Math.sqrt(-insideOfSqrt )); Complex_F64 root = new Complex_F64(); ComplexMath_F64.root(inside, 3, 2, root); // imaginary components cancel out double ret = c + 2*root.getReal(); return -ret/(3.0*d); } }
java
public static double cubicRootReal(double a, double b, double c, double d) { // normalize for numerical stability double norm = Math.max(Math.abs(a), Math.abs(b)); norm = Math.max(norm,Math.abs(c)); norm = Math.max(norm, Math.abs(d)); a /= norm; b /= norm; c /= norm; d /= norm; // proceed with standard algorithm double insideLeft = 2*c*c*c - 9*d*c*b + 27*d*d*a; double temp = c*c-3*d*b; double insideOfSqrt = insideLeft*insideLeft - 4*temp*temp*temp; if( insideOfSqrt >= 0 ) { double insideRight = Math.sqrt(insideOfSqrt ); double ret = c + root3(0.5*(insideLeft+insideRight)) + root3(0.5*(insideLeft-insideRight)); return -ret/(3.0*d); } else { Complex_F64 inside = new Complex_F64(0.5*insideLeft,0.5*Math.sqrt(-insideOfSqrt )); Complex_F64 root = new Complex_F64(); ComplexMath_F64.root(inside, 3, 2, root); // imaginary components cancel out double ret = c + 2*root.getReal(); return -ret/(3.0*d); } }
[ "public", "static", "double", "cubicRootReal", "(", "double", "a", ",", "double", "b", ",", "double", "c", ",", "double", "d", ")", "{", "// normalize for numerical stability", "double", "norm", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "a", ")", ",", "Math", ".", "abs", "(", "b", ")", ")", ";", "norm", "=", "Math", ".", "max", "(", "norm", ",", "Math", ".", "abs", "(", "c", ")", ")", ";", "norm", "=", "Math", ".", "max", "(", "norm", ",", "Math", ".", "abs", "(", "d", ")", ")", ";", "a", "/=", "norm", ";", "b", "/=", "norm", ";", "c", "/=", "norm", ";", "d", "/=", "norm", ";", "// proceed with standard algorithm", "double", "insideLeft", "=", "2", "*", "c", "*", "c", "*", "c", "-", "9", "*", "d", "*", "c", "*", "b", "+", "27", "*", "d", "*", "d", "*", "a", ";", "double", "temp", "=", "c", "*", "c", "-", "3", "*", "d", "*", "b", ";", "double", "insideOfSqrt", "=", "insideLeft", "*", "insideLeft", "-", "4", "*", "temp", "*", "temp", "*", "temp", ";", "if", "(", "insideOfSqrt", ">=", "0", ")", "{", "double", "insideRight", "=", "Math", ".", "sqrt", "(", "insideOfSqrt", ")", ";", "double", "ret", "=", "c", "+", "root3", "(", "0.5", "*", "(", "insideLeft", "+", "insideRight", ")", ")", "+", "root3", "(", "0.5", "*", "(", "insideLeft", "-", "insideRight", ")", ")", ";", "return", "-", "ret", "/", "(", "3.0", "*", "d", ")", ";", "}", "else", "{", "Complex_F64", "inside", "=", "new", "Complex_F64", "(", "0.5", "*", "insideLeft", ",", "0.5", "*", "Math", ".", "sqrt", "(", "-", "insideOfSqrt", ")", ")", ";", "Complex_F64", "root", "=", "new", "Complex_F64", "(", ")", ";", "ComplexMath_F64", ".", "root", "(", "inside", ",", "3", ",", "2", ",", "root", ")", ";", "// imaginary components cancel out", "double", "ret", "=", "c", "+", "2", "*", "root", ".", "getReal", "(", ")", ";", "return", "-", "ret", "/", "(", "3.0", "*", "d", ")", ";", "}", "}" ]
<p> A cubic polynomial of the form "f(x) = a + b*x + c*x<sup>2</sup> + d*x<sup>3</sup>" has three roots. These roots will either be all real or one real and two imaginary. This function will return a root which is always real. </p> <p> WARNING: Not as numerically stable as {@link #polynomialRootsEVD(double...)}, but still fairly stable. </p> @param a polynomial coefficient. @param b polynomial coefficient. @param c polynomial coefficient. @param d polynomial coefficient. @return A real root of the cubic polynomial
[ "<p", ">", "A", "cubic", "polynomial", "of", "the", "form", "f", "(", "x", ")", "=", "a", "+", "b", "*", "x", "+", "c", "*", "x<sup", ">", "2<", "/", "sup", ">", "+", "d", "*", "x<sup", ">", "3<", "/", "sup", ">", "has", "three", "roots", ".", "These", "roots", "will", "either", "be", "all", "real", "or", "one", "real", "and", "two", "imaginary", ".", "This", "function", "will", "return", "a", "root", "which", "is", "always", "real", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/solver/PolynomialSolver.java#L96-L132
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/msgstore/ItemStream.java
ItemStream.addItem
public void addItem(final Item item, final Transaction transaction) throws ProtocolException, OutOfCacheSpace, StreamIsFull, TransactionException, PersistenceException, SevereMessageStoreException { """ Add an {@link Item} to an item stream under a transaction. An Item can only be added onto one stream at a time. . <p>This method can be overridden by subclass implementors in order to customize the behaviour of the stream. Any override should call the superclass implementation to maintain correct behaviour.</p> @param item @param transaction @throws SevereMessageStoreException @throws {@link OutOfCacheSpace} if there is not enough space in the unstoredCache and the storage strategy is {@link AbstractItem#STORE_NEVER}. @throws {@link StreamIsFull} if the size of the stream would exceed the maximum permissable size if an add were performed. @throws {@ProtocolException} Thrown if an add is attempted when the transaction cannot allow any further work to be added i.e. after completion of the transaction. @throws {@TransactionException} Thrown if an unexpected error occurs. @throws {@PersistenceException} Thrown if a database error occurs. """ // default lock id long lockId = NO_LOCK_ID; // delivery delay is set, hence DELIVERY_DELAY_LOCK_ID will be used to lock the Item if (item.getDeliveryDelay() > 0) lockId = DELIVERY_DELAY_LOCK_ID; addItem(item, lockId, transaction); }
java
public void addItem(final Item item, final Transaction transaction) throws ProtocolException, OutOfCacheSpace, StreamIsFull, TransactionException, PersistenceException, SevereMessageStoreException { // default lock id long lockId = NO_LOCK_ID; // delivery delay is set, hence DELIVERY_DELAY_LOCK_ID will be used to lock the Item if (item.getDeliveryDelay() > 0) lockId = DELIVERY_DELAY_LOCK_ID; addItem(item, lockId, transaction); }
[ "public", "void", "addItem", "(", "final", "Item", "item", ",", "final", "Transaction", "transaction", ")", "throws", "ProtocolException", ",", "OutOfCacheSpace", ",", "StreamIsFull", ",", "TransactionException", ",", "PersistenceException", ",", "SevereMessageStoreException", "{", "// default lock id", "long", "lockId", "=", "NO_LOCK_ID", ";", "// delivery delay is set, hence DELIVERY_DELAY_LOCK_ID will be used to lock the Item", "if", "(", "item", ".", "getDeliveryDelay", "(", ")", ">", "0", ")", "lockId", "=", "DELIVERY_DELAY_LOCK_ID", ";", "addItem", "(", "item", ",", "lockId", ",", "transaction", ")", ";", "}" ]
Add an {@link Item} to an item stream under a transaction. An Item can only be added onto one stream at a time. . <p>This method can be overridden by subclass implementors in order to customize the behaviour of the stream. Any override should call the superclass implementation to maintain correct behaviour.</p> @param item @param transaction @throws SevereMessageStoreException @throws {@link OutOfCacheSpace} if there is not enough space in the unstoredCache and the storage strategy is {@link AbstractItem#STORE_NEVER}. @throws {@link StreamIsFull} if the size of the stream would exceed the maximum permissable size if an add were performed. @throws {@ProtocolException} Thrown if an add is attempted when the transaction cannot allow any further work to be added i.e. after completion of the transaction. @throws {@TransactionException} Thrown if an unexpected error occurs. @throws {@PersistenceException} Thrown if a database error occurs.
[ "Add", "an", "{", "@link", "Item", "}", "to", "an", "item", "stream", "under", "a", "transaction", ".", "An", "Item", "can", "only", "be", "added", "onto", "one", "stream", "at", "a", "time", ".", ".", "<p", ">", "This", "method", "can", "be", "overridden", "by", "subclass", "implementors", "in", "order", "to", "customize", "the", "behaviour", "of", "the", "stream", ".", "Any", "override", "should", "call", "the", "superclass", "implementation", "to", "maintain", "correct", "behaviour", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/msgstore/ItemStream.java#L124-L136
kuali/ojb-1.0.4
src/java/org/apache/ojb/odmg/ObjectEnvelopeTable.java
ObjectEnvelopeTable.get
public ObjectEnvelope get(Identity oid, Object pKey, boolean isNew) { """ retrieve an objects ObjectEnvelope state from the hashtable. If no ObjectEnvelope is found, a new one is created and returned. @return the resulting ObjectEnvelope """ ObjectEnvelope result = getByIdentity(oid); if(result == null) { result = new ObjectEnvelope(this, oid, pKey, isNew); mhtObjectEnvelopes.put(oid, result); mvOrderOfIds.add(oid); if(log.isDebugEnabled()) log.debug("register: " + result); } return result; }
java
public ObjectEnvelope get(Identity oid, Object pKey, boolean isNew) { ObjectEnvelope result = getByIdentity(oid); if(result == null) { result = new ObjectEnvelope(this, oid, pKey, isNew); mhtObjectEnvelopes.put(oid, result); mvOrderOfIds.add(oid); if(log.isDebugEnabled()) log.debug("register: " + result); } return result; }
[ "public", "ObjectEnvelope", "get", "(", "Identity", "oid", ",", "Object", "pKey", ",", "boolean", "isNew", ")", "{", "ObjectEnvelope", "result", "=", "getByIdentity", "(", "oid", ")", ";", "if", "(", "result", "==", "null", ")", "{", "result", "=", "new", "ObjectEnvelope", "(", "this", ",", "oid", ",", "pKey", ",", "isNew", ")", ";", "mhtObjectEnvelopes", ".", "put", "(", "oid", ",", "result", ")", ";", "mvOrderOfIds", ".", "add", "(", "oid", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"register: \"", "+", "result", ")", ";", "}", "return", "result", ";", "}" ]
retrieve an objects ObjectEnvelope state from the hashtable. If no ObjectEnvelope is found, a new one is created and returned. @return the resulting ObjectEnvelope
[ "retrieve", "an", "objects", "ObjectEnvelope", "state", "from", "the", "hashtable", ".", "If", "no", "ObjectEnvelope", "is", "found", "a", "new", "one", "is", "created", "and", "returned", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/ObjectEnvelopeTable.java#L426-L438
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/wikipedia/Descriptor.java
Descriptor.setCategories
public void setCategories(int i, Title v) { """ indexed setter for categories - sets an indexed value - List of Wikipedia categories associated with a Wikipedia page. @generated @param i index in the array to set @param v value to set into the array """ if (Descriptor_Type.featOkTst && ((Descriptor_Type)jcasType).casFeat_categories == null) jcasType.jcas.throwFeatMissing("categories", "de.julielab.jules.types.wikipedia.Descriptor"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Descriptor_Type)jcasType).casFeatCode_categories), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Descriptor_Type)jcasType).casFeatCode_categories), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public void setCategories(int i, Title v) { if (Descriptor_Type.featOkTst && ((Descriptor_Type)jcasType).casFeat_categories == null) jcasType.jcas.throwFeatMissing("categories", "de.julielab.jules.types.wikipedia.Descriptor"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Descriptor_Type)jcasType).casFeatCode_categories), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Descriptor_Type)jcasType).casFeatCode_categories), i, jcasType.ll_cas.ll_getFSRef(v));}
[ "public", "void", "setCategories", "(", "int", "i", ",", "Title", "v", ")", "{", "if", "(", "Descriptor_Type", ".", "featOkTst", "&&", "(", "(", "Descriptor_Type", ")", "jcasType", ")", ".", "casFeat_categories", "==", "null", ")", "jcasType", ".", "jcas", ".", "throwFeatMissing", "(", "\"categories\"", ",", "\"de.julielab.jules.types.wikipedia.Descriptor\"", ")", ";", "jcasType", ".", "jcas", ".", "checkArrayBounds", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Descriptor_Type", ")", "jcasType", ")", ".", "casFeatCode_categories", ")", ",", "i", ")", ";", "jcasType", ".", "ll_cas", ".", "ll_setRefArrayValue", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Descriptor_Type", ")", "jcasType", ")", ".", "casFeatCode_categories", ")", ",", "i", ",", "jcasType", ".", "ll_cas", ".", "ll_getFSRef", "(", "v", ")", ")", ";", "}" ]
indexed setter for categories - sets an indexed value - List of Wikipedia categories associated with a Wikipedia page. @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "categories", "-", "sets", "an", "indexed", "value", "-", "List", "of", "Wikipedia", "categories", "associated", "with", "a", "Wikipedia", "page", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/wikipedia/Descriptor.java#L117-L121
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java
ProcessGroovyMethods.consumeProcessOutput
public static void consumeProcessOutput(Process self, OutputStream output, OutputStream error) { """ Gets the output and error streams from a process and reads them to keep the process from blocking due to a full output buffer. The processed stream data is appended to the supplied OutputStream. For this, two Threads are started, so this method will return immediately. The threads will not be join()ed, even if waitFor() is called. To wait for the output to be fully consumed call waitForProcessOutput(). @param self a Process @param output an OutputStream to capture the process stdout @param error an OutputStream to capture the process stderr @since 1.5.2 """ consumeProcessOutputStream(self, output); consumeProcessErrorStream(self, error); }
java
public static void consumeProcessOutput(Process self, OutputStream output, OutputStream error) { consumeProcessOutputStream(self, output); consumeProcessErrorStream(self, error); }
[ "public", "static", "void", "consumeProcessOutput", "(", "Process", "self", ",", "OutputStream", "output", ",", "OutputStream", "error", ")", "{", "consumeProcessOutputStream", "(", "self", ",", "output", ")", ";", "consumeProcessErrorStream", "(", "self", ",", "error", ")", ";", "}" ]
Gets the output and error streams from a process and reads them to keep the process from blocking due to a full output buffer. The processed stream data is appended to the supplied OutputStream. For this, two Threads are started, so this method will return immediately. The threads will not be join()ed, even if waitFor() is called. To wait for the output to be fully consumed call waitForProcessOutput(). @param self a Process @param output an OutputStream to capture the process stdout @param error an OutputStream to capture the process stderr @since 1.5.2
[ "Gets", "the", "output", "and", "error", "streams", "from", "a", "process", "and", "reads", "them", "to", "keep", "the", "process", "from", "blocking", "due", "to", "a", "full", "output", "buffer", ".", "The", "processed", "stream", "data", "is", "appended", "to", "the", "supplied", "OutputStream", ".", "For", "this", "two", "Threads", "are", "started", "so", "this", "method", "will", "return", "immediately", ".", "The", "threads", "will", "not", "be", "join", "()", "ed", "even", "if", "waitFor", "()", "is", "called", ".", "To", "wait", "for", "the", "output", "to", "be", "fully", "consumed", "call", "waitForProcessOutput", "()", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L205-L208
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/model/globalfac/ConsecutiveSiblingsFactor.java
ConsecutiveSiblingsFactor.getLinkVar
public LinkVar getLinkVar(int parent, int child) { """ Get the link var corresponding to the specified parent and child position. @param parent The parent word position, or -1 to indicate the wall node. @param child The child word position. @return The link variable. """ if (parent == -1) { return rootVars[child]; } else { return childVars[parent][child]; } }
java
public LinkVar getLinkVar(int parent, int child) { if (parent == -1) { return rootVars[child]; } else { return childVars[parent][child]; } }
[ "public", "LinkVar", "getLinkVar", "(", "int", "parent", ",", "int", "child", ")", "{", "if", "(", "parent", "==", "-", "1", ")", "{", "return", "rootVars", "[", "child", "]", ";", "}", "else", "{", "return", "childVars", "[", "parent", "]", "[", "child", "]", ";", "}", "}" ]
Get the link var corresponding to the specified parent and child position. @param parent The parent word position, or -1 to indicate the wall node. @param child The child word position. @return The link variable.
[ "Get", "the", "link", "var", "corresponding", "to", "the", "specified", "parent", "and", "child", "position", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/model/globalfac/ConsecutiveSiblingsFactor.java#L179-L185
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberingSystem.java
NumberingSystem.getInstance
public static NumberingSystem getInstance(ULocale locale) { """ Returns the default numbering system for the specified ULocale. """ // Check for @numbers boolean nsResolved = true; String numbersKeyword = locale.getKeywordValue("numbers"); if (numbersKeyword != null ) { for ( String keyword : OTHER_NS_KEYWORDS ) { if ( numbersKeyword.equals(keyword)) { nsResolved = false; break; } } } else { numbersKeyword = "default"; nsResolved = false; } if (nsResolved) { NumberingSystem ns = getInstanceByName(numbersKeyword); if (ns != null) { return ns; } // If the @numbers keyword points to a bogus numbering system name, // we return the default for the locale. numbersKeyword = "default"; } // Attempt to get the numbering system from the cache String baseName = locale.getBaseName(); // TODO: Caching by locale+numbersKeyword could yield a large cache. // Try to load for each locale the mappings from OTHER_NS_KEYWORDS and default // to real numbering system names; can we get those from supplemental data? // Then look up those mappings for the locale and resolve the keyword. String key = baseName+"@numbers="+numbersKeyword; LocaleLookupData localeLookupData = new LocaleLookupData(locale, numbersKeyword); return cachedLocaleData.getInstance(key, localeLookupData); }
java
public static NumberingSystem getInstance(ULocale locale) { // Check for @numbers boolean nsResolved = true; String numbersKeyword = locale.getKeywordValue("numbers"); if (numbersKeyword != null ) { for ( String keyword : OTHER_NS_KEYWORDS ) { if ( numbersKeyword.equals(keyword)) { nsResolved = false; break; } } } else { numbersKeyword = "default"; nsResolved = false; } if (nsResolved) { NumberingSystem ns = getInstanceByName(numbersKeyword); if (ns != null) { return ns; } // If the @numbers keyword points to a bogus numbering system name, // we return the default for the locale. numbersKeyword = "default"; } // Attempt to get the numbering system from the cache String baseName = locale.getBaseName(); // TODO: Caching by locale+numbersKeyword could yield a large cache. // Try to load for each locale the mappings from OTHER_NS_KEYWORDS and default // to real numbering system names; can we get those from supplemental data? // Then look up those mappings for the locale and resolve the keyword. String key = baseName+"@numbers="+numbersKeyword; LocaleLookupData localeLookupData = new LocaleLookupData(locale, numbersKeyword); return cachedLocaleData.getInstance(key, localeLookupData); }
[ "public", "static", "NumberingSystem", "getInstance", "(", "ULocale", "locale", ")", "{", "// Check for @numbers", "boolean", "nsResolved", "=", "true", ";", "String", "numbersKeyword", "=", "locale", ".", "getKeywordValue", "(", "\"numbers\"", ")", ";", "if", "(", "numbersKeyword", "!=", "null", ")", "{", "for", "(", "String", "keyword", ":", "OTHER_NS_KEYWORDS", ")", "{", "if", "(", "numbersKeyword", ".", "equals", "(", "keyword", ")", ")", "{", "nsResolved", "=", "false", ";", "break", ";", "}", "}", "}", "else", "{", "numbersKeyword", "=", "\"default\"", ";", "nsResolved", "=", "false", ";", "}", "if", "(", "nsResolved", ")", "{", "NumberingSystem", "ns", "=", "getInstanceByName", "(", "numbersKeyword", ")", ";", "if", "(", "ns", "!=", "null", ")", "{", "return", "ns", ";", "}", "// If the @numbers keyword points to a bogus numbering system name,", "// we return the default for the locale.", "numbersKeyword", "=", "\"default\"", ";", "}", "// Attempt to get the numbering system from the cache", "String", "baseName", "=", "locale", ".", "getBaseName", "(", ")", ";", "// TODO: Caching by locale+numbersKeyword could yield a large cache.", "// Try to load for each locale the mappings from OTHER_NS_KEYWORDS and default", "// to real numbering system names; can we get those from supplemental data?", "// Then look up those mappings for the locale and resolve the keyword.", "String", "key", "=", "baseName", "+", "\"@numbers=\"", "+", "numbersKeyword", ";", "LocaleLookupData", "localeLookupData", "=", "new", "LocaleLookupData", "(", "locale", ",", "numbersKeyword", ")", ";", "return", "cachedLocaleData", ".", "getInstance", "(", "key", ",", "localeLookupData", ")", ";", "}" ]
Returns the default numbering system for the specified ULocale.
[ "Returns", "the", "default", "numbering", "system", "for", "the", "specified", "ULocale", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberingSystem.java#L110-L145
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/websphere/ssl/JSSEHelper.java
JSSEHelper.registerSSLConfigChangeListener
public void registerSSLConfigChangeListener(String sslAliasName, Map<String, Object> connectionInfo, SSLConfigChangeListener listener) throws SSLException { """ <p> This method registers an SSLConfigChangeListener for the specific SSL configuration chosen based upon the parameters passed in using the precedence logic described in the JavaDoc for the getSSLContext API. The SSLConfigChangeListener must be deregistered by deregisterSSLConfigChangeListener when it is no longer needed. </p> @param sslAliasName @param connectionInfo @param listener @throws com.ibm.websphere.ssl.SSLException @ibm-api """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "registerSSLConfigChangeListener", new Object[] { sslAliasName, connectionInfo, listener }); getProperties(sslAliasName, connectionInfo, listener); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "registerSSLConfigChangeListener"); }
java
public void registerSSLConfigChangeListener(String sslAliasName, Map<String, Object> connectionInfo, SSLConfigChangeListener listener) throws SSLException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "registerSSLConfigChangeListener", new Object[] { sslAliasName, connectionInfo, listener }); getProperties(sslAliasName, connectionInfo, listener); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "registerSSLConfigChangeListener"); }
[ "public", "void", "registerSSLConfigChangeListener", "(", "String", "sslAliasName", ",", "Map", "<", "String", ",", "Object", ">", "connectionInfo", ",", "SSLConfigChangeListener", "listener", ")", "throws", "SSLException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"registerSSLConfigChangeListener\"", ",", "new", "Object", "[", "]", "{", "sslAliasName", ",", "connectionInfo", ",", "listener", "}", ")", ";", "getProperties", "(", "sslAliasName", ",", "connectionInfo", ",", "listener", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"registerSSLConfigChangeListener\"", ")", ";", "}" ]
<p> This method registers an SSLConfigChangeListener for the specific SSL configuration chosen based upon the parameters passed in using the precedence logic described in the JavaDoc for the getSSLContext API. The SSLConfigChangeListener must be deregistered by deregisterSSLConfigChangeListener when it is no longer needed. </p> @param sslAliasName @param connectionInfo @param listener @throws com.ibm.websphere.ssl.SSLException @ibm-api
[ "<p", ">", "This", "method", "registers", "an", "SSLConfigChangeListener", "for", "the", "specific", "SSL", "configuration", "chosen", "based", "upon", "the", "parameters", "passed", "in", "using", "the", "precedence", "logic", "described", "in", "the", "JavaDoc", "for", "the", "getSSLContext", "API", ".", "The", "SSLConfigChangeListener", "must", "be", "deregistered", "by", "deregisterSSLConfigChangeListener", "when", "it", "is", "no", "longer", "needed", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/websphere/ssl/JSSEHelper.java#L1169-L1175
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java
ChunkFrequencyManager.cleanConnectionClose
private void cleanConnectionClose(Connection connection, Statement stmt) { """ Close connection and sql statement in a clean way. @param connection Connection to close. @param stmt Statement to close. """ try { // clean close if (connection != null) { connection.rollback(); } if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e1) { e1.printStackTrace(); } }
java
private void cleanConnectionClose(Connection connection, Statement stmt) { try { // clean close if (connection != null) { connection.rollback(); } if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e1) { e1.printStackTrace(); } }
[ "private", "void", "cleanConnectionClose", "(", "Connection", "connection", ",", "Statement", "stmt", ")", "{", "try", "{", "// clean close", "if", "(", "connection", "!=", "null", ")", "{", "connection", ".", "rollback", "(", ")", ";", "}", "if", "(", "stmt", "!=", "null", ")", "{", "stmt", ".", "close", "(", ")", ";", "}", "if", "(", "connection", "!=", "null", ")", "{", "connection", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "SQLException", "e1", ")", "{", "e1", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Close connection and sql statement in a clean way. @param connection Connection to close. @param stmt Statement to close.
[ "Close", "connection", "and", "sql", "statement", "in", "a", "clean", "way", "." ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java#L532-L549
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/AccountsApi.java
AccountsApi.listSharedAccess
public AccountSharedAccess listSharedAccess(String accountId, AccountsApi.ListSharedAccessOptions options) throws ApiException { """ Reserved: Gets the shared item status for one or more users. Reserved: Retrieves shared item status for one or more users and types of items. Users with account administration privileges can retrieve shared access information for all account users. Users without account administrator privileges can only retrieve shared access information for themselves and the returned information is limited to the retrieving the status of all members of the account that are sharing their folders to the user. This is equivalent to setting the shared&#x3D;shared_from. @param accountId The external account number (int) or account ID Guid. (required) @param options for modifying the method behavior. @return AccountSharedAccess @throws ApiException if fails to make API call """ Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling listSharedAccess"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/shared_access".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "envelopes_not_shared_user_status", options.envelopesNotSharedUserStatus)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "folder_ids", options.folderIds)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "item_type", options.itemType)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "search_text", options.searchText)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "shared", options.shared)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "user_ids", options.userIds)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<AccountSharedAccess> localVarReturnType = new GenericType<AccountSharedAccess>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
java
public AccountSharedAccess listSharedAccess(String accountId, AccountsApi.ListSharedAccessOptions options) throws ApiException { Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling listSharedAccess"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/shared_access".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "envelopes_not_shared_user_status", options.envelopesNotSharedUserStatus)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "folder_ids", options.folderIds)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "item_type", options.itemType)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "search_text", options.searchText)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "shared", options.shared)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "user_ids", options.userIds)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<AccountSharedAccess> localVarReturnType = new GenericType<AccountSharedAccess>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
[ "public", "AccountSharedAccess", "listSharedAccess", "(", "String", "accountId", ",", "AccountsApi", ".", "ListSharedAccessOptions", "options", ")", "throws", "ApiException", "{", "Object", "localVarPostBody", "=", "\"{}\"", ";", "// verify the required parameter 'accountId' is set", "if", "(", "accountId", "==", "null", ")", "{", "throw", "new", "ApiException", "(", "400", ",", "\"Missing the required parameter 'accountId' when calling listSharedAccess\"", ")", ";", "}", "// create path and map variables", "String", "localVarPath", "=", "\"/v2/accounts/{accountId}/shared_access\"", ".", "replaceAll", "(", "\"\\\\{format\\\\}\"", ",", "\"json\"", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"accountId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "accountId", ".", "toString", "(", ")", ")", ")", ";", "// query params", "java", ".", "util", ".", "List", "<", "Pair", ">", "localVarQueryParams", "=", "new", "java", ".", "util", ".", "ArrayList", "<", "Pair", ">", "(", ")", ";", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "localVarHeaderParams", "=", "new", "java", ".", "util", ".", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "java", ".", "util", ".", "Map", "<", "String", ",", "Object", ">", "localVarFormParams", "=", "new", "java", ".", "util", ".", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "if", "(", "options", "!=", "null", ")", "{", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"count\"", ",", "options", ".", "count", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"envelopes_not_shared_user_status\"", ",", "options", ".", "envelopesNotSharedUserStatus", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"folder_ids\"", ",", "options", ".", "folderIds", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"item_type\"", ",", "options", ".", "itemType", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"search_text\"", ",", "options", ".", "searchText", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"shared\"", ",", "options", ".", "shared", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"start_position\"", ",", "options", ".", "startPosition", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"user_ids\"", ",", "options", ".", "userIds", ")", ")", ";", "}", "final", "String", "[", "]", "localVarAccepts", "=", "{", "\"application/json\"", "}", ";", "final", "String", "localVarAccept", "=", "apiClient", ".", "selectHeaderAccept", "(", "localVarAccepts", ")", ";", "final", "String", "[", "]", "localVarContentTypes", "=", "{", "}", ";", "final", "String", "localVarContentType", "=", "apiClient", ".", "selectHeaderContentType", "(", "localVarContentTypes", ")", ";", "String", "[", "]", "localVarAuthNames", "=", "new", "String", "[", "]", "{", "\"docusignAccessCode\"", "}", ";", "//{ };", "GenericType", "<", "AccountSharedAccess", ">", "localVarReturnType", "=", "new", "GenericType", "<", "AccountSharedAccess", ">", "(", ")", "{", "}", ";", "return", "apiClient", ".", "invokeAPI", "(", "localVarPath", ",", "\"GET\"", ",", "localVarQueryParams", ",", "localVarPostBody", ",", "localVarHeaderParams", ",", "localVarFormParams", ",", "localVarAccept", ",", "localVarContentType", ",", "localVarAuthNames", ",", "localVarReturnType", ")", ";", "}" ]
Reserved: Gets the shared item status for one or more users. Reserved: Retrieves shared item status for one or more users and types of items. Users with account administration privileges can retrieve shared access information for all account users. Users without account administrator privileges can only retrieve shared access information for themselves and the returned information is limited to the retrieving the status of all members of the account that are sharing their folders to the user. This is equivalent to setting the shared&#x3D;shared_from. @param accountId The external account number (int) or account ID Guid. (required) @param options for modifying the method behavior. @return AccountSharedAccess @throws ApiException if fails to make API call
[ "Reserved", ":", "Gets", "the", "shared", "item", "status", "for", "one", "or", "more", "users", ".", "Reserved", ":", "Retrieves", "shared", "item", "status", "for", "one", "or", "more", "users", "and", "types", "of", "items", ".", "Users", "with", "account", "administration", "privileges", "can", "retrieve", "shared", "access", "information", "for", "all", "account", "users", ".", "Users", "without", "account", "administrator", "privileges", "can", "only", "retrieve", "shared", "access", "information", "for", "themselves", "and", "the", "returned", "information", "is", "limited", "to", "the", "retrieving", "the", "status", "of", "all", "members", "of", "the", "account", "that", "are", "sharing", "their", "folders", "to", "the", "user", ".", "This", "is", "equivalent", "to", "setting", "the", "shared&#x3D", ";", "shared_from", "." ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L2283-L2326
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.rotationTowardsXY
public Matrix4d rotationTowardsXY(double dirX, double dirY) { """ Set this matrix to a rotation transformation about the Z axis to align the local <code>+X</code> towards <code>(dirX, dirY)</code>. <p> The vector <code>(dirX, dirY)</code> must be a unit vector. @param dirX the x component of the normalized direction @param dirY the y component of the normalized direction @return this """ if ((properties & PROPERTY_IDENTITY) == 0) this._identity(); this.m00 = dirY; this.m01 = dirX; this.m10 = -dirX; this.m11 = dirY; properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL; return this; }
java
public Matrix4d rotationTowardsXY(double dirX, double dirY) { if ((properties & PROPERTY_IDENTITY) == 0) this._identity(); this.m00 = dirY; this.m01 = dirX; this.m10 = -dirX; this.m11 = dirY; properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL; return this; }
[ "public", "Matrix4d", "rotationTowardsXY", "(", "double", "dirX", ",", "double", "dirY", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "==", "0", ")", "this", ".", "_identity", "(", ")", ";", "this", ".", "m00", "=", "dirY", ";", "this", ".", "m01", "=", "dirX", ";", "this", ".", "m10", "=", "-", "dirX", ";", "this", ".", "m11", "=", "dirY", ";", "properties", "=", "PROPERTY_AFFINE", "|", "PROPERTY_ORTHONORMAL", ";", "return", "this", ";", "}" ]
Set this matrix to a rotation transformation about the Z axis to align the local <code>+X</code> towards <code>(dirX, dirY)</code>. <p> The vector <code>(dirX, dirY)</code> must be a unit vector. @param dirX the x component of the normalized direction @param dirY the y component of the normalized direction @return this
[ "Set", "this", "matrix", "to", "a", "rotation", "transformation", "about", "the", "Z", "axis", "to", "align", "the", "local", "<code", ">", "+", "X<", "/", "code", ">", "towards", "<code", ">", "(", "dirX", "dirY", ")", "<", "/", "code", ">", ".", "<p", ">", "The", "vector", "<code", ">", "(", "dirX", "dirY", ")", "<", "/", "code", ">", "must", "be", "a", "unit", "vector", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L3721-L3730
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java
SqlFunctionUtils.sround
public static BigDecimal sround(BigDecimal b0, int b1) { """ SQL <code>ROUND</code> operator applied to BigDecimal values. """ return b0.movePointRight(b1) .setScale(0, RoundingMode.HALF_UP).movePointLeft(b1); }
java
public static BigDecimal sround(BigDecimal b0, int b1) { return b0.movePointRight(b1) .setScale(0, RoundingMode.HALF_UP).movePointLeft(b1); }
[ "public", "static", "BigDecimal", "sround", "(", "BigDecimal", "b0", ",", "int", "b1", ")", "{", "return", "b0", ".", "movePointRight", "(", "b1", ")", ".", "setScale", "(", "0", ",", "RoundingMode", ".", "HALF_UP", ")", ".", "movePointLeft", "(", "b1", ")", ";", "}" ]
SQL <code>ROUND</code> operator applied to BigDecimal values.
[ "SQL", "<code", ">", "ROUND<", "/", "code", ">", "operator", "applied", "to", "BigDecimal", "values", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java#L772-L775
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-blame/xwiki-commons-blame-api/src/main/java/org/xwiki/blame/internal/DefaultAnnotatedContent.java
DefaultAnnotatedContent.analyseRevision
void analyseRevision(R revision, List<E> previous) { """ Resolve revision of line to current revision based on given previous content, and prepare for next analysis. @param revision the revision of the content provided. @param previous the content in a previous revision. """ if (currentRevision == null) { return; } if (previous == null || previous.isEmpty()) { resolveRemainingToCurrent(); } else { resolveToCurrent(DiffUtils.diff(currentRevisionContent, previous).getDeltas()); assert currentRevisionContent.equals(previous) : "Patch application failed"; } currentRevision = revision; }
java
void analyseRevision(R revision, List<E> previous) { if (currentRevision == null) { return; } if (previous == null || previous.isEmpty()) { resolveRemainingToCurrent(); } else { resolveToCurrent(DiffUtils.diff(currentRevisionContent, previous).getDeltas()); assert currentRevisionContent.equals(previous) : "Patch application failed"; } currentRevision = revision; }
[ "void", "analyseRevision", "(", "R", "revision", ",", "List", "<", "E", ">", "previous", ")", "{", "if", "(", "currentRevision", "==", "null", ")", "{", "return", ";", "}", "if", "(", "previous", "==", "null", "||", "previous", ".", "isEmpty", "(", ")", ")", "{", "resolveRemainingToCurrent", "(", ")", ";", "}", "else", "{", "resolveToCurrent", "(", "DiffUtils", ".", "diff", "(", "currentRevisionContent", ",", "previous", ")", ".", "getDeltas", "(", ")", ")", ";", "assert", "currentRevisionContent", ".", "equals", "(", "previous", ")", ":", "\"Patch application failed\"", ";", "}", "currentRevision", "=", "revision", ";", "}" ]
Resolve revision of line to current revision based on given previous content, and prepare for next analysis. @param revision the revision of the content provided. @param previous the content in a previous revision.
[ "Resolve", "revision", "of", "line", "to", "current", "revision", "based", "on", "given", "previous", "content", "and", "prepare", "for", "next", "analysis", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-blame/xwiki-commons-blame-api/src/main/java/org/xwiki/blame/internal/DefaultAnnotatedContent.java#L118-L132
zaproxy/zaproxy
src/org/parosproxy/paros/view/AbstractParamContainerPanel.java
AbstractParamContainerPanel.showParamPanel
public void showParamPanel(String parent, String child) { """ ZAP: Made public so that other classes can specify which panel is displayed """ if (parent == null || child == null) { return; } AbstractParamPanel panel = tablePanel.get(parent); if (panel == null) { return; } showParamPanel(panel, parent); }
java
public void showParamPanel(String parent, String child) { if (parent == null || child == null) { return; } AbstractParamPanel panel = tablePanel.get(parent); if (panel == null) { return; } showParamPanel(panel, parent); }
[ "public", "void", "showParamPanel", "(", "String", "parent", ",", "String", "child", ")", "{", "if", "(", "parent", "==", "null", "||", "child", "==", "null", ")", "{", "return", ";", "}", "AbstractParamPanel", "panel", "=", "tablePanel", ".", "get", "(", "parent", ")", ";", "if", "(", "panel", "==", "null", ")", "{", "return", ";", "}", "showParamPanel", "(", "panel", ",", "parent", ")", ";", "}" ]
ZAP: Made public so that other classes can specify which panel is displayed
[ "ZAP", ":", "Made", "public", "so", "that", "other", "classes", "can", "specify", "which", "panel", "is", "displayed" ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/AbstractParamContainerPanel.java#L448-L459
xwiki/xwiki-rendering
xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/WikiPageUtil.java
WikiPageUtil.isValidXmlNameStartChar
public static boolean isValidXmlNameStartChar(char ch, boolean colonEnabled) { """ Returns <code>true</code> if the given value is a valid first character of an XML name. <p> See http://www.w3.org/TR/xml/#NT-NameStartChar. </p> @param ch the character to check @param colonEnabled if this flag is <code>true</code> then this method accepts the ':' symbol. @return <code>true</code> if the given value is a valid first character for an XML name """ if (ch == ':') { return colonEnabled; } return (ch >= 'A' && ch <= 'Z') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 0xC0 && ch <= 0xD6) || (ch >= 0xD8 && ch <= 0xF6) || (ch >= 0xF8 && ch <= 0x2FF) || (ch >= 0x370 && ch <= 0x37D) || (ch >= 0x37F && ch <= 0x1FFF) || (ch >= 0x200C && ch <= 0x200D) || (ch >= 0x2070 && ch <= 0x218F) || (ch >= 0x2C00 && ch <= 0x2FEF) || (ch >= 0x3001 && ch <= 0xD7FF) || (ch >= 0xF900 && ch <= 0xFDCF) || (ch >= 0xFDF0 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0xEFFFF); }
java
public static boolean isValidXmlNameStartChar(char ch, boolean colonEnabled) { if (ch == ':') { return colonEnabled; } return (ch >= 'A' && ch <= 'Z') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 0xC0 && ch <= 0xD6) || (ch >= 0xD8 && ch <= 0xF6) || (ch >= 0xF8 && ch <= 0x2FF) || (ch >= 0x370 && ch <= 0x37D) || (ch >= 0x37F && ch <= 0x1FFF) || (ch >= 0x200C && ch <= 0x200D) || (ch >= 0x2070 && ch <= 0x218F) || (ch >= 0x2C00 && ch <= 0x2FEF) || (ch >= 0x3001 && ch <= 0xD7FF) || (ch >= 0xF900 && ch <= 0xFDCF) || (ch >= 0xFDF0 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0xEFFFF); }
[ "public", "static", "boolean", "isValidXmlNameStartChar", "(", "char", "ch", ",", "boolean", "colonEnabled", ")", "{", "if", "(", "ch", "==", "'", "'", ")", "{", "return", "colonEnabled", ";", "}", "return", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "ch", "==", "'", "'", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", ">=", "0xC0", "&&", "ch", "<=", "0xD6", ")", "||", "(", "ch", ">=", "0xD8", "&&", "ch", "<=", "0xF6", ")", "||", "(", "ch", ">=", "0xF8", "&&", "ch", "<=", "0x2FF", ")", "||", "(", "ch", ">=", "0x370", "&&", "ch", "<=", "0x37D", ")", "||", "(", "ch", ">=", "0x37F", "&&", "ch", "<=", "0x1FFF", ")", "||", "(", "ch", ">=", "0x200C", "&&", "ch", "<=", "0x200D", ")", "||", "(", "ch", ">=", "0x2070", "&&", "ch", "<=", "0x218F", ")", "||", "(", "ch", ">=", "0x2C00", "&&", "ch", "<=", "0x2FEF", ")", "||", "(", "ch", ">=", "0x3001", "&&", "ch", "<=", "0xD7FF", ")", "||", "(", "ch", ">=", "0xF900", "&&", "ch", "<=", "0xFDCF", ")", "||", "(", "ch", ">=", "0xFDF0", "&&", "ch", "<=", "0xFFFD", ")", "||", "(", "ch", ">=", "0x10000", "&&", "ch", "<=", "0xEFFFF", ")", ";", "}" ]
Returns <code>true</code> if the given value is a valid first character of an XML name. <p> See http://www.w3.org/TR/xml/#NT-NameStartChar. </p> @param ch the character to check @param colonEnabled if this flag is <code>true</code> then this method accepts the ':' symbol. @return <code>true</code> if the given value is a valid first character for an XML name
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "given", "value", "is", "a", "valid", "first", "character", "of", "an", "XML", "name", ".", "<p", ">", "See", "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "xml", "/", "#NT", "-", "NameStartChar", ".", "<", "/", "p", ">" ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/WikiPageUtil.java#L291-L311
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/TreeCRI.java
TreeCRI.execute
public boolean execute(Context context) throws Exception { """ Implementation of the {@link Command} interface for using this class as part of a Chain of Responsibility. @param context the Chain's context object @return <code>true</code> if the request was handled by this command; <code>false</code> otherwise @throws Exception any exception that is throw during processing """ assert context != null; assert context instanceof WebChainContext; assert ((WebChainContext)context).getServletRequest() instanceof HttpServletRequest; assert ((WebChainContext)context).getServletResponse() instanceof HttpServletResponse; WebChainContext webChainContext = (WebChainContext)context; HttpServletRequest request = (HttpServletRequest)webChainContext.getServletRequest(); HttpServletResponse response = (HttpServletResponse)webChainContext.getServletResponse(); String cmd = parseCommand(request.getRequestURI()); return render(request, response, webChainContext.getServletContext(), cmd); }
java
public boolean execute(Context context) throws Exception { assert context != null; assert context instanceof WebChainContext; assert ((WebChainContext)context).getServletRequest() instanceof HttpServletRequest; assert ((WebChainContext)context).getServletResponse() instanceof HttpServletResponse; WebChainContext webChainContext = (WebChainContext)context; HttpServletRequest request = (HttpServletRequest)webChainContext.getServletRequest(); HttpServletResponse response = (HttpServletResponse)webChainContext.getServletResponse(); String cmd = parseCommand(request.getRequestURI()); return render(request, response, webChainContext.getServletContext(), cmd); }
[ "public", "boolean", "execute", "(", "Context", "context", ")", "throws", "Exception", "{", "assert", "context", "!=", "null", ";", "assert", "context", "instanceof", "WebChainContext", ";", "assert", "(", "(", "WebChainContext", ")", "context", ")", ".", "getServletRequest", "(", ")", "instanceof", "HttpServletRequest", ";", "assert", "(", "(", "WebChainContext", ")", "context", ")", ".", "getServletResponse", "(", ")", "instanceof", "HttpServletResponse", ";", "WebChainContext", "webChainContext", "=", "(", "WebChainContext", ")", "context", ";", "HttpServletRequest", "request", "=", "(", "HttpServletRequest", ")", "webChainContext", ".", "getServletRequest", "(", ")", ";", "HttpServletResponse", "response", "=", "(", "HttpServletResponse", ")", "webChainContext", ".", "getServletResponse", "(", ")", ";", "String", "cmd", "=", "parseCommand", "(", "request", ".", "getRequestURI", "(", ")", ")", ";", "return", "render", "(", "request", ",", "response", ",", "webChainContext", ".", "getServletContext", "(", ")", ",", "cmd", ")", ";", "}" ]
Implementation of the {@link Command} interface for using this class as part of a Chain of Responsibility. @param context the Chain's context object @return <code>true</code> if the request was handled by this command; <code>false</code> otherwise @throws Exception any exception that is throw during processing
[ "Implementation", "of", "the", "{", "@link", "Command", "}", "interface", "for", "using", "this", "class", "as", "part", "of", "a", "Chain", "of", "Responsibility", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/TreeCRI.java#L65-L79
OpenLiberty/open-liberty
dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/container/config/ConfigElementList.java
ConfigElementList.removeBy
public E removeBy(String attributeName, String attributeValue) { """ Removes the first element in this list with a matching attribute name/value @param attributeName the attribute for which to search (Example: jndiName) @param attributeValue the value to match @return the removed element, or null of no element was removed """ // traverses the list twice, but reuse code E element = this.getBy(attributeName, attributeValue); if (element != null) { this.remove(element); // this should always return true since we already found the element } return element; }
java
public E removeBy(String attributeName, String attributeValue) { // traverses the list twice, but reuse code E element = this.getBy(attributeName, attributeValue); if (element != null) { this.remove(element); // this should always return true since we already found the element } return element; }
[ "public", "E", "removeBy", "(", "String", "attributeName", ",", "String", "attributeValue", ")", "{", "// traverses the list twice, but reuse code", "E", "element", "=", "this", ".", "getBy", "(", "attributeName", ",", "attributeValue", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "this", ".", "remove", "(", "element", ")", ";", "// this should always return true since we already found the element", "}", "return", "element", ";", "}" ]
Removes the first element in this list with a matching attribute name/value @param attributeName the attribute for which to search (Example: jndiName) @param attributeValue the value to match @return the removed element, or null of no element was removed
[ "Removes", "the", "first", "element", "in", "this", "list", "with", "a", "matching", "attribute", "name", "/", "value" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/container/config/ConfigElementList.java#L112-L119
apache/groovy
src/main/java/org/codehaus/groovy/control/ClassNodeResolver.java
ClassNodeResolver.resolveName
public LookupResult resolveName(String name, CompilationUnit compilationUnit) { """ Resolves the name of a class to a SourceUnit or ClassNode. If no class or source is found this method returns null. A lookup is done by first asking the cache if there is an entry for the class already available to then call {@link #findClassNode(String, CompilationUnit)}. The result of that method call will be cached if a ClassNode is found. If a SourceUnit is found, this method will not be asked later on again for that class, because ResolveVisitor will first ask the CompilationUnit for classes in the compilation queue and it will find the class for that SourceUnit there then. method return a ClassNode instead of a SourceUnit, the res @param name - the name of the class @param compilationUnit - the current CompilationUnit @return the LookupResult """ ClassNode res = getFromClassCache(name); if (res==NO_CLASS) return null; if (res!=null) return new LookupResult(null,res); LookupResult lr = findClassNode(name, compilationUnit); if (lr != null) { if (lr.isClassNode()) cacheClass(name, lr.getClassNode()); return lr; } else { cacheClass(name, NO_CLASS); return null; } }
java
public LookupResult resolveName(String name, CompilationUnit compilationUnit) { ClassNode res = getFromClassCache(name); if (res==NO_CLASS) return null; if (res!=null) return new LookupResult(null,res); LookupResult lr = findClassNode(name, compilationUnit); if (lr != null) { if (lr.isClassNode()) cacheClass(name, lr.getClassNode()); return lr; } else { cacheClass(name, NO_CLASS); return null; } }
[ "public", "LookupResult", "resolveName", "(", "String", "name", ",", "CompilationUnit", "compilationUnit", ")", "{", "ClassNode", "res", "=", "getFromClassCache", "(", "name", ")", ";", "if", "(", "res", "==", "NO_CLASS", ")", "return", "null", ";", "if", "(", "res", "!=", "null", ")", "return", "new", "LookupResult", "(", "null", ",", "res", ")", ";", "LookupResult", "lr", "=", "findClassNode", "(", "name", ",", "compilationUnit", ")", ";", "if", "(", "lr", "!=", "null", ")", "{", "if", "(", "lr", ".", "isClassNode", "(", ")", ")", "cacheClass", "(", "name", ",", "lr", ".", "getClassNode", "(", ")", ")", ";", "return", "lr", ";", "}", "else", "{", "cacheClass", "(", "name", ",", "NO_CLASS", ")", ";", "return", "null", ";", "}", "}" ]
Resolves the name of a class to a SourceUnit or ClassNode. If no class or source is found this method returns null. A lookup is done by first asking the cache if there is an entry for the class already available to then call {@link #findClassNode(String, CompilationUnit)}. The result of that method call will be cached if a ClassNode is found. If a SourceUnit is found, this method will not be asked later on again for that class, because ResolveVisitor will first ask the CompilationUnit for classes in the compilation queue and it will find the class for that SourceUnit there then. method return a ClassNode instead of a SourceUnit, the res @param name - the name of the class @param compilationUnit - the current CompilationUnit @return the LookupResult
[ "Resolves", "the", "name", "of", "a", "class", "to", "a", "SourceUnit", "or", "ClassNode", ".", "If", "no", "class", "or", "source", "is", "found", "this", "method", "returns", "null", ".", "A", "lookup", "is", "done", "by", "first", "asking", "the", "cache", "if", "there", "is", "an", "entry", "for", "the", "class", "already", "available", "to", "then", "call", "{" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/control/ClassNodeResolver.java#L121-L133
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.validIndex
public static <T> T[] validIndex(final T[] array, final int index) { """ <p>Validates that the index is within the bounds of the argument array; otherwise throwing an exception.</p> <pre>Validate.validIndex(myArray, 2);</pre> <p>If the array is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p> <p>If the index is invalid, then the message of the exception is &quot;The validated array index is invalid: &quot; followed by the index.</p> @param <T> the array type @param array the array to check, validated not null by this method @param index the index to check @return the validated array (never {@code null} for method chaining) @throws NullPointerException if the array is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(Object[], int, String, Object...) @since 3.0 """ return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); }
java
public static <T> T[] validIndex(final T[] array, final int index) { return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); }
[ "public", "static", "<", "T", ">", "T", "[", "]", "validIndex", "(", "final", "T", "[", "]", "array", ",", "final", "int", "index", ")", "{", "return", "validIndex", "(", "array", ",", "index", ",", "DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE", ",", "Integer", ".", "valueOf", "(", "index", ")", ")", ";", "}" ]
<p>Validates that the index is within the bounds of the argument array; otherwise throwing an exception.</p> <pre>Validate.validIndex(myArray, 2);</pre> <p>If the array is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p> <p>If the index is invalid, then the message of the exception is &quot;The validated array index is invalid: &quot; followed by the index.</p> @param <T> the array type @param array the array to check, validated not null by this method @param index the index to check @return the validated array (never {@code null} for method chaining) @throws NullPointerException if the array is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(Object[], int, String, Object...) @since 3.0
[ "<p", ">", "Validates", "that", "the", "index", "is", "within", "the", "bounds", "of", "the", "argument", "array", ";", "otherwise", "throwing", "an", "exception", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L668-L670
padrig64/ValidationFramework
validationframework-swing/src/main/java/com/google/code/validationframework/swing/property/JTableRolloverCellProperty.java
JTableRolloverCellProperty.updateValue
private void updateValue(Point location) { """ Updates the value of this property based on the location of the mouse pointer. @param location Location of the mouse in the relatively to the table. """ CellPosition oldValue = value; if (location == null) { value = null; } else { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); value = new CellPosition(row, column); } maybeNotifyListeners(oldValue, value); }
java
private void updateValue(Point location) { CellPosition oldValue = value; if (location == null) { value = null; } else { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); value = new CellPosition(row, column); } maybeNotifyListeners(oldValue, value); }
[ "private", "void", "updateValue", "(", "Point", "location", ")", "{", "CellPosition", "oldValue", "=", "value", ";", "if", "(", "location", "==", "null", ")", "{", "value", "=", "null", ";", "}", "else", "{", "int", "row", "=", "table", ".", "rowAtPoint", "(", "location", ")", ";", "int", "column", "=", "table", ".", "columnAtPoint", "(", "location", ")", ";", "value", "=", "new", "CellPosition", "(", "row", ",", "column", ")", ";", "}", "maybeNotifyListeners", "(", "oldValue", ",", "value", ")", ";", "}" ]
Updates the value of this property based on the location of the mouse pointer. @param location Location of the mouse in the relatively to the table.
[ "Updates", "the", "value", "of", "this", "property", "based", "on", "the", "location", "of", "the", "mouse", "pointer", "." ]
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/property/JTableRolloverCellProperty.java#L104-L114
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java
MmtfStructureWriter.addBonds
private void addBonds(Atom atom, List<Atom> atomsInGroup, List<Atom> allAtoms) { """ Add the bonds for a given atom. @param atom the atom for which bonds are to be formed @param atomsInGroup the list of atoms in the group @param allAtoms the list of atoms in the whole structure """ if(atom.getBonds()==null){ return; } for(Bond bond : atom.getBonds()) { // Now set the bonding information. Atom other = bond.getOther(atom); // If both atoms are in the group if (atomsInGroup.indexOf(other)!=-1){ Integer firstBondIndex = atomsInGroup.indexOf(atom); Integer secondBondIndex = atomsInGroup.indexOf(other); // Don't add the same bond twice if(firstBondIndex>secondBondIndex){ int bondOrder = bond.getBondOrder(); mmtfDecoderInterface.setGroupBond(firstBondIndex, secondBondIndex, bondOrder); } } // Otherwise it's an inter group bond - so add it here else { Integer firstBondIndex = allAtoms.indexOf(atom); Integer secondBondIndex = allAtoms.indexOf(other); if(firstBondIndex>secondBondIndex){ // Don't add the same bond twice int bondOrder = bond.getBondOrder(); mmtfDecoderInterface.setInterGroupBond(firstBondIndex, secondBondIndex, bondOrder); } } } }
java
private void addBonds(Atom atom, List<Atom> atomsInGroup, List<Atom> allAtoms) { if(atom.getBonds()==null){ return; } for(Bond bond : atom.getBonds()) { // Now set the bonding information. Atom other = bond.getOther(atom); // If both atoms are in the group if (atomsInGroup.indexOf(other)!=-1){ Integer firstBondIndex = atomsInGroup.indexOf(atom); Integer secondBondIndex = atomsInGroup.indexOf(other); // Don't add the same bond twice if(firstBondIndex>secondBondIndex){ int bondOrder = bond.getBondOrder(); mmtfDecoderInterface.setGroupBond(firstBondIndex, secondBondIndex, bondOrder); } } // Otherwise it's an inter group bond - so add it here else { Integer firstBondIndex = allAtoms.indexOf(atom); Integer secondBondIndex = allAtoms.indexOf(other); if(firstBondIndex>secondBondIndex){ // Don't add the same bond twice int bondOrder = bond.getBondOrder(); mmtfDecoderInterface.setInterGroupBond(firstBondIndex, secondBondIndex, bondOrder); } } } }
[ "private", "void", "addBonds", "(", "Atom", "atom", ",", "List", "<", "Atom", ">", "atomsInGroup", ",", "List", "<", "Atom", ">", "allAtoms", ")", "{", "if", "(", "atom", ".", "getBonds", "(", ")", "==", "null", ")", "{", "return", ";", "}", "for", "(", "Bond", "bond", ":", "atom", ".", "getBonds", "(", ")", ")", "{", "// Now set the bonding information.", "Atom", "other", "=", "bond", ".", "getOther", "(", "atom", ")", ";", "// If both atoms are in the group", "if", "(", "atomsInGroup", ".", "indexOf", "(", "other", ")", "!=", "-", "1", ")", "{", "Integer", "firstBondIndex", "=", "atomsInGroup", ".", "indexOf", "(", "atom", ")", ";", "Integer", "secondBondIndex", "=", "atomsInGroup", ".", "indexOf", "(", "other", ")", ";", "// Don't add the same bond twice", "if", "(", "firstBondIndex", ">", "secondBondIndex", ")", "{", "int", "bondOrder", "=", "bond", ".", "getBondOrder", "(", ")", ";", "mmtfDecoderInterface", ".", "setGroupBond", "(", "firstBondIndex", ",", "secondBondIndex", ",", "bondOrder", ")", ";", "}", "}", "// Otherwise it's an inter group bond - so add it here", "else", "{", "Integer", "firstBondIndex", "=", "allAtoms", ".", "indexOf", "(", "atom", ")", ";", "Integer", "secondBondIndex", "=", "allAtoms", ".", "indexOf", "(", "other", ")", ";", "if", "(", "firstBondIndex", ">", "secondBondIndex", ")", "{", "// Don't add the same bond twice", "int", "bondOrder", "=", "bond", ".", "getBondOrder", "(", ")", ";", "mmtfDecoderInterface", ".", "setInterGroupBond", "(", "firstBondIndex", ",", "secondBondIndex", ",", "bondOrder", ")", ";", "}", "}", "}", "}" ]
Add the bonds for a given atom. @param atom the atom for which bonds are to be formed @param atomsInGroup the list of atoms in the group @param allAtoms the list of atoms in the whole structure
[ "Add", "the", "bonds", "for", "a", "given", "atom", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java#L132-L160
zandero/rest.vertx
src/main/java/com/zandero/rest/data/ClassFactory.java
ClassFactory.constructViaConstructor
static <T> Pair<Boolean, T> constructViaConstructor(Class<T> type, String fromValue) { """ have a constructor that accepts a single argument (String or any other primitive type that can be converted from String) Pair(success, object) """ Constructor[] allConstructors = type.getDeclaredConstructors(); for (Constructor ctor : allConstructors) { Class<?>[] pType = ctor.getParameterTypes(); if (pType.length == 1) { // ok ... match ... might be possible to use try { for (Class primitive : SIMPLE_TYPE) { if (pType[0].isAssignableFrom(primitive)) { Object value = stringToPrimitiveType(fromValue, primitive); return new Pair(true, ctor.newInstance(value)); } } } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { //continue; // try next one ... if any log.warn("Failed constructing: " + ctor, e); } } } return new Pair<>(false, null); }
java
static <T> Pair<Boolean, T> constructViaConstructor(Class<T> type, String fromValue) { Constructor[] allConstructors = type.getDeclaredConstructors(); for (Constructor ctor : allConstructors) { Class<?>[] pType = ctor.getParameterTypes(); if (pType.length == 1) { // ok ... match ... might be possible to use try { for (Class primitive : SIMPLE_TYPE) { if (pType[0].isAssignableFrom(primitive)) { Object value = stringToPrimitiveType(fromValue, primitive); return new Pair(true, ctor.newInstance(value)); } } } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { //continue; // try next one ... if any log.warn("Failed constructing: " + ctor, e); } } } return new Pair<>(false, null); }
[ "static", "<", "T", ">", "Pair", "<", "Boolean", ",", "T", ">", "constructViaConstructor", "(", "Class", "<", "T", ">", "type", ",", "String", "fromValue", ")", "{", "Constructor", "[", "]", "allConstructors", "=", "type", ".", "getDeclaredConstructors", "(", ")", ";", "for", "(", "Constructor", "ctor", ":", "allConstructors", ")", "{", "Class", "<", "?", ">", "[", "]", "pType", "=", "ctor", ".", "getParameterTypes", "(", ")", ";", "if", "(", "pType", ".", "length", "==", "1", ")", "{", "// ok ... match ... might be possible to use", "try", "{", "for", "(", "Class", "primitive", ":", "SIMPLE_TYPE", ")", "{", "if", "(", "pType", "[", "0", "]", ".", "isAssignableFrom", "(", "primitive", ")", ")", "{", "Object", "value", "=", "stringToPrimitiveType", "(", "fromValue", ",", "primitive", ")", ";", "return", "new", "Pair", "(", "true", ",", "ctor", ".", "newInstance", "(", "value", ")", ")", ";", "}", "}", "}", "catch", "(", "IllegalAccessException", "|", "InstantiationException", "|", "InvocationTargetException", "e", ")", "{", "//continue; // try next one ... if any", "log", ".", "warn", "(", "\"Failed constructing: \"", "+", "ctor", ",", "e", ")", ";", "}", "}", "}", "return", "new", "Pair", "<>", "(", "false", ",", "null", ")", ";", "}" ]
have a constructor that accepts a single argument (String or any other primitive type that can be converted from String) Pair(success, object)
[ "have", "a", "constructor", "that", "accepts", "a", "single", "argument", "(", "String", "or", "any", "other", "primitive", "type", "that", "can", "be", "converted", "from", "String", ")", "Pair", "(", "success", "object", ")" ]
train
https://github.com/zandero/rest.vertx/blob/ba458720cf59e076953eab9dac7227eeaf9e58ce/src/main/java/com/zandero/rest/data/ClassFactory.java#L506-L533
geomajas/geomajas-project-client-gwt
plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/factory/FeatureDetailWidgetFactory.java
FeatureDetailWidgetFactory.createDefaultFeatureDetailWindow
public static Window createDefaultFeatureDetailWindow(Feature feature, Layer<?> layer, boolean editingAllowed) { """ Overrule configuration and create Geomajas default FeatureAttributeWindow. @param feature @param editingAllowed @return """ if (layer instanceof VectorLayer) { FeatureAttributeWindow w = new FeatureAttributeWindow(feature, editingAllowed); customize(w, feature); return w; } else { return new RasterLayerAttributeWindow(feature); } }
java
public static Window createDefaultFeatureDetailWindow(Feature feature, Layer<?> layer, boolean editingAllowed) { if (layer instanceof VectorLayer) { FeatureAttributeWindow w = new FeatureAttributeWindow(feature, editingAllowed); customize(w, feature); return w; } else { return new RasterLayerAttributeWindow(feature); } }
[ "public", "static", "Window", "createDefaultFeatureDetailWindow", "(", "Feature", "feature", ",", "Layer", "<", "?", ">", "layer", ",", "boolean", "editingAllowed", ")", "{", "if", "(", "layer", "instanceof", "VectorLayer", ")", "{", "FeatureAttributeWindow", "w", "=", "new", "FeatureAttributeWindow", "(", "feature", ",", "editingAllowed", ")", ";", "customize", "(", "w", ",", "feature", ")", ";", "return", "w", ";", "}", "else", "{", "return", "new", "RasterLayerAttributeWindow", "(", "feature", ")", ";", "}", "}" ]
Overrule configuration and create Geomajas default FeatureAttributeWindow. @param feature @param editingAllowed @return
[ "Overrule", "configuration", "and", "create", "Geomajas", "default", "FeatureAttributeWindow", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/factory/FeatureDetailWidgetFactory.java#L77-L85
box/box-java-sdk
src/main/java/com/box/sdk/BoxAPIResponse.java
BoxAPIResponse.getBody
public InputStream getBody(ProgressListener listener) { """ Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener. @param listener a listener for monitoring the read progress of the body. @return an InputStream for reading the response's body. """ if (this.inputStream == null) { String contentEncoding = this.connection.getContentEncoding(); try { if (this.rawInputStream == null) { this.rawInputStream = this.connection.getInputStream(); } if (listener == null) { this.inputStream = this.rawInputStream; } else { this.inputStream = new ProgressInputStream(this.rawInputStream, listener, this.getContentLength()); } if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { this.inputStream = new GZIPInputStream(this.inputStream); } } catch (IOException e) { throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); } } return this.inputStream; }
java
public InputStream getBody(ProgressListener listener) { if (this.inputStream == null) { String contentEncoding = this.connection.getContentEncoding(); try { if (this.rawInputStream == null) { this.rawInputStream = this.connection.getInputStream(); } if (listener == null) { this.inputStream = this.rawInputStream; } else { this.inputStream = new ProgressInputStream(this.rawInputStream, listener, this.getContentLength()); } if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { this.inputStream = new GZIPInputStream(this.inputStream); } } catch (IOException e) { throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); } } return this.inputStream; }
[ "public", "InputStream", "getBody", "(", "ProgressListener", "listener", ")", "{", "if", "(", "this", ".", "inputStream", "==", "null", ")", "{", "String", "contentEncoding", "=", "this", ".", "connection", ".", "getContentEncoding", "(", ")", ";", "try", "{", "if", "(", "this", ".", "rawInputStream", "==", "null", ")", "{", "this", ".", "rawInputStream", "=", "this", ".", "connection", ".", "getInputStream", "(", ")", ";", "}", "if", "(", "listener", "==", "null", ")", "{", "this", ".", "inputStream", "=", "this", ".", "rawInputStream", ";", "}", "else", "{", "this", ".", "inputStream", "=", "new", "ProgressInputStream", "(", "this", ".", "rawInputStream", ",", "listener", ",", "this", ".", "getContentLength", "(", ")", ")", ";", "}", "if", "(", "contentEncoding", "!=", "null", "&&", "contentEncoding", ".", "equalsIgnoreCase", "(", "\"gzip\"", ")", ")", "{", "this", ".", "inputStream", "=", "new", "GZIPInputStream", "(", "this", ".", "inputStream", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "BoxAPIException", "(", "\"Couldn't connect to the Box API due to a network error.\"", ",", "e", ")", ";", "}", "}", "return", "this", ".", "inputStream", ";", "}" ]
Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener. @param listener a listener for monitoring the read progress of the body. @return an InputStream for reading the response's body.
[ "Gets", "an", "InputStream", "for", "reading", "this", "response", "s", "body", "which", "will", "report", "its", "read", "progress", "to", "a", "ProgressListener", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxAPIResponse.java#L145-L169
Jacksgong/JKeyboardPanelSwitch
library/src/main/java/cn/dreamtobe/kpswitch/util/KPSwitchConflictUtil.java
KPSwitchConflictUtil.switchPanelAndKeyboard
public static boolean switchPanelAndKeyboard(final View panelLayout, final View focusView) { """ If the keyboard is showing, then going to show the {@code panelLayout}, and hide the keyboard with non-layout-conflict. <p/> If the panel is showing, then going to show the keyboard, and hide the {@code panelLayout} with non-layout-conflict. <p/> If the panel and the keyboard are both hiding. then going to show the {@code panelLayout} with non-layout-conflict. @param panelLayout the layout of panel. @param focusView the view will be focused or lose the focus. @return If true, switch to showing {@code panelLayout}; If false, switch to showing Keyboard. """ boolean switchToPanel = panelLayout.getVisibility() != View.VISIBLE; if (!switchToPanel) { showKeyboard(panelLayout, focusView); } else { showPanel(panelLayout); } return switchToPanel; }
java
public static boolean switchPanelAndKeyboard(final View panelLayout, final View focusView) { boolean switchToPanel = panelLayout.getVisibility() != View.VISIBLE; if (!switchToPanel) { showKeyboard(panelLayout, focusView); } else { showPanel(panelLayout); } return switchToPanel; }
[ "public", "static", "boolean", "switchPanelAndKeyboard", "(", "final", "View", "panelLayout", ",", "final", "View", "focusView", ")", "{", "boolean", "switchToPanel", "=", "panelLayout", ".", "getVisibility", "(", ")", "!=", "View", ".", "VISIBLE", ";", "if", "(", "!", "switchToPanel", ")", "{", "showKeyboard", "(", "panelLayout", ",", "focusView", ")", ";", "}", "else", "{", "showPanel", "(", "panelLayout", ")", ";", "}", "return", "switchToPanel", ";", "}" ]
If the keyboard is showing, then going to show the {@code panelLayout}, and hide the keyboard with non-layout-conflict. <p/> If the panel is showing, then going to show the keyboard, and hide the {@code panelLayout} with non-layout-conflict. <p/> If the panel and the keyboard are both hiding. then going to show the {@code panelLayout} with non-layout-conflict. @param panelLayout the layout of panel. @param focusView the view will be focused or lose the focus. @return If true, switch to showing {@code panelLayout}; If false, switch to showing Keyboard.
[ "If", "the", "keyboard", "is", "showing", "then", "going", "to", "show", "the", "{", "@code", "panelLayout", "}", "and", "hide", "the", "keyboard", "with", "non", "-", "layout", "-", "conflict", ".", "<p", "/", ">", "If", "the", "panel", "is", "showing", "then", "going", "to", "show", "the", "keyboard", "and", "hide", "the", "{", "@code", "panelLayout", "}", "with", "non", "-", "layout", "-", "conflict", ".", "<p", "/", ">", "If", "the", "panel", "and", "the", "keyboard", "are", "both", "hiding", ".", "then", "going", "to", "show", "the", "{", "@code", "panelLayout", "}", "with", "non", "-", "layout", "-", "conflict", "." ]
train
https://github.com/Jacksgong/JKeyboardPanelSwitch/blob/092128023e824c85da63540780c79088b37a0c74/library/src/main/java/cn/dreamtobe/kpswitch/util/KPSwitchConflictUtil.java#L227-L236
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/reportv2/ReportClient.java
ReportClient.getMessageStatistic
public MessageStatListResult getMessageStatistic(String timeUnit, String start, int duration) throws APIConnectionException, APIRequestException { """ Get message statistic. Detail instructions please refer to https://docs.jiguang.cn/jmessage/server/rest_api_im_report_v2/#_6 @param timeUnit MUST be one of HOUR, DAY, MONTH @param start start time, when timeUnit is HOUR, format: yyyy-MM-dd HH, @param duration depends on timeUnit, the duration has limit @return {@link MessageStatListResult} @throws APIConnectionException connect exception @throws APIRequestException request exception """ Preconditions.checkArgument(verifyDateFormat(timeUnit, start), "Time format error, please check your argument"); if (timeUnit.equals("HOUR")) { Preconditions.checkArgument(0 <= duration && duration <= 24, "time unit is HOUR, duration must between 0 and 24 "); } else if (timeUnit.equals("DAY")) { Preconditions.checkArgument(0 <= duration && duration <= 60, "time unit is DAY, duration must between 0 and 60"); } else if (timeUnit.equals("MONTH")) { Preconditions.checkArgument(0 <= duration && duration <= 2, "time unit is MONTH, duration must between 0 and 2"); } else throw new IllegalArgumentException("Time unit error"); String url = mBaseReportPath + mV2StatisticPath + "/messages?time_unit=" + timeUnit + "&start=" + start + "&duration=" + duration; ResponseWrapper responseWrapper = _httpClient.sendGet(url); return MessageStatListResult.fromResponse(responseWrapper, MessageStatListResult.class); }
java
public MessageStatListResult getMessageStatistic(String timeUnit, String start, int duration) throws APIConnectionException, APIRequestException { Preconditions.checkArgument(verifyDateFormat(timeUnit, start), "Time format error, please check your argument"); if (timeUnit.equals("HOUR")) { Preconditions.checkArgument(0 <= duration && duration <= 24, "time unit is HOUR, duration must between 0 and 24 "); } else if (timeUnit.equals("DAY")) { Preconditions.checkArgument(0 <= duration && duration <= 60, "time unit is DAY, duration must between 0 and 60"); } else if (timeUnit.equals("MONTH")) { Preconditions.checkArgument(0 <= duration && duration <= 2, "time unit is MONTH, duration must between 0 and 2"); } else throw new IllegalArgumentException("Time unit error"); String url = mBaseReportPath + mV2StatisticPath + "/messages?time_unit=" + timeUnit + "&start=" + start + "&duration=" + duration; ResponseWrapper responseWrapper = _httpClient.sendGet(url); return MessageStatListResult.fromResponse(responseWrapper, MessageStatListResult.class); }
[ "public", "MessageStatListResult", "getMessageStatistic", "(", "String", "timeUnit", ",", "String", "start", ",", "int", "duration", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "Preconditions", ".", "checkArgument", "(", "verifyDateFormat", "(", "timeUnit", ",", "start", ")", ",", "\"Time format error, please check your argument\"", ")", ";", "if", "(", "timeUnit", ".", "equals", "(", "\"HOUR\"", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "0", "<=", "duration", "&&", "duration", "<=", "24", ",", "\"time unit is HOUR, duration must between 0 and 24 \"", ")", ";", "}", "else", "if", "(", "timeUnit", ".", "equals", "(", "\"DAY\"", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "0", "<=", "duration", "&&", "duration", "<=", "60", ",", "\"time unit is DAY, duration must between 0 and 60\"", ")", ";", "}", "else", "if", "(", "timeUnit", ".", "equals", "(", "\"MONTH\"", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "0", "<=", "duration", "&&", "duration", "<=", "2", ",", "\"time unit is MONTH, duration must between 0 and 2\"", ")", ";", "}", "else", "throw", "new", "IllegalArgumentException", "(", "\"Time unit error\"", ")", ";", "String", "url", "=", "mBaseReportPath", "+", "mV2StatisticPath", "+", "\"/messages?time_unit=\"", "+", "timeUnit", "+", "\"&start=\"", "+", "start", "+", "\"&duration=\"", "+", "duration", ";", "ResponseWrapper", "responseWrapper", "=", "_httpClient", ".", "sendGet", "(", "url", ")", ";", "return", "MessageStatListResult", ".", "fromResponse", "(", "responseWrapper", ",", "MessageStatListResult", ".", "class", ")", ";", "}" ]
Get message statistic. Detail instructions please refer to https://docs.jiguang.cn/jmessage/server/rest_api_im_report_v2/#_6 @param timeUnit MUST be one of HOUR, DAY, MONTH @param start start time, when timeUnit is HOUR, format: yyyy-MM-dd HH, @param duration depends on timeUnit, the duration has limit @return {@link MessageStatListResult} @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "message", "statistic", ".", "Detail", "instructions", "please", "refer", "to", "https", ":", "//", "docs", ".", "jiguang", ".", "cn", "/", "jmessage", "/", "server", "/", "rest_api_im_report_v2", "/", "#_6" ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/reportv2/ReportClient.java#L273-L286
salesforce/Argus
ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AlertService.java
AlertService.updateAlert
public Alert updateAlert(BigInteger alertId, Alert alert) throws IOException, TokenExpiredException { """ Updates an existing alert. @param alertId The alert ID. @param alert The updated alert information. @return The updated alert. @throws IOException If the server cannot be reached. @throws TokenExpiredException If the token sent along with the request has expired """ String requestUrl = RESOURCE + "/" + alertId.toString(); ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.PUT, requestUrl, alert); assertValidResponse(response, requestUrl); return fromJson(response.getResult(), Alert.class); }
java
public Alert updateAlert(BigInteger alertId, Alert alert) throws IOException, TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId.toString(); ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.PUT, requestUrl, alert); assertValidResponse(response, requestUrl); return fromJson(response.getResult(), Alert.class); }
[ "public", "Alert", "updateAlert", "(", "BigInteger", "alertId", ",", "Alert", "alert", ")", "throws", "IOException", ",", "TokenExpiredException", "{", "String", "requestUrl", "=", "RESOURCE", "+", "\"/\"", "+", "alertId", ".", "toString", "(", ")", ";", "ArgusResponse", "response", "=", "getClient", "(", ")", ".", "executeHttpRequest", "(", "ArgusHttpClient", ".", "RequestType", ".", "PUT", ",", "requestUrl", ",", "alert", ")", ";", "assertValidResponse", "(", "response", ",", "requestUrl", ")", ";", "return", "fromJson", "(", "response", ".", "getResult", "(", ")", ",", "Alert", ".", "class", ")", ";", "}" ]
Updates an existing alert. @param alertId The alert ID. @param alert The updated alert information. @return The updated alert. @throws IOException If the server cannot be reached. @throws TokenExpiredException If the token sent along with the request has expired
[ "Updates", "an", "existing", "alert", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AlertService.java#L277-L283
jblas-project/jblas
src/main/java/org/jblas/ComplexFloat.java
ComplexFloat.addi
public ComplexFloat addi(ComplexFloat c, ComplexFloat result) { """ Add two complex numbers in-place @param c other complex number @param result complex number where result is stored @return same as result """ if (this == result) { r += c.r; i += c.i; } else { result.r = r + c.r; result.i = i + c.i; } return result; }
java
public ComplexFloat addi(ComplexFloat c, ComplexFloat result) { if (this == result) { r += c.r; i += c.i; } else { result.r = r + c.r; result.i = i + c.i; } return result; }
[ "public", "ComplexFloat", "addi", "(", "ComplexFloat", "c", ",", "ComplexFloat", "result", ")", "{", "if", "(", "this", "==", "result", ")", "{", "r", "+=", "c", ".", "r", ";", "i", "+=", "c", ".", "i", ";", "}", "else", "{", "result", ".", "r", "=", "r", "+", "c", ".", "r", ";", "result", ".", "i", "=", "i", "+", "c", ".", "i", ";", "}", "return", "result", ";", "}" ]
Add two complex numbers in-place @param c other complex number @param result complex number where result is stored @return same as result
[ "Add", "two", "complex", "numbers", "in", "-", "place" ]
train
https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/ComplexFloat.java#L101-L110
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java
MarkerUtil.redisplayMarkers
public static void redisplayMarkers(final IJavaProject javaProject) { """ Attempt to redisplay FindBugs problem markers for given project. @param javaProject the project """ final IProject project = javaProject.getProject(); FindBugsJob job = new FindBugsJob("Refreshing SpotBugs markers", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { // TODO in case we removed some of previously available // detectors, we should // throw away bugs reported by them // Get the saved bug collection for the project SortedBugCollection bugs = FindbugsPlugin.getBugCollection(project, monitor); // Remove old markers project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE); // Display warnings createMarkers(javaProject, bugs, project, monitor); } }; job.setRule(project); job.scheduleInteractive(); }
java
public static void redisplayMarkers(final IJavaProject javaProject) { final IProject project = javaProject.getProject(); FindBugsJob job = new FindBugsJob("Refreshing SpotBugs markers", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { // TODO in case we removed some of previously available // detectors, we should // throw away bugs reported by them // Get the saved bug collection for the project SortedBugCollection bugs = FindbugsPlugin.getBugCollection(project, monitor); // Remove old markers project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE); // Display warnings createMarkers(javaProject, bugs, project, monitor); } }; job.setRule(project); job.scheduleInteractive(); }
[ "public", "static", "void", "redisplayMarkers", "(", "final", "IJavaProject", "javaProject", ")", "{", "final", "IProject", "project", "=", "javaProject", ".", "getProject", "(", ")", ";", "FindBugsJob", "job", "=", "new", "FindBugsJob", "(", "\"Refreshing SpotBugs markers\"", ",", "project", ")", "{", "@", "Override", "protected", "void", "runWithProgress", "(", "IProgressMonitor", "monitor", ")", "throws", "CoreException", "{", "// TODO in case we removed some of previously available", "// detectors, we should", "// throw away bugs reported by them", "// Get the saved bug collection for the project", "SortedBugCollection", "bugs", "=", "FindbugsPlugin", ".", "getBugCollection", "(", "project", ",", "monitor", ")", ";", "// Remove old markers", "project", ".", "deleteMarkers", "(", "FindBugsMarker", ".", "NAME", ",", "true", ",", "IResource", ".", "DEPTH_INFINITE", ")", ";", "// Display warnings", "createMarkers", "(", "javaProject", ",", "bugs", ",", "project", ",", "monitor", ")", ";", "}", "}", ";", "job", ".", "setRule", "(", "project", ")", ";", "job", ".", "scheduleInteractive", "(", ")", ";", "}" ]
Attempt to redisplay FindBugs problem markers for given project. @param javaProject the project
[ "Attempt", "to", "redisplay", "FindBugs", "problem", "markers", "for", "given", "project", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java#L552-L571
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java
InternalListenerIntrospector.validateMethod
private void validateMethod(Method method, CallbackType callbackType) { """ Validates the given method to ensure if it is a valid callback method for the given event type. @param method the method to validate @param callbackType the callback type """ int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { String message = String.format("Method %s in class %s must be public", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isStatic(modifiers)) { String message = String.format("Method %s in class %s must not be static", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isAbstract(modifiers)) { String message = String.format("Method %s in class %s must not be abstract", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 0) { String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + "have any parameters. "; String message = String.format(pattern, method.getName(), method.getDeclaringClass().getName(), callbackType); throw new EntityManagerException(message); } if (method.getReturnType() != void.class) { String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), method.getDeclaringClass().getName(), void.class.getName()); throw new EntityManagerException(message); } }
java
private void validateMethod(Method method, CallbackType callbackType) { int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { String message = String.format("Method %s in class %s must be public", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isStatic(modifiers)) { String message = String.format("Method %s in class %s must not be static", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isAbstract(modifiers)) { String message = String.format("Method %s in class %s must not be abstract", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 0) { String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + "have any parameters. "; String message = String.format(pattern, method.getName(), method.getDeclaringClass().getName(), callbackType); throw new EntityManagerException(message); } if (method.getReturnType() != void.class) { String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), method.getDeclaringClass().getName(), void.class.getName()); throw new EntityManagerException(message); } }
[ "private", "void", "validateMethod", "(", "Method", "method", ",", "CallbackType", "callbackType", ")", "{", "int", "modifiers", "=", "method", ".", "getModifiers", "(", ")", ";", "if", "(", "!", "Modifier", ".", "isPublic", "(", "modifiers", ")", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Method %s in class %s must be public\"", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ")", ";", "throw", "new", "EntityManagerException", "(", "message", ")", ";", "}", "if", "(", "Modifier", ".", "isStatic", "(", "modifiers", ")", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Method %s in class %s must not be static\"", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ")", ";", "throw", "new", "EntityManagerException", "(", "message", ")", ";", "}", "if", "(", "Modifier", ".", "isAbstract", "(", "modifiers", ")", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Method %s in class %s must not be abstract\"", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ")", ";", "throw", "new", "EntityManagerException", "(", "message", ")", ";", "}", "Class", "<", "?", ">", "[", "]", "parameters", "=", "method", ".", "getParameterTypes", "(", ")", ";", "if", "(", "parameters", ".", "length", "!=", "0", ")", "{", "String", "pattern", "=", "\"Method %s in class %s is not a valid %s callback method. Method must not \"", "+", "\"have any parameters. \"", ";", "String", "message", "=", "String", ".", "format", "(", "pattern", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ",", "callbackType", ")", ";", "throw", "new", "EntityManagerException", "(", "message", ")", ";", "}", "if", "(", "method", ".", "getReturnType", "(", ")", "!=", "void", ".", "class", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Method %s in class %s must have a return type of %s\"", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ",", "void", ".", "class", ".", "getName", "(", ")", ")", ";", "throw", "new", "EntityManagerException", "(", "message", ")", ";", "}", "}" ]
Validates the given method to ensure if it is a valid callback method for the given event type. @param method the method to validate @param callbackType the callback type
[ "Validates", "the", "given", "method", "to", "ensure", "if", "it", "is", "a", "valid", "callback", "method", "for", "the", "given", "event", "type", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java#L113-L143
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj21/ClockSkewDetector.java
ClockSkewDetector.searchTime
private Element searchTime() throws IfmapErrorResult, IfmapException { """ Search for the self-published client time on {@link #mDev}. @return XML element with client and server timestamp @throws IfmapErrorResult @throws IfmapException """ SearchRequest sr; SearchResult res; List<ResultItem> items; ResultItem ri; List<Document> mlist; Node node; String resultFilter = IfmapStrings.OP_METADATA_PREFIX + ":client-time[@" + IfmapStrings.PUBLISHER_ID_ATTR + " = \"" + mSsrc.getPublisherId() + "\"]"; sr = Requests.createSearchReq(null, 0, null, null, resultFilter, mDev); sr.addNamespaceDeclaration(IfmapStrings.OP_METADATA_PREFIX, IfmapStrings.OP_METADATA_NS_URI); res = mSsrc.search(sr); items = res.getResultItems(); if (items.size() > 1) { IfmapJLog.warn("time sync: weird result item count: " + items.size()); } if (items.size() == 0) { throw new IfmapException("time sync", "No ResultItems for search!"); } ri = items.get(0); mlist = ri.getMetadata(); if (mlist.size() > 1) { IfmapJLog.warn("time sync: multiple client-time elements: " + mlist.size()); } if (mlist.size() == 0) { throw new IfmapException("time sync", "No client-time metadata!"); } // Take the last one in the list, hoping that it is the most current // one. Document clientTime = mlist.get(mlist.size() - 1); node = clientTime.getFirstChild(); if (node.getNodeType() != Node.ELEMENT_NODE) { throw new IfmapException("time sync", "Metadata is not element"); } return (Element) node; }
java
private Element searchTime() throws IfmapErrorResult, IfmapException { SearchRequest sr; SearchResult res; List<ResultItem> items; ResultItem ri; List<Document> mlist; Node node; String resultFilter = IfmapStrings.OP_METADATA_PREFIX + ":client-time[@" + IfmapStrings.PUBLISHER_ID_ATTR + " = \"" + mSsrc.getPublisherId() + "\"]"; sr = Requests.createSearchReq(null, 0, null, null, resultFilter, mDev); sr.addNamespaceDeclaration(IfmapStrings.OP_METADATA_PREFIX, IfmapStrings.OP_METADATA_NS_URI); res = mSsrc.search(sr); items = res.getResultItems(); if (items.size() > 1) { IfmapJLog.warn("time sync: weird result item count: " + items.size()); } if (items.size() == 0) { throw new IfmapException("time sync", "No ResultItems for search!"); } ri = items.get(0); mlist = ri.getMetadata(); if (mlist.size() > 1) { IfmapJLog.warn("time sync: multiple client-time elements: " + mlist.size()); } if (mlist.size() == 0) { throw new IfmapException("time sync", "No client-time metadata!"); } // Take the last one in the list, hoping that it is the most current // one. Document clientTime = mlist.get(mlist.size() - 1); node = clientTime.getFirstChild(); if (node.getNodeType() != Node.ELEMENT_NODE) { throw new IfmapException("time sync", "Metadata is not element"); } return (Element) node; }
[ "private", "Element", "searchTime", "(", ")", "throws", "IfmapErrorResult", ",", "IfmapException", "{", "SearchRequest", "sr", ";", "SearchResult", "res", ";", "List", "<", "ResultItem", ">", "items", ";", "ResultItem", "ri", ";", "List", "<", "Document", ">", "mlist", ";", "Node", "node", ";", "String", "resultFilter", "=", "IfmapStrings", ".", "OP_METADATA_PREFIX", "+", "\":client-time[@\"", "+", "IfmapStrings", ".", "PUBLISHER_ID_ATTR", "+", "\" = \\\"\"", "+", "mSsrc", ".", "getPublisherId", "(", ")", "+", "\"\\\"]\"", ";", "sr", "=", "Requests", ".", "createSearchReq", "(", "null", ",", "0", ",", "null", ",", "null", ",", "resultFilter", ",", "mDev", ")", ";", "sr", ".", "addNamespaceDeclaration", "(", "IfmapStrings", ".", "OP_METADATA_PREFIX", ",", "IfmapStrings", ".", "OP_METADATA_NS_URI", ")", ";", "res", "=", "mSsrc", ".", "search", "(", "sr", ")", ";", "items", "=", "res", ".", "getResultItems", "(", ")", ";", "if", "(", "items", ".", "size", "(", ")", ">", "1", ")", "{", "IfmapJLog", ".", "warn", "(", "\"time sync: weird result item count: \"", "+", "items", ".", "size", "(", ")", ")", ";", "}", "if", "(", "items", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "IfmapException", "(", "\"time sync\"", ",", "\"No ResultItems for search!\"", ")", ";", "}", "ri", "=", "items", ".", "get", "(", "0", ")", ";", "mlist", "=", "ri", ".", "getMetadata", "(", ")", ";", "if", "(", "mlist", ".", "size", "(", ")", ">", "1", ")", "{", "IfmapJLog", ".", "warn", "(", "\"time sync: multiple client-time elements: \"", "+", "mlist", ".", "size", "(", ")", ")", ";", "}", "if", "(", "mlist", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "IfmapException", "(", "\"time sync\"", ",", "\"No client-time metadata!\"", ")", ";", "}", "// Take the last one in the list, hoping that it is the most current", "// one.", "Document", "clientTime", "=", "mlist", ".", "get", "(", "mlist", ".", "size", "(", ")", "-", "1", ")", ";", "node", "=", "clientTime", ".", "getFirstChild", "(", ")", ";", "if", "(", "node", ".", "getNodeType", "(", ")", "!=", "Node", ".", "ELEMENT_NODE", ")", "{", "throw", "new", "IfmapException", "(", "\"time sync\"", ",", "\"Metadata is not element\"", ")", ";", "}", "return", "(", "Element", ")", "node", ";", "}" ]
Search for the self-published client time on {@link #mDev}. @return XML element with client and server timestamp @throws IfmapErrorResult @throws IfmapException
[ "Search", "for", "the", "self", "-", "published", "client", "time", "on", "{", "@link", "#mDev", "}", "." ]
train
https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj21/ClockSkewDetector.java#L293-L347
dbracewell/mango
src/main/java/com/davidbracewell/reflection/ReflectionUtils.java
ReflectionUtils.typesMatch
@SuppressWarnings("unchecked") public static boolean typesMatch(Class<?>[] c1, Class[] c2) { """ Determines if the two given arrays of class are compatible with one another. @param c1 array 1 @param c2 array 2 @return True if all classes are the same or those c1 are assignable from c2, otherwise false """ if (c1.length != c2.length) { return false; } for (int i = 0; i < c1.length; i++) { if (!inSameHierarchy(c1[i], c2[i]) && !isConvertible(c1[i], c2[i])) { return false; } } return true; }
java
@SuppressWarnings("unchecked") public static boolean typesMatch(Class<?>[] c1, Class[] c2) { if (c1.length != c2.length) { return false; } for (int i = 0; i < c1.length; i++) { if (!inSameHierarchy(c1[i], c2[i]) && !isConvertible(c1[i], c2[i])) { return false; } } return true; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "boolean", "typesMatch", "(", "Class", "<", "?", ">", "[", "]", "c1", ",", "Class", "[", "]", "c2", ")", "{", "if", "(", "c1", ".", "length", "!=", "c2", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "c1", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "inSameHierarchy", "(", "c1", "[", "i", "]", ",", "c2", "[", "i", "]", ")", "&&", "!", "isConvertible", "(", "c1", "[", "i", "]", ",", "c2", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determines if the two given arrays of class are compatible with one another. @param c1 array 1 @param c2 array 2 @return True if all classes are the same or those c1 are assignable from c2, otherwise false
[ "Determines", "if", "the", "two", "given", "arrays", "of", "class", "are", "compatible", "with", "one", "another", "." ]
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/reflection/ReflectionUtils.java#L376-L387
headius/invokebinder
src/main/java/com/headius/invokebinder/transform/Transform.java
Transform.buildClassCast
protected static void buildClassCast(StringBuilder builder, Class cls) { """ Build Java code to represent a cast to the given type. This will be an argument of the form "(pkg.Cls1)" or "(pkg.Cls2[])" or "(primtype)" @param builder the builder in which to build the argument @param cls the type for the argument """ builder.append('('); buildClass(builder, cls); builder.append(')'); }
java
protected static void buildClassCast(StringBuilder builder, Class cls) { builder.append('('); buildClass(builder, cls); builder.append(')'); }
[ "protected", "static", "void", "buildClassCast", "(", "StringBuilder", "builder", ",", "Class", "cls", ")", "{", "builder", ".", "append", "(", "'", "'", ")", ";", "buildClass", "(", "builder", ",", "cls", ")", ";", "builder", ".", "append", "(", "'", "'", ")", ";", "}" ]
Build Java code to represent a cast to the given type. This will be an argument of the form "(pkg.Cls1)" or "(pkg.Cls2[])" or "(primtype)" @param builder the builder in which to build the argument @param cls the type for the argument
[ "Build", "Java", "code", "to", "represent", "a", "cast", "to", "the", "given", "type", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/transform/Transform.java#L95-L99
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasLayerUtils.java
KerasLayerUtils.getClassNameFromConfig
public static String getClassNameFromConfig(Map<String, Object> layerConfig, KerasLayerConfiguration conf) throws InvalidKerasConfigurationException { """ Get Keras layer class name from Keras layer configuration. @param layerConfig dictionary containing Keras layer configuration @return Keras layer class name @throws InvalidKerasConfigurationException Invalid Keras config """ if (!layerConfig.containsKey(conf.getLAYER_FIELD_CLASS_NAME())) throw new InvalidKerasConfigurationException( "Field " + conf.getLAYER_FIELD_CLASS_NAME() + " missing from layer config"); return (String) layerConfig.get(conf.getLAYER_FIELD_CLASS_NAME()); }
java
public static String getClassNameFromConfig(Map<String, Object> layerConfig, KerasLayerConfiguration conf) throws InvalidKerasConfigurationException { if (!layerConfig.containsKey(conf.getLAYER_FIELD_CLASS_NAME())) throw new InvalidKerasConfigurationException( "Field " + conf.getLAYER_FIELD_CLASS_NAME() + " missing from layer config"); return (String) layerConfig.get(conf.getLAYER_FIELD_CLASS_NAME()); }
[ "public", "static", "String", "getClassNameFromConfig", "(", "Map", "<", "String", ",", "Object", ">", "layerConfig", ",", "KerasLayerConfiguration", "conf", ")", "throws", "InvalidKerasConfigurationException", "{", "if", "(", "!", "layerConfig", ".", "containsKey", "(", "conf", ".", "getLAYER_FIELD_CLASS_NAME", "(", ")", ")", ")", "throw", "new", "InvalidKerasConfigurationException", "(", "\"Field \"", "+", "conf", ".", "getLAYER_FIELD_CLASS_NAME", "(", ")", "+", "\" missing from layer config\"", ")", ";", "return", "(", "String", ")", "layerConfig", ".", "get", "(", "conf", ".", "getLAYER_FIELD_CLASS_NAME", "(", ")", ")", ";", "}" ]
Get Keras layer class name from Keras layer configuration. @param layerConfig dictionary containing Keras layer configuration @return Keras layer class name @throws InvalidKerasConfigurationException Invalid Keras config
[ "Get", "Keras", "layer", "class", "name", "from", "Keras", "layer", "configuration", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasLayerUtils.java#L338-L344
google/flogger
api/src/main/java/com/google/common/flogger/backend/Platform.java
Platform.shouldForceLogging
public static boolean shouldForceLogging(String loggerName, Level level, boolean isEnabled) { """ Returns whether the given logger should have logging forced at the specified level. When logging is forced for a log statement it will be emitted regardless or the normal log level configuration of the logger and ignoring any rate limiting or other filtering. <p> This method is intended to be invoked unconditionally from a fluent logger's {@code at(Level)} method to permit overriding of default logging behavior. @param loggerName the fully qualified logger name (e.g. "com.example.SomeClass") @param level the level of the log statement being invoked @param isEnabled whether the logger is enabled at the given level (i.e. the result of calling {@code isLoggable()} on the backend instance) """ return LazyHolder.INSTANCE.shouldForceLoggingImpl(loggerName, level, isEnabled); }
java
public static boolean shouldForceLogging(String loggerName, Level level, boolean isEnabled) { return LazyHolder.INSTANCE.shouldForceLoggingImpl(loggerName, level, isEnabled); }
[ "public", "static", "boolean", "shouldForceLogging", "(", "String", "loggerName", ",", "Level", "level", ",", "boolean", "isEnabled", ")", "{", "return", "LazyHolder", ".", "INSTANCE", ".", "shouldForceLoggingImpl", "(", "loggerName", ",", "level", ",", "isEnabled", ")", ";", "}" ]
Returns whether the given logger should have logging forced at the specified level. When logging is forced for a log statement it will be emitted regardless or the normal log level configuration of the logger and ignoring any rate limiting or other filtering. <p> This method is intended to be invoked unconditionally from a fluent logger's {@code at(Level)} method to permit overriding of default logging behavior. @param loggerName the fully qualified logger name (e.g. "com.example.SomeClass") @param level the level of the log statement being invoked @param isEnabled whether the logger is enabled at the given level (i.e. the result of calling {@code isLoggable()} on the backend instance)
[ "Returns", "whether", "the", "given", "logger", "should", "have", "logging", "forced", "at", "the", "specified", "level", ".", "When", "logging", "is", "forced", "for", "a", "log", "statement", "it", "will", "be", "emitted", "regardless", "or", "the", "normal", "log", "level", "configuration", "of", "the", "logger", "and", "ignoring", "any", "rate", "limiting", "or", "other", "filtering", ".", "<p", ">", "This", "method", "is", "intended", "to", "be", "invoked", "unconditionally", "from", "a", "fluent", "logger", "s", "{", "@code", "at", "(", "Level", ")", "}", "method", "to", "permit", "overriding", "of", "default", "logging", "behavior", "." ]
train
https://github.com/google/flogger/blob/a164967a93a9f4ce92f34319fc0cc7c91a57321c/api/src/main/java/com/google/common/flogger/backend/Platform.java#L175-L177
motown-io/motown
domain/core-api/src/main/java/io/motown/domain/api/chargingstation/NumberedTransactionId.java
NumberedTransactionId.numberFromTransactionIdString
private int numberFromTransactionIdString(ChargingStationId chargingStationId, String protocol, String transactionId) { """ Retrieves the number from a transaction id string. ChargingStationId and protocol are passed to make a better guess at the number. @param chargingStationId the charging station's identifier. @param protocol the protocol identifier. @param transactionId the transaction id containing the number. @return the transaction number @throws NumberFormatException if the number cannot be extracted from {@code transactionId}. """ String transactionIdPartBeforeNumber = String.format("%s_%s_", chargingStationId.getId(), protocol); try { return Integer.parseInt(transactionId.substring(transactionIdPartBeforeNumber.length())); } catch (NumberFormatException e) { throw new NumberFormatException(String.format("Cannot retrieve transaction number from string [%s]", transactionId)); } }
java
private int numberFromTransactionIdString(ChargingStationId chargingStationId, String protocol, String transactionId) { String transactionIdPartBeforeNumber = String.format("%s_%s_", chargingStationId.getId(), protocol); try { return Integer.parseInt(transactionId.substring(transactionIdPartBeforeNumber.length())); } catch (NumberFormatException e) { throw new NumberFormatException(String.format("Cannot retrieve transaction number from string [%s]", transactionId)); } }
[ "private", "int", "numberFromTransactionIdString", "(", "ChargingStationId", "chargingStationId", ",", "String", "protocol", ",", "String", "transactionId", ")", "{", "String", "transactionIdPartBeforeNumber", "=", "String", ".", "format", "(", "\"%s_%s_\"", ",", "chargingStationId", ".", "getId", "(", ")", ",", "protocol", ")", ";", "try", "{", "return", "Integer", ".", "parseInt", "(", "transactionId", ".", "substring", "(", "transactionIdPartBeforeNumber", ".", "length", "(", ")", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "NumberFormatException", "(", "String", ".", "format", "(", "\"Cannot retrieve transaction number from string [%s]\"", ",", "transactionId", ")", ")", ";", "}", "}" ]
Retrieves the number from a transaction id string. ChargingStationId and protocol are passed to make a better guess at the number. @param chargingStationId the charging station's identifier. @param protocol the protocol identifier. @param transactionId the transaction id containing the number. @return the transaction number @throws NumberFormatException if the number cannot be extracted from {@code transactionId}.
[ "Retrieves", "the", "number", "from", "a", "transaction", "id", "string", ".", "ChargingStationId", "and", "protocol", "are", "passed", "to", "make", "a", "better", "guess", "at", "the", "number", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/domain/core-api/src/main/java/io/motown/domain/api/chargingstation/NumberedTransactionId.java#L110-L117
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java
MapDotApi.dotGetMap
public static <A, B> Optional<Map<A, B>> dotGetMap(final Map map, final String pathString) { """ Get map value by path. @param <A> map key type @param <B> map value type @param map subject @param pathString nodes to walk in map @return value """ return dotGet(map, Map.class, pathString).map(m -> (Map<A, B>) m); }
java
public static <A, B> Optional<Map<A, B>> dotGetMap(final Map map, final String pathString) { return dotGet(map, Map.class, pathString).map(m -> (Map<A, B>) m); }
[ "public", "static", "<", "A", ",", "B", ">", "Optional", "<", "Map", "<", "A", ",", "B", ">", ">", "dotGetMap", "(", "final", "Map", "map", ",", "final", "String", "pathString", ")", "{", "return", "dotGet", "(", "map", ",", "Map", ".", "class", ",", "pathString", ")", ".", "map", "(", "m", "->", "(", "Map", "<", "A", ",", "B", ">", ")", "m", ")", ";", "}" ]
Get map value by path. @param <A> map key type @param <B> map value type @param map subject @param pathString nodes to walk in map @return value
[ "Get", "map", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java#L168-L170
iipc/openwayback-access-control
access-control/src/main/java/org/archive/accesscontrol/AccessControlClient.java
AccessControlClient.getPolicy
public String getPolicy(String url, Date captureDate, Date retrievalDate, Collection<String> groups) throws RobotsUnavailableException, RuleOracleUnavailableException { """ Return the best-matching policy for the requested document. @param url URL of the requested document. @param captureDate Date the document was archived. @param retrievalDate Date of retrieval (usually now). @param groups Group names of the user accessing the document. @return Access-control policy that should be enforced. eg "robots", "block" or "allow". @throws RobotsUnavailableException @throws RuleOracleUnavailableException """ return getPolicy(url, getRule(url, captureDate, retrievalDate, groups)); }
java
public String getPolicy(String url, Date captureDate, Date retrievalDate, Collection<String> groups) throws RobotsUnavailableException, RuleOracleUnavailableException { return getPolicy(url, getRule(url, captureDate, retrievalDate, groups)); }
[ "public", "String", "getPolicy", "(", "String", "url", ",", "Date", "captureDate", ",", "Date", "retrievalDate", ",", "Collection", "<", "String", ">", "groups", ")", "throws", "RobotsUnavailableException", ",", "RuleOracleUnavailableException", "{", "return", "getPolicy", "(", "url", ",", "getRule", "(", "url", ",", "captureDate", ",", "retrievalDate", ",", "groups", ")", ")", ";", "}" ]
Return the best-matching policy for the requested document. @param url URL of the requested document. @param captureDate Date the document was archived. @param retrievalDate Date of retrieval (usually now). @param groups Group names of the user accessing the document. @return Access-control policy that should be enforced. eg "robots", "block" or "allow". @throws RobotsUnavailableException @throws RuleOracleUnavailableException
[ "Return", "the", "best", "-", "matching", "policy", "for", "the", "requested", "document", "." ]
train
https://github.com/iipc/openwayback-access-control/blob/4a0f70f200fd8d7b6e313624b7628656d834bf31/access-control/src/main/java/org/archive/accesscontrol/AccessControlClient.java#L111-L115
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java
TasksImpl.listSubtasks
public CloudTaskListSubtasksResult listSubtasks(String jobId, String taskId, TaskListSubtasksOptions taskListSubtasksOptions) { """ Lists all of the subtasks that are associated with the specified multi-instance task. If the task is not a multi-instance task then this returns an empty collection. @param jobId The ID of the job. @param taskId The ID of the task. @param taskListSubtasksOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the CloudTaskListSubtasksResult object if successful. """ return listSubtasksWithServiceResponseAsync(jobId, taskId, taskListSubtasksOptions).toBlocking().single().body(); }
java
public CloudTaskListSubtasksResult listSubtasks(String jobId, String taskId, TaskListSubtasksOptions taskListSubtasksOptions) { return listSubtasksWithServiceResponseAsync(jobId, taskId, taskListSubtasksOptions).toBlocking().single().body(); }
[ "public", "CloudTaskListSubtasksResult", "listSubtasks", "(", "String", "jobId", ",", "String", "taskId", ",", "TaskListSubtasksOptions", "taskListSubtasksOptions", ")", "{", "return", "listSubtasksWithServiceResponseAsync", "(", "jobId", ",", "taskId", ",", "taskListSubtasksOptions", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Lists all of the subtasks that are associated with the specified multi-instance task. If the task is not a multi-instance task then this returns an empty collection. @param jobId The ID of the job. @param taskId The ID of the task. @param taskListSubtasksOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the CloudTaskListSubtasksResult object if successful.
[ "Lists", "all", "of", "the", "subtasks", "that", "are", "associated", "with", "the", "specified", "multi", "-", "instance", "task", ".", "If", "the", "task", "is", "not", "a", "multi", "-", "instance", "task", "then", "this", "returns", "an", "empty", "collection", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java#L1719-L1721
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContent.java
CmsXmlContent.copyLocale
public void copyLocale(Locale source, Locale destination, Set<String> elements) throws CmsXmlException { """ Copies the content of the given source locale to the given destination locale in this XML document.<p> @param source the source locale @param destination the destination loacle @param elements the set of elements to copy @throws CmsXmlException if something goes wrong """ if (!hasLocale(source)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } if (hasLocale(destination)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_ALREADY_EXISTS_1, destination)); } Element sourceElement = null; Element rootNode = m_document.getRootElement(); Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(rootNode); String localeStr = source.toString(); while (i.hasNext()) { Element element = i.next(); String language = element.attributeValue(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, null); if ((language != null) && (localeStr.equals(language))) { // detach node with the locale sourceElement = createDeepElementCopy(element, elements); // there can be only one node for the locale break; } } if (sourceElement == null) { // should not happen since this was checked already, just to make sure... throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } // switch locale value in attribute of copied node sourceElement.addAttribute(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, destination.toString()); // attach the copied node to the root node rootNode.add(sourceElement); // re-initialize the document bookmarks initDocument(m_document, m_encoding, getContentDefinition()); }
java
public void copyLocale(Locale source, Locale destination, Set<String> elements) throws CmsXmlException { if (!hasLocale(source)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } if (hasLocale(destination)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_ALREADY_EXISTS_1, destination)); } Element sourceElement = null; Element rootNode = m_document.getRootElement(); Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(rootNode); String localeStr = source.toString(); while (i.hasNext()) { Element element = i.next(); String language = element.attributeValue(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, null); if ((language != null) && (localeStr.equals(language))) { // detach node with the locale sourceElement = createDeepElementCopy(element, elements); // there can be only one node for the locale break; } } if (sourceElement == null) { // should not happen since this was checked already, just to make sure... throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } // switch locale value in attribute of copied node sourceElement.addAttribute(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, destination.toString()); // attach the copied node to the root node rootNode.add(sourceElement); // re-initialize the document bookmarks initDocument(m_document, m_encoding, getContentDefinition()); }
[ "public", "void", "copyLocale", "(", "Locale", "source", ",", "Locale", "destination", ",", "Set", "<", "String", ">", "elements", ")", "throws", "CmsXmlException", "{", "if", "(", "!", "hasLocale", "(", "source", ")", ")", "{", "throw", "new", "CmsXmlException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "xml", ".", "Messages", ".", "ERR_LOCALE_NOT_AVAILABLE_1", ",", "source", ")", ")", ";", "}", "if", "(", "hasLocale", "(", "destination", ")", ")", "{", "throw", "new", "CmsXmlException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "xml", ".", "Messages", ".", "ERR_LOCALE_ALREADY_EXISTS_1", ",", "destination", ")", ")", ";", "}", "Element", "sourceElement", "=", "null", ";", "Element", "rootNode", "=", "m_document", ".", "getRootElement", "(", ")", ";", "Iterator", "<", "Element", ">", "i", "=", "CmsXmlGenericWrapper", ".", "elementIterator", "(", "rootNode", ")", ";", "String", "localeStr", "=", "source", ".", "toString", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "Element", "element", "=", "i", ".", "next", "(", ")", ";", "String", "language", "=", "element", ".", "attributeValue", "(", "CmsXmlContentDefinition", ".", "XSD_ATTRIBUTE_VALUE_LANGUAGE", ",", "null", ")", ";", "if", "(", "(", "language", "!=", "null", ")", "&&", "(", "localeStr", ".", "equals", "(", "language", ")", ")", ")", "{", "// detach node with the locale", "sourceElement", "=", "createDeepElementCopy", "(", "element", ",", "elements", ")", ";", "// there can be only one node for the locale", "break", ";", "}", "}", "if", "(", "sourceElement", "==", "null", ")", "{", "// should not happen since this was checked already, just to make sure...", "throw", "new", "CmsXmlException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "xml", ".", "Messages", ".", "ERR_LOCALE_NOT_AVAILABLE_1", ",", "source", ")", ")", ";", "}", "// switch locale value in attribute of copied node", "sourceElement", ".", "addAttribute", "(", "CmsXmlContentDefinition", ".", "XSD_ATTRIBUTE_VALUE_LANGUAGE", ",", "destination", ".", "toString", "(", ")", ")", ";", "// attach the copied node to the root node", "rootNode", ".", "add", "(", "sourceElement", ")", ";", "// re-initialize the document bookmarks", "initDocument", "(", "m_document", ",", "m_encoding", ",", "getContentDefinition", "(", ")", ")", ";", "}" ]
Copies the content of the given source locale to the given destination locale in this XML document.<p> @param source the source locale @param destination the destination loacle @param elements the set of elements to copy @throws CmsXmlException if something goes wrong
[ "Copies", "the", "content", "of", "the", "given", "source", "locale", "to", "the", "given", "destination", "locale", "in", "this", "XML", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContent.java#L400-L439
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
HtmlTree.HTML
public static HtmlTree HTML(String lang, Content head, Content body) { """ Generates an HTML tag with lang attribute. It also adds head and body content to the HTML tree. @param lang language for the HTML document @param head head for the HTML tag @param body body for the HTML tag @return an HtmlTree object for the HTML tag """ HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body)); htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang)); return htmltree; }
java
public static HtmlTree HTML(String lang, Content head, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body)); htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang)); return htmltree; }
[ "public", "static", "HtmlTree", "HTML", "(", "String", "lang", ",", "Content", "head", ",", "Content", "body", ")", "{", "HtmlTree", "htmltree", "=", "new", "HtmlTree", "(", "HtmlTag", ".", "HTML", ",", "nullCheck", "(", "head", ")", ",", "nullCheck", "(", "body", ")", ")", ";", "htmltree", ".", "addAttr", "(", "HtmlAttr", ".", "LANG", ",", "nullCheck", "(", "lang", ")", ")", ";", "return", "htmltree", ";", "}" ]
Generates an HTML tag with lang attribute. It also adds head and body content to the HTML tree. @param lang language for the HTML document @param head head for the HTML tag @param body body for the HTML tag @return an HtmlTree object for the HTML tag
[ "Generates", "an", "HTML", "tag", "with", "lang", "attribute", ".", "It", "also", "adds", "head", "and", "body", "content", "to", "the", "HTML", "tree", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L450-L454
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbservice_dnsview_binding.java
gslbservice_dnsview_binding.count_filtered
public static long count_filtered(nitro_service service, String servicename, filtervalue[] filter) throws Exception { """ Use this API to count the filtered set of gslbservice_dnsview_binding resources. set the filter parameter values in filtervalue object. """ gslbservice_dnsview_binding obj = new gslbservice_dnsview_binding(); obj.set_servicename(servicename); options option = new options(); option.set_count(true); option.set_filter(filter); gslbservice_dnsview_binding[] response = (gslbservice_dnsview_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
java
public static long count_filtered(nitro_service service, String servicename, filtervalue[] filter) throws Exception{ gslbservice_dnsview_binding obj = new gslbservice_dnsview_binding(); obj.set_servicename(servicename); options option = new options(); option.set_count(true); option.set_filter(filter); gslbservice_dnsview_binding[] response = (gslbservice_dnsview_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
[ "public", "static", "long", "count_filtered", "(", "nitro_service", "service", ",", "String", "servicename", ",", "filtervalue", "[", "]", "filter", ")", "throws", "Exception", "{", "gslbservice_dnsview_binding", "obj", "=", "new", "gslbservice_dnsview_binding", "(", ")", ";", "obj", ".", "set_servicename", "(", "servicename", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_count", "(", "true", ")", ";", "option", ".", "set_filter", "(", "filter", ")", ";", "gslbservice_dnsview_binding", "[", "]", "response", "=", "(", "gslbservice_dnsview_binding", "[", "]", ")", "obj", ".", "getfiltered", "(", "service", ",", "option", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "return", "response", "[", "0", "]", ".", "__count", ";", "}", "return", "0", ";", "}" ]
Use this API to count the filtered set of gslbservice_dnsview_binding resources. set the filter parameter values in filtervalue object.
[ "Use", "this", "API", "to", "count", "the", "filtered", "set", "of", "gslbservice_dnsview_binding", "resources", ".", "set", "the", "filter", "parameter", "values", "in", "filtervalue", "object", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbservice_dnsview_binding.java#L244-L255
UrielCh/ovh-java-sdk
ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/ApiOvhCdnwebsite.java
ApiOvhCdnwebsite.serviceName_zone_domains_POST
public OvhDomain serviceName_zone_domains_POST(String serviceName, String domain) throws IOException { """ Configure a domain on CDN REST: POST /cdn/website/{serviceName}/zone/domains @param domain [required] domain to add on CDN @param serviceName [required] The internal name of your CDN Website offer """ String qPath = "/cdn/website/{serviceName}/zone/domains"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "domain", domain); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhDomain.class); }
java
public OvhDomain serviceName_zone_domains_POST(String serviceName, String domain) throws IOException { String qPath = "/cdn/website/{serviceName}/zone/domains"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "domain", domain); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhDomain.class); }
[ "public", "OvhDomain", "serviceName_zone_domains_POST", "(", "String", "serviceName", ",", "String", "domain", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cdn/website/{serviceName}/zone/domains\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"domain\"", ",", "domain", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhDomain", ".", "class", ")", ";", "}" ]
Configure a domain on CDN REST: POST /cdn/website/{serviceName}/zone/domains @param domain [required] domain to add on CDN @param serviceName [required] The internal name of your CDN Website offer
[ "Configure", "a", "domain", "on", "CDN" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/ApiOvhCdnwebsite.java#L325-L332
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/WaveformDetail.java
WaveformDetail.segmentHeight
@SuppressWarnings("WeakerAccess") public int segmentHeight(final int segment, final int scale) { """ Determine the height of the waveform given an index into it. If {@code scale} is larger than 1 we are zoomed out, so we determine an average height of {@code scale} segments starting with the specified one. @param segment the index of the first waveform byte to examine @param scale the number of wave segments being drawn as a single pixel column @return a value from 0 to 31 representing the height of the waveform at that segment, which may be an average of a number of values starting there, determined by the scale """ final ByteBuffer waveBytes = getData(); final int limit = getFrameCount(); int sum = 0; for (int i = segment; (i < segment + scale) && (i < limit); i++) { if (isColor) { sum += (getColorWaveformBits(waveBytes, segment) >> 2) & 0x1f; } else { sum += waveBytes.get(i) & 0x1f; } } return sum / scale; }
java
@SuppressWarnings("WeakerAccess") public int segmentHeight(final int segment, final int scale) { final ByteBuffer waveBytes = getData(); final int limit = getFrameCount(); int sum = 0; for (int i = segment; (i < segment + scale) && (i < limit); i++) { if (isColor) { sum += (getColorWaveformBits(waveBytes, segment) >> 2) & 0x1f; } else { sum += waveBytes.get(i) & 0x1f; } } return sum / scale; }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "int", "segmentHeight", "(", "final", "int", "segment", ",", "final", "int", "scale", ")", "{", "final", "ByteBuffer", "waveBytes", "=", "getData", "(", ")", ";", "final", "int", "limit", "=", "getFrameCount", "(", ")", ";", "int", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "segment", ";", "(", "i", "<", "segment", "+", "scale", ")", "&&", "(", "i", "<", "limit", ")", ";", "i", "++", ")", "{", "if", "(", "isColor", ")", "{", "sum", "+=", "(", "getColorWaveformBits", "(", "waveBytes", ",", "segment", ")", ">>", "2", ")", "&", "0x1f", ";", "}", "else", "{", "sum", "+=", "waveBytes", ".", "get", "(", "i", ")", "&", "0x1f", ";", "}", "}", "return", "sum", "/", "scale", ";", "}" ]
Determine the height of the waveform given an index into it. If {@code scale} is larger than 1 we are zoomed out, so we determine an average height of {@code scale} segments starting with the specified one. @param segment the index of the first waveform byte to examine @param scale the number of wave segments being drawn as a single pixel column @return a value from 0 to 31 representing the height of the waveform at that segment, which may be an average of a number of values starting there, determined by the scale
[ "Determine", "the", "height", "of", "the", "waveform", "given", "an", "index", "into", "it", ".", "If", "{", "@code", "scale", "}", "is", "larger", "than", "1", "we", "are", "zoomed", "out", "so", "we", "determine", "an", "average", "height", "of", "{", "@code", "scale", "}", "segments", "starting", "with", "the", "specified", "one", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/WaveformDetail.java#L225-L238
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
ScopeImpl.installUnBoundProvider
private <T> InternalProviderImpl<? extends T> installUnBoundProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider) { """ Install the provider of the class {@code clazz} and name {@code bindingName} in the pool of unbound providers. @param clazz the class for which to install the provider. @param bindingName the name, possibly {@code null}, for which to install the scoped provider. @param internalProvider the internal provider to install. @param <T> the type of {@code clazz}. """ return installInternalProvider(clazz, bindingName, internalProvider, false, false); }
java
private <T> InternalProviderImpl<? extends T> installUnBoundProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider) { return installInternalProvider(clazz, bindingName, internalProvider, false, false); }
[ "private", "<", "T", ">", "InternalProviderImpl", "<", "?", "extends", "T", ">", "installUnBoundProvider", "(", "Class", "<", "T", ">", "clazz", ",", "String", "bindingName", ",", "InternalProviderImpl", "<", "?", "extends", "T", ">", "internalProvider", ")", "{", "return", "installInternalProvider", "(", "clazz", ",", "bindingName", ",", "internalProvider", ",", "false", ",", "false", ")", ";", "}" ]
Install the provider of the class {@code clazz} and name {@code bindingName} in the pool of unbound providers. @param clazz the class for which to install the provider. @param bindingName the name, possibly {@code null}, for which to install the scoped provider. @param internalProvider the internal provider to install. @param <T> the type of {@code clazz}.
[ "Install", "the", "provider", "of", "the", "class", "{", "@code", "clazz", "}", "and", "name", "{", "@code", "bindingName", "}", "in", "the", "pool", "of", "unbound", "providers", "." ]
train
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/ScopeImpl.java#L459-L462
kaazing/gateway
util/src/main/java/org/kaazing/gateway/util/Utils.java
Utils.putByteBuffer
public static void putByteBuffer(ByteBuffer source, ByteBuffer target) { """ Writes the contents of source to target without mutating source (so safe for multithreaded access to source) and without GC (unless source is a direct buffer). """ if (source.hasArray()) { byte[] array = source.array(); int arrayOffset = source.arrayOffset(); target.put(array, arrayOffset + source.position(), source.remaining()); } else { target.put(source.duplicate()); } }
java
public static void putByteBuffer(ByteBuffer source, ByteBuffer target) { if (source.hasArray()) { byte[] array = source.array(); int arrayOffset = source.arrayOffset(); target.put(array, arrayOffset + source.position(), source.remaining()); } else { target.put(source.duplicate()); } }
[ "public", "static", "void", "putByteBuffer", "(", "ByteBuffer", "source", ",", "ByteBuffer", "target", ")", "{", "if", "(", "source", ".", "hasArray", "(", ")", ")", "{", "byte", "[", "]", "array", "=", "source", ".", "array", "(", ")", ";", "int", "arrayOffset", "=", "source", ".", "arrayOffset", "(", ")", ";", "target", ".", "put", "(", "array", ",", "arrayOffset", "+", "source", ".", "position", "(", ")", ",", "source", ".", "remaining", "(", ")", ")", ";", "}", "else", "{", "target", ".", "put", "(", "source", ".", "duplicate", "(", ")", ")", ";", "}", "}" ]
Writes the contents of source to target without mutating source (so safe for multithreaded access to source) and without GC (unless source is a direct buffer).
[ "Writes", "the", "contents", "of", "source", "to", "target", "without", "mutating", "source", "(", "so", "safe", "for", "multithreaded", "access", "to", "source", ")", "and", "without", "GC", "(", "unless", "source", "is", "a", "direct", "buffer", ")", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/Utils.java#L465-L474
cdk/cdk
storage/pdb/src/main/java/org/openscience/cdk/tools/ProteinBuilderTool.java
ProteinBuilderTool.addAminoAcidAtNTerminus
public static IBioPolymer addAminoAcidAtNTerminus(IBioPolymer protein, IAminoAcid aaToAdd, IStrand strand, IAminoAcid aaToAddTo) { """ Builds a protein by connecting a new amino acid at the N-terminus of the given strand. @param protein protein to which the strand belongs @param aaToAdd amino acid to add to the strand of the protein @param strand strand to which the protein is added """ // then add the amino acid addAminoAcid(protein, aaToAdd, strand); // Now think about the protein back bone connection if (protein.getMonomerCount() == 0) { // make the connection between that aminoAcid's C-terminus and the // protein's N-terminus protein.addBond(aaToAdd.getBuilder().newInstance(IBond.class, aaToAddTo.getNTerminus(), aaToAdd.getCTerminus(), IBond.Order.SINGLE)); } // else : no current N-terminus, so nothing special to do return protein; }
java
public static IBioPolymer addAminoAcidAtNTerminus(IBioPolymer protein, IAminoAcid aaToAdd, IStrand strand, IAminoAcid aaToAddTo) { // then add the amino acid addAminoAcid(protein, aaToAdd, strand); // Now think about the protein back bone connection if (protein.getMonomerCount() == 0) { // make the connection between that aminoAcid's C-terminus and the // protein's N-terminus protein.addBond(aaToAdd.getBuilder().newInstance(IBond.class, aaToAddTo.getNTerminus(), aaToAdd.getCTerminus(), IBond.Order.SINGLE)); } // else : no current N-terminus, so nothing special to do return protein; }
[ "public", "static", "IBioPolymer", "addAminoAcidAtNTerminus", "(", "IBioPolymer", "protein", ",", "IAminoAcid", "aaToAdd", ",", "IStrand", "strand", ",", "IAminoAcid", "aaToAddTo", ")", "{", "// then add the amino acid", "addAminoAcid", "(", "protein", ",", "aaToAdd", ",", "strand", ")", ";", "// Now think about the protein back bone connection", "if", "(", "protein", ".", "getMonomerCount", "(", ")", "==", "0", ")", "{", "// make the connection between that aminoAcid's C-terminus and the", "// protein's N-terminus", "protein", ".", "addBond", "(", "aaToAdd", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IBond", ".", "class", ",", "aaToAddTo", ".", "getNTerminus", "(", ")", ",", "aaToAdd", ".", "getCTerminus", "(", ")", ",", "IBond", ".", "Order", ".", "SINGLE", ")", ")", ";", "}", "// else : no current N-terminus, so nothing special to do", "return", "protein", ";", "}" ]
Builds a protein by connecting a new amino acid at the N-terminus of the given strand. @param protein protein to which the strand belongs @param aaToAdd amino acid to add to the strand of the protein @param strand strand to which the protein is added
[ "Builds", "a", "protein", "by", "connecting", "a", "new", "amino", "acid", "at", "the", "N", "-", "terminus", "of", "the", "given", "strand", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/pdb/src/main/java/org/openscience/cdk/tools/ProteinBuilderTool.java#L60-L72
inaiat/jqplot4java
src/main/java/br/com/digilabs/jqplot/chart/BubbleChart.java
BubbleChart.addValue
public void addValue(Integer x, Integer y, Integer radius, String label) { """ Add a value @param x x @param y y @param radius radius @param label label """ bubbleData.addValue(new BubbleItem(x, y, radius, label)); }
java
public void addValue(Integer x, Integer y, Integer radius, String label) { bubbleData.addValue(new BubbleItem(x, y, radius, label)); }
[ "public", "void", "addValue", "(", "Integer", "x", ",", "Integer", "y", ",", "Integer", "radius", ",", "String", "label", ")", "{", "bubbleData", ".", "addValue", "(", "new", "BubbleItem", "(", "x", ",", "y", ",", "radius", ",", "label", ")", ")", ";", "}" ]
Add a value @param x x @param y y @param radius radius @param label label
[ "Add", "a", "value" ]
train
https://github.com/inaiat/jqplot4java/blob/35bcd17749442e88695df0438c8330a65a3977cc/src/main/java/br/com/digilabs/jqplot/chart/BubbleChart.java#L95-L97
xvik/dropwizard-guicey
src/main/java/ru/vyarus/dropwizard/guice/module/installer/feature/jersey/AbstractJerseyInstaller.java
AbstractJerseyInstaller.isLazy
protected boolean isLazy(final Class<?> type, final boolean lazy) { """ Checks if lazy flag could be counted (only when extension is managed by guice). Prints warning in case of incorrect lazy marker usage. @param type extension type @param lazy lazy marker (annotation presence) @return lazy marker if guice managed type and false when hk managed. """ if (isHkExtension(type) && lazy) { logger.warn("@LazyBinding is ignored, because @HK2Managed set: {}", type.getName()); return false; } return lazy; }
java
protected boolean isLazy(final Class<?> type, final boolean lazy) { if (isHkExtension(type) && lazy) { logger.warn("@LazyBinding is ignored, because @HK2Managed set: {}", type.getName()); return false; } return lazy; }
[ "protected", "boolean", "isLazy", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "boolean", "lazy", ")", "{", "if", "(", "isHkExtension", "(", "type", ")", "&&", "lazy", ")", "{", "logger", ".", "warn", "(", "\"@LazyBinding is ignored, because @HK2Managed set: {}\"", ",", "type", ".", "getName", "(", ")", ")", ";", "return", "false", ";", "}", "return", "lazy", ";", "}" ]
Checks if lazy flag could be counted (only when extension is managed by guice). Prints warning in case of incorrect lazy marker usage. @param type extension type @param lazy lazy marker (annotation presence) @return lazy marker if guice managed type and false when hk managed.
[ "Checks", "if", "lazy", "flag", "could", "be", "counted", "(", "only", "when", "extension", "is", "managed", "by", "guice", ")", ".", "Prints", "warning", "in", "case", "of", "incorrect", "lazy", "marker", "usage", "." ]
train
https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/installer/feature/jersey/AbstractJerseyInstaller.java#L41-L47
likethecolor/Alchemy-API
src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java
AbstractParser.getDouble
protected Double getDouble(final String key, final JSONObject jsonObject) { """ Check to make sure the JSONObject has the specified key and if so return the value as a double. If no key is found null is returned. @param key name of the field to fetch from the json object @param jsonObject object from which to fetch the value @return double value corresponding to the key or null if key not found """ Double value = null; if(hasKey(key, jsonObject)) { try { value = jsonObject.getDouble(key); } catch(JSONException e) { LOGGER.error("Could not get Double from JSONObject for key: " + key, e); } } return value; }
java
protected Double getDouble(final String key, final JSONObject jsonObject) { Double value = null; if(hasKey(key, jsonObject)) { try { value = jsonObject.getDouble(key); } catch(JSONException e) { LOGGER.error("Could not get Double from JSONObject for key: " + key, e); } } return value; }
[ "protected", "Double", "getDouble", "(", "final", "String", "key", ",", "final", "JSONObject", "jsonObject", ")", "{", "Double", "value", "=", "null", ";", "if", "(", "hasKey", "(", "key", ",", "jsonObject", ")", ")", "{", "try", "{", "value", "=", "jsonObject", ".", "getDouble", "(", "key", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Could not get Double from JSONObject for key: \"", "+", "key", ",", "e", ")", ";", "}", "}", "return", "value", ";", "}" ]
Check to make sure the JSONObject has the specified key and if so return the value as a double. If no key is found null is returned. @param key name of the field to fetch from the json object @param jsonObject object from which to fetch the value @return double value corresponding to the key or null if key not found
[ "Check", "to", "make", "sure", "the", "JSONObject", "has", "the", "specified", "key", "and", "if", "so", "return", "the", "value", "as", "a", "double", ".", "If", "no", "key", "is", "found", "null", "is", "returned", "." ]
train
https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java#L142-L153
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/util/SegmentIntersection.java
SegmentIntersection.divisionByZeroSideEffect
private static boolean divisionByZeroSideEffect( final double pXA, final double pYA, final double pXB, final double pYB, final double pXC, final double pYC, final double pXD, final double pYD, final PointL pIntersection ) { """ Main intersection formula works only without division by zero """ return divisionByZeroSideEffectX(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection) || divisionByZeroSideEffectX(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection) || divisionByZeroSideEffectY(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection) || divisionByZeroSideEffectY(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection); }
java
private static boolean divisionByZeroSideEffect( final double pXA, final double pYA, final double pXB, final double pYB, final double pXC, final double pYC, final double pXD, final double pYD, final PointL pIntersection ) { return divisionByZeroSideEffectX(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection) || divisionByZeroSideEffectX(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection) || divisionByZeroSideEffectY(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection) || divisionByZeroSideEffectY(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection); }
[ "private", "static", "boolean", "divisionByZeroSideEffect", "(", "final", "double", "pXA", ",", "final", "double", "pYA", ",", "final", "double", "pXB", ",", "final", "double", "pYB", ",", "final", "double", "pXC", ",", "final", "double", "pYC", ",", "final", "double", "pXD", ",", "final", "double", "pYD", ",", "final", "PointL", "pIntersection", ")", "{", "return", "divisionByZeroSideEffectX", "(", "pXA", ",", "pYA", ",", "pXB", ",", "pYB", ",", "pXC", ",", "pYC", ",", "pXD", ",", "pYD", ",", "pIntersection", ")", "||", "divisionByZeroSideEffectX", "(", "pXC", ",", "pYC", ",", "pXD", ",", "pYD", ",", "pXA", ",", "pYA", ",", "pXB", ",", "pYB", ",", "pIntersection", ")", "||", "divisionByZeroSideEffectY", "(", "pXA", ",", "pYA", ",", "pXB", ",", "pYB", ",", "pXC", ",", "pYC", ",", "pXD", ",", "pYD", ",", "pIntersection", ")", "||", "divisionByZeroSideEffectY", "(", "pXC", ",", "pYC", ",", "pXD", ",", "pYD", ",", "pXA", ",", "pYA", ",", "pXB", ",", "pYB", ",", "pIntersection", ")", ";", "}" ]
Main intersection formula works only without division by zero
[ "Main", "intersection", "formula", "works", "only", "without", "division", "by", "zero" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/SegmentIntersection.java#L134-L143
dita-ot/dita-ot
src/main/java/org/dita/dost/util/XMLUtils.java
XMLUtils.addOrSetAttribute
public static void addOrSetAttribute(final AttributesImpl atts, final Node att) { """ Add or set attribute. Convenience method for {@link #addOrSetAttribute(AttributesImpl, String, String, String, String, String)}. @param atts attributes @param att attribute node """ if (att.getNodeType() != Node.ATTRIBUTE_NODE) { throw new IllegalArgumentException(); } final Attr a = (Attr) att; String localName = a.getLocalName(); if (localName == null) { localName = a.getName(); final int i = localName.indexOf(':'); if (i != -1) { localName = localName.substring(i + 1); } } addOrSetAttribute(atts, a.getNamespaceURI() != null ? a.getNamespaceURI() : NULL_NS_URI, localName, a.getName() != null ? a.getName() : localName, a.isId() ? "ID" : "CDATA", a.getValue()); }
java
public static void addOrSetAttribute(final AttributesImpl atts, final Node att) { if (att.getNodeType() != Node.ATTRIBUTE_NODE) { throw new IllegalArgumentException(); } final Attr a = (Attr) att; String localName = a.getLocalName(); if (localName == null) { localName = a.getName(); final int i = localName.indexOf(':'); if (i != -1) { localName = localName.substring(i + 1); } } addOrSetAttribute(atts, a.getNamespaceURI() != null ? a.getNamespaceURI() : NULL_NS_URI, localName, a.getName() != null ? a.getName() : localName, a.isId() ? "ID" : "CDATA", a.getValue()); }
[ "public", "static", "void", "addOrSetAttribute", "(", "final", "AttributesImpl", "atts", ",", "final", "Node", "att", ")", "{", "if", "(", "att", ".", "getNodeType", "(", ")", "!=", "Node", ".", "ATTRIBUTE_NODE", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "final", "Attr", "a", "=", "(", "Attr", ")", "att", ";", "String", "localName", "=", "a", ".", "getLocalName", "(", ")", ";", "if", "(", "localName", "==", "null", ")", "{", "localName", "=", "a", ".", "getName", "(", ")", ";", "final", "int", "i", "=", "localName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "i", "!=", "-", "1", ")", "{", "localName", "=", "localName", ".", "substring", "(", "i", "+", "1", ")", ";", "}", "}", "addOrSetAttribute", "(", "atts", ",", "a", ".", "getNamespaceURI", "(", ")", "!=", "null", "?", "a", ".", "getNamespaceURI", "(", ")", ":", "NULL_NS_URI", ",", "localName", ",", "a", ".", "getName", "(", ")", "!=", "null", "?", "a", ".", "getName", "(", ")", ":", "localName", ",", "a", ".", "isId", "(", ")", "?", "\"ID\"", ":", "\"CDATA\"", ",", "a", ".", "getValue", "(", ")", ")", ";", "}" ]
Add or set attribute. Convenience method for {@link #addOrSetAttribute(AttributesImpl, String, String, String, String, String)}. @param atts attributes @param att attribute node
[ "Add", "or", "set", "attribute", ".", "Convenience", "method", "for", "{", "@link", "#addOrSetAttribute", "(", "AttributesImpl", "String", "String", "String", "String", "String", ")", "}", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLUtils.java#L390-L409
structurizr/java
structurizr-core/src/com/structurizr/view/ViewSet.java
ViewSet.createComponentView
public ComponentView createComponentView(Container container, String key, String description) { """ Creates a component view, where the scope of the view is the specified container. @param container the Container object representing the scope of the view @param key the key for the view (must be unique) @param description a description of the view @return a ContainerView object @throws IllegalArgumentException if the container is null or the key is not unique """ assertThatTheContainerIsNotNull(container); assertThatTheViewKeyIsSpecifiedAndUnique(key); ComponentView view = new ComponentView(container, key, description); view.setViewSet(this); componentViews.add(view); return view; }
java
public ComponentView createComponentView(Container container, String key, String description) { assertThatTheContainerIsNotNull(container); assertThatTheViewKeyIsSpecifiedAndUnique(key); ComponentView view = new ComponentView(container, key, description); view.setViewSet(this); componentViews.add(view); return view; }
[ "public", "ComponentView", "createComponentView", "(", "Container", "container", ",", "String", "key", ",", "String", "description", ")", "{", "assertThatTheContainerIsNotNull", "(", "container", ")", ";", "assertThatTheViewKeyIsSpecifiedAndUnique", "(", "key", ")", ";", "ComponentView", "view", "=", "new", "ComponentView", "(", "container", ",", "key", ",", "description", ")", ";", "view", ".", "setViewSet", "(", "this", ")", ";", "componentViews", ".", "add", "(", "view", ")", ";", "return", "view", ";", "}" ]
Creates a component view, where the scope of the view is the specified container. @param container the Container object representing the scope of the view @param key the key for the view (must be unique) @param description a description of the view @return a ContainerView object @throws IllegalArgumentException if the container is null or the key is not unique
[ "Creates", "a", "component", "view", "where", "the", "scope", "of", "the", "view", "is", "the", "specified", "container", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/view/ViewSet.java#L109-L117
codeprimate-software/cp-elements
src/main/java/org/cp/elements/context/configure/AbstractConfiguration.java
AbstractConfiguration.getPropertyValueAs
public <T> T getPropertyValueAs(final String propertyName, final Class<T> type) { """ Gets the value of the configuration property identified by name as a value of the specified Class type. The property is required to be declared and defined otherwise a ConfigurationException is thrown. @param propertyName a String value indicating the name of the configuration property. @param type the expected Class type of the configuration property value. @return the value of the configuration property identified by name. @throws ConfigurationException if the property value was undeclared or is undefined. """ return convert(getPropertyValue(propertyName, DEFAULT_REQUIRED), type); }
java
public <T> T getPropertyValueAs(final String propertyName, final Class<T> type) { return convert(getPropertyValue(propertyName, DEFAULT_REQUIRED), type); }
[ "public", "<", "T", ">", "T", "getPropertyValueAs", "(", "final", "String", "propertyName", ",", "final", "Class", "<", "T", ">", "type", ")", "{", "return", "convert", "(", "getPropertyValue", "(", "propertyName", ",", "DEFAULT_REQUIRED", ")", ",", "type", ")", ";", "}" ]
Gets the value of the configuration property identified by name as a value of the specified Class type. The property is required to be declared and defined otherwise a ConfigurationException is thrown. @param propertyName a String value indicating the name of the configuration property. @param type the expected Class type of the configuration property value. @return the value of the configuration property identified by name. @throws ConfigurationException if the property value was undeclared or is undefined.
[ "Gets", "the", "value", "of", "the", "configuration", "property", "identified", "by", "name", "as", "a", "value", "of", "the", "specified", "Class", "type", ".", "The", "property", "is", "required", "to", "be", "declared", "and", "defined", "otherwise", "a", "ConfigurationException", "is", "thrown", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/context/configure/AbstractConfiguration.java#L231-L233
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/string/Finder.java
Finder.find
public MultiPos<String, String, String> find() { """ Returns a NegateMultiPos instance with all lookup results @return """ return new MultiPos<String, String, String>(null, null) { @Override protected String result() { return findingReplacing(EMPTY, 'L', pos, position); } }; }
java
public MultiPos<String, String, String> find() { return new MultiPos<String, String, String>(null, null) { @Override protected String result() { return findingReplacing(EMPTY, 'L', pos, position); } }; }
[ "public", "MultiPos", "<", "String", ",", "String", ",", "String", ">", "find", "(", ")", "{", "return", "new", "MultiPos", "<", "String", ",", "String", ",", "String", ">", "(", "null", ",", "null", ")", "{", "@", "Override", "protected", "String", "result", "(", ")", "{", "return", "findingReplacing", "(", "EMPTY", ",", "'", "'", ",", "pos", ",", "position", ")", ";", "}", "}", ";", "}" ]
Returns a NegateMultiPos instance with all lookup results @return
[ "Returns", "a", "NegateMultiPos", "instance", "with", "all", "lookup", "results" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Finder.java#L90-L97
apache/groovy
src/main/groovy/groovy/lang/Script.java
Script.printf
public void printf(String format, Object value) { """ Prints a formatted string using the specified format string and argument. @param format the format to follow @param value the value to be formatted """ Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.printf(System.out, format, value); return; } InvokerHelper.invokeMethod(object, "printf", new Object[] { format, value }); }
java
public void printf(String format, Object value) { Object object; try { object = getProperty("out"); } catch (MissingPropertyException e) { DefaultGroovyMethods.printf(System.out, format, value); return; } InvokerHelper.invokeMethod(object, "printf", new Object[] { format, value }); }
[ "public", "void", "printf", "(", "String", "format", ",", "Object", "value", ")", "{", "Object", "object", ";", "try", "{", "object", "=", "getProperty", "(", "\"out\"", ")", ";", "}", "catch", "(", "MissingPropertyException", "e", ")", "{", "DefaultGroovyMethods", ".", "printf", "(", "System", ".", "out", ",", "format", ",", "value", ")", ";", "return", ";", "}", "InvokerHelper", ".", "invokeMethod", "(", "object", ",", "\"printf\"", ",", "new", "Object", "[", "]", "{", "format", ",", "value", "}", ")", ";", "}" ]
Prints a formatted string using the specified format string and argument. @param format the format to follow @param value the value to be formatted
[ "Prints", "a", "formatted", "string", "using", "the", "specified", "format", "string", "and", "argument", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/Script.java#L167-L178
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/HornSchunck.java
HornSchunck.process
public void process( T image1 , T image2 , ImageFlow output) { """ Computes dense optical flow from the first image's gradient and the difference between the second and the first image. @param image1 First image @param image2 Second image @param output Found dense optical flow """ InputSanityCheck.checkSameShape(image1,image2); derivX.reshape(image1.width,image1.height); derivY.reshape(image1.width,image1.height); derivT.reshape(image1.width,image1.height); averageFlow.reshape(output.width,output.height); if( resetOutput ) output.fillZero(); computeDerivX(image1,image2,derivX); computeDerivY(image1,image2,derivY); computeDerivT(image1,image2,derivT); findFlow(derivX,derivY,derivT,output); }
java
public void process( T image1 , T image2 , ImageFlow output) { InputSanityCheck.checkSameShape(image1,image2); derivX.reshape(image1.width,image1.height); derivY.reshape(image1.width,image1.height); derivT.reshape(image1.width,image1.height); averageFlow.reshape(output.width,output.height); if( resetOutput ) output.fillZero(); computeDerivX(image1,image2,derivX); computeDerivY(image1,image2,derivY); computeDerivT(image1,image2,derivT); findFlow(derivX,derivY,derivT,output); }
[ "public", "void", "process", "(", "T", "image1", ",", "T", "image2", ",", "ImageFlow", "output", ")", "{", "InputSanityCheck", ".", "checkSameShape", "(", "image1", ",", "image2", ")", ";", "derivX", ".", "reshape", "(", "image1", ".", "width", ",", "image1", ".", "height", ")", ";", "derivY", ".", "reshape", "(", "image1", ".", "width", ",", "image1", ".", "height", ")", ";", "derivT", ".", "reshape", "(", "image1", ".", "width", ",", "image1", ".", "height", ")", ";", "averageFlow", ".", "reshape", "(", "output", ".", "width", ",", "output", ".", "height", ")", ";", "if", "(", "resetOutput", ")", "output", ".", "fillZero", "(", ")", ";", "computeDerivX", "(", "image1", ",", "image2", ",", "derivX", ")", ";", "computeDerivY", "(", "image1", ",", "image2", ",", "derivY", ")", ";", "computeDerivT", "(", "image1", ",", "image2", ",", "derivT", ")", ";", "findFlow", "(", "derivX", ",", "derivY", ",", "derivT", ",", "output", ")", ";", "}" ]
Computes dense optical flow from the first image's gradient and the difference between the second and the first image. @param image1 First image @param image2 Second image @param output Found dense optical flow
[ "Computes", "dense", "optical", "flow", "from", "the", "first", "image", "s", "gradient", "and", "the", "difference", "between", "the", "second", "and", "the", "first", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/HornSchunck.java#L92-L110
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.deleteAnnotationIfNeccessary
public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType) { """ Removes the annotation from javac's AST (it remains in lombok's AST), then removes any import statement that imports this exact annotation (not star imports). Only does this if the DeleteLombokAnnotations class is in the context. """ deleteAnnotationIfNeccessary0(annotation, annotationType.getName()); }
java
public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType) { deleteAnnotationIfNeccessary0(annotation, annotationType.getName()); }
[ "public", "static", "void", "deleteAnnotationIfNeccessary", "(", "JavacNode", "annotation", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType", ")", "{", "deleteAnnotationIfNeccessary0", "(", "annotation", ",", "annotationType", ".", "getName", "(", ")", ")", ";", "}" ]
Removes the annotation from javac's AST (it remains in lombok's AST), then removes any import statement that imports this exact annotation (not star imports). Only does this if the DeleteLombokAnnotations class is in the context.
[ "Removes", "the", "annotation", "from", "javac", "s", "AST", "(", "it", "remains", "in", "lombok", "s", "AST", ")", "then", "removes", "any", "import", "statement", "that", "imports", "this", "exact", "annotation", "(", "not", "star", "imports", ")", ".", "Only", "does", "this", "if", "the", "DeleteLombokAnnotations", "class", "is", "in", "the", "context", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L465-L467
apache/groovy
subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
AstBuilder.visitGstring
@Override public GStringExpression visitGstring(GstringContext ctx) { """ gstring { -------------------------------------------------------------------- """ final List<ConstantExpression> stringLiteralList = new LinkedList<>(); final String begin = ctx.GStringBegin().getText(); final String beginQuotation = beginQuotation(begin); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringBegin(ctx, beginQuotation)), ctx.GStringBegin())); List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> configureAST(new ConstantExpression(parseGStringPart(e, beginQuotation)), e)) .collect(Collectors.toList()); stringLiteralList.addAll(partStrings); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringEnd(ctx, beginQuotation)), ctx.GStringEnd())); List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !hasArrow(e)) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().noneMatch(DefaultGroovyMethods::asBoolean)) { return configureAST(new ConstantExpression(null), e); } return configureAST(this.createCallMethodCallExpression(expression, new ArgumentListExpression(), true), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = stringLiteralList.size(), s = values.size(); i < n; i++) { verbatimText.append(stringLiteralList.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return configureAST(new GStringExpression(verbatimText.toString(), stringLiteralList, values), ctx); }
java
@Override public GStringExpression visitGstring(GstringContext ctx) { final List<ConstantExpression> stringLiteralList = new LinkedList<>(); final String begin = ctx.GStringBegin().getText(); final String beginQuotation = beginQuotation(begin); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringBegin(ctx, beginQuotation)), ctx.GStringBegin())); List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> configureAST(new ConstantExpression(parseGStringPart(e, beginQuotation)), e)) .collect(Collectors.toList()); stringLiteralList.addAll(partStrings); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringEnd(ctx, beginQuotation)), ctx.GStringEnd())); List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !hasArrow(e)) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().noneMatch(DefaultGroovyMethods::asBoolean)) { return configureAST(new ConstantExpression(null), e); } return configureAST(this.createCallMethodCallExpression(expression, new ArgumentListExpression(), true), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = stringLiteralList.size(), s = values.size(); i < n; i++) { verbatimText.append(stringLiteralList.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return configureAST(new GStringExpression(verbatimText.toString(), stringLiteralList, values), ctx); }
[ "@", "Override", "public", "GStringExpression", "visitGstring", "(", "GstringContext", "ctx", ")", "{", "final", "List", "<", "ConstantExpression", ">", "stringLiteralList", "=", "new", "LinkedList", "<>", "(", ")", ";", "final", "String", "begin", "=", "ctx", ".", "GStringBegin", "(", ")", ".", "getText", "(", ")", ";", "final", "String", "beginQuotation", "=", "beginQuotation", "(", "begin", ")", ";", "stringLiteralList", ".", "add", "(", "configureAST", "(", "new", "ConstantExpression", "(", "parseGStringBegin", "(", "ctx", ",", "beginQuotation", ")", ")", ",", "ctx", ".", "GStringBegin", "(", ")", ")", ")", ";", "List", "<", "ConstantExpression", ">", "partStrings", "=", "ctx", ".", "GStringPart", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "e", "->", "configureAST", "(", "new", "ConstantExpression", "(", "parseGStringPart", "(", "e", ",", "beginQuotation", ")", ")", ",", "e", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "stringLiteralList", ".", "addAll", "(", "partStrings", ")", ";", "stringLiteralList", ".", "add", "(", "configureAST", "(", "new", "ConstantExpression", "(", "parseGStringEnd", "(", "ctx", ",", "beginQuotation", ")", ")", ",", "ctx", ".", "GStringEnd", "(", ")", ")", ")", ";", "List", "<", "Expression", ">", "values", "=", "ctx", ".", "gstringValue", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "e", "->", "{", "Expression", "expression", "=", "this", ".", "visitGstringValue", "(", "e", ")", ";", "if", "(", "expression", "instanceof", "ClosureExpression", "&&", "!", "hasArrow", "(", "e", ")", ")", "{", "List", "<", "Statement", ">", "statementList", "=", "(", "(", "BlockStatement", ")", "(", "(", "ClosureExpression", ")", "expression", ")", ".", "getCode", "(", ")", ")", ".", "getStatements", "(", ")", ";", "if", "(", "statementList", ".", "stream", "(", ")", ".", "noneMatch", "(", "DefaultGroovyMethods", "::", "asBoolean", ")", ")", "{", "return", "configureAST", "(", "new", "ConstantExpression", "(", "null", ")", ",", "e", ")", ";", "}", "return", "configureAST", "(", "this", ".", "createCallMethodCallExpression", "(", "expression", ",", "new", "ArgumentListExpression", "(", ")", ",", "true", ")", ",", "e", ")", ";", "}", "return", "expression", ";", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "StringBuilder", "verbatimText", "=", "new", "StringBuilder", "(", "ctx", ".", "getText", "(", ")", ".", "length", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ",", "n", "=", "stringLiteralList", ".", "size", "(", ")", ",", "s", "=", "values", ".", "size", "(", ")", ";", "i", "<", "n", ";", "i", "++", ")", "{", "verbatimText", ".", "append", "(", "stringLiteralList", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "if", "(", "i", "==", "s", ")", "{", "continue", ";", "}", "Expression", "value", "=", "values", ".", "get", "(", "i", ")", ";", "if", "(", "!", "asBoolean", "(", "value", ")", ")", "{", "continue", ";", "}", "verbatimText", ".", "append", "(", "DOLLAR_STR", ")", ";", "verbatimText", ".", "append", "(", "value", ".", "getText", "(", ")", ")", ";", "}", "return", "configureAST", "(", "new", "GStringExpression", "(", "verbatimText", ".", "toString", "(", ")", ",", "stringLiteralList", ",", "values", ")", ",", "ctx", ")", ";", "}" ]
gstring { --------------------------------------------------------------------
[ "gstring", "{", "--------------------------------------------------------------------" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java#L3568-L3619
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.extractIntResult
static public int extractIntResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { """ This method returns an int result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A value returned at the specified index @throws Exception If there is no column at index """ int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: return rs.getInt(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
java
static public int extractIntResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: return rs.getInt(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
[ "static", "public", "int", "extractIntResult", "(", "ResultSet", "rs", ",", "ResultSetMetaData", "rsmd", ",", "int", "index", ")", "throws", "Exception", "{", "int", "count", "=", "rsmd", ".", "getColumnCount", "(", ")", ";", "if", "(", "index", ">", "count", "||", "index", "<", "1", ")", "{", "throw", "new", "Exception", "(", "\"Invalid index\"", ")", ";", "}", "int", "type", "=", "rsmd", ".", "getColumnType", "(", "index", ")", ";", "switch", "(", "type", ")", "{", "case", "java", ".", "sql", ".", "Types", ".", "INTEGER", ":", "case", "java", ".", "sql", ".", "Types", ".", "SMALLINT", ":", "return", "rs", ".", "getInt", "(", "index", ")", ";", "}", "throw", "new", "Exception", "(", "\"Column type (\"", "+", "type", "+", "\") invalid for a string at index: \"", "+", "index", ")", ";", "}" ]
This method returns an int result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A value returned at the specified index @throws Exception If there is no column at index
[ "This", "method", "returns", "an", "int", "result", "at", "a", "given", "index", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L131-L146
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java
CmsPositionBean.isOverElement
public boolean isOverElement(int absLeft, int absTop) { """ Returns if given position is inside the position beans coordinates.<p> @param absLeft the absolute left position @param absTop the absolute top position @return true if the given position if within the beans coordinates """ if ((absTop > m_top) && (absTop < (m_top + m_height)) && (absLeft > m_left) && (absLeft < (m_left + m_width))) { return true; } /* */ return false; }
java
public boolean isOverElement(int absLeft, int absTop) { if ((absTop > m_top) && (absTop < (m_top + m_height)) && (absLeft > m_left) && (absLeft < (m_left + m_width))) { return true; } /* */ return false; }
[ "public", "boolean", "isOverElement", "(", "int", "absLeft", ",", "int", "absTop", ")", "{", "if", "(", "(", "absTop", ">", "m_top", ")", "&&", "(", "absTop", "<", "(", "m_top", "+", "m_height", ")", ")", "&&", "(", "absLeft", ">", "m_left", ")", "&&", "(", "absLeft", "<", "(", "m_left", "+", "m_width", ")", ")", ")", "{", "return", "true", ";", "}", "/* */", "return", "false", ";", "}" ]
Returns if given position is inside the position beans coordinates.<p> @param absLeft the absolute left position @param absTop the absolute top position @return true if the given position if within the beans coordinates
[ "Returns", "if", "given", "position", "is", "inside", "the", "position", "beans", "coordinates", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java#L550-L557
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java
SparkUtils.writeStringToFile
public static void writeStringToFile(String path, String toWrite, SparkContext sc) throws IOException { """ Write a String to a file (on HDFS or local) in UTF-8 format @param path Path to write to @param toWrite String to write @param sc Spark context """ writeStringToFile(path, toWrite, sc.hadoopConfiguration()); }
java
public static void writeStringToFile(String path, String toWrite, SparkContext sc) throws IOException { writeStringToFile(path, toWrite, sc.hadoopConfiguration()); }
[ "public", "static", "void", "writeStringToFile", "(", "String", "path", ",", "String", "toWrite", ",", "SparkContext", "sc", ")", "throws", "IOException", "{", "writeStringToFile", "(", "path", ",", "toWrite", ",", "sc", ".", "hadoopConfiguration", "(", ")", ")", ";", "}" ]
Write a String to a file (on HDFS or local) in UTF-8 format @param path Path to write to @param toWrite String to write @param sc Spark context
[ "Write", "a", "String", "to", "a", "file", "(", "on", "HDFS", "or", "local", ")", "in", "UTF", "-", "8", "format" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java#L85-L87
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readResources
private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap) { """ This method extracts resource data from an MSPDI file. @param project Root node of the MSPDI file @param calendarMap Map of calendar UIDs to names """ Project.Resources resources = project.getResources(); if (resources != null) { for (Project.Resources.Resource resource : resources.getResource()) { readResource(resource, calendarMap); } } }
java
private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap) { Project.Resources resources = project.getResources(); if (resources != null) { for (Project.Resources.Resource resource : resources.getResource()) { readResource(resource, calendarMap); } } }
[ "private", "void", "readResources", "(", "Project", "project", ",", "HashMap", "<", "BigInteger", ",", "ProjectCalendar", ">", "calendarMap", ")", "{", "Project", ".", "Resources", "resources", "=", "project", ".", "getResources", "(", ")", ";", "if", "(", "resources", "!=", "null", ")", "{", "for", "(", "Project", ".", "Resources", ".", "Resource", "resource", ":", "resources", ".", "getResource", "(", ")", ")", "{", "readResource", "(", "resource", ",", "calendarMap", ")", ";", "}", "}", "}" ]
This method extracts resource data from an MSPDI file. @param project Root node of the MSPDI file @param calendarMap Map of calendar UIDs to names
[ "This", "method", "extracts", "resource", "data", "from", "an", "MSPDI", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L861-L871
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisUtils.java
JedisUtils.newJedisPool
public static JedisPool newJedisPool(JedisPoolConfig poolConfig, String hostAndPort) { """ Create a new {@link JedisPool} with specified pool configs. @param poolConfig @param hostAndPort format {@code host:port} or {@code host}, default Redis port is used if not specified @return """ return newJedisPool(poolConfig, hostAndPort, null, Protocol.DEFAULT_DATABASE, Protocol.DEFAULT_TIMEOUT); }
java
public static JedisPool newJedisPool(JedisPoolConfig poolConfig, String hostAndPort) { return newJedisPool(poolConfig, hostAndPort, null, Protocol.DEFAULT_DATABASE, Protocol.DEFAULT_TIMEOUT); }
[ "public", "static", "JedisPool", "newJedisPool", "(", "JedisPoolConfig", "poolConfig", ",", "String", "hostAndPort", ")", "{", "return", "newJedisPool", "(", "poolConfig", ",", "hostAndPort", ",", "null", ",", "Protocol", ".", "DEFAULT_DATABASE", ",", "Protocol", ".", "DEFAULT_TIMEOUT", ")", ";", "}" ]
Create a new {@link JedisPool} with specified pool configs. @param poolConfig @param hostAndPort format {@code host:port} or {@code host}, default Redis port is used if not specified @return
[ "Create", "a", "new", "{", "@link", "JedisPool", "}", "with", "specified", "pool", "configs", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisUtils.java#L73-L76
crawljax/crawljax
core/src/main/java/com/crawljax/util/DomUtils.java
DomUtils.getTextContent
public static String getTextContent(Document document, boolean individualTokens) { """ To get all the textual content in the dom @param document @param individualTokens : default True : when set to true, each text node from dom is used to build the text content : when set to false, the text content of whole is obtained at once. @return """ String textContent = null; if (individualTokens) { List<String> tokens = getTextTokens(document); textContent = StringUtils.join(tokens, ","); } else { textContent = document.getDocumentElement().getTextContent().trim().replaceAll("\\s+", ","); } return textContent; }
java
public static String getTextContent(Document document, boolean individualTokens) { String textContent = null; if (individualTokens) { List<String> tokens = getTextTokens(document); textContent = StringUtils.join(tokens, ","); } else { textContent = document.getDocumentElement().getTextContent().trim().replaceAll("\\s+", ","); } return textContent; }
[ "public", "static", "String", "getTextContent", "(", "Document", "document", ",", "boolean", "individualTokens", ")", "{", "String", "textContent", "=", "null", ";", "if", "(", "individualTokens", ")", "{", "List", "<", "String", ">", "tokens", "=", "getTextTokens", "(", "document", ")", ";", "textContent", "=", "StringUtils", ".", "join", "(", "tokens", ",", "\",\"", ")", ";", "}", "else", "{", "textContent", "=", "document", ".", "getDocumentElement", "(", ")", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ".", "replaceAll", "(", "\"\\\\s+\"", ",", "\",\"", ")", ";", "}", "return", "textContent", ";", "}" ]
To get all the textual content in the dom @param document @param individualTokens : default True : when set to true, each text node from dom is used to build the text content : when set to false, the text content of whole is obtained at once. @return
[ "To", "get", "all", "the", "textual", "content", "in", "the", "dom" ]
train
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L511-L521
wcm-io-caravan/caravan-commons
httpclient/src/main/java/io/wcm/caravan/commons/httpclient/impl/helpers/CertificateLoader.java
CertificateLoader.getKeyManagerFactory
public static KeyManagerFactory getKeyManagerFactory(String keyStoreFilename, StoreProperties storeProperties) throws IOException, GeneralSecurityException { """ Get key manager factory @param keyStoreFilename Keystore file name @param storeProperties store properties @return Key manager factory @throws IOException @throws GeneralSecurityException """ InputStream is = getResourceAsStream(keyStoreFilename); if (is == null) { throw new FileNotFoundException("Certificate file not found: " + getFilenameInfo(keyStoreFilename)); } try { return getKeyManagerFactory(is, storeProperties); } finally { try { is.close(); } catch (IOException ex) { // ignore } } }
java
public static KeyManagerFactory getKeyManagerFactory(String keyStoreFilename, StoreProperties storeProperties) throws IOException, GeneralSecurityException { InputStream is = getResourceAsStream(keyStoreFilename); if (is == null) { throw new FileNotFoundException("Certificate file not found: " + getFilenameInfo(keyStoreFilename)); } try { return getKeyManagerFactory(is, storeProperties); } finally { try { is.close(); } catch (IOException ex) { // ignore } } }
[ "public", "static", "KeyManagerFactory", "getKeyManagerFactory", "(", "String", "keyStoreFilename", ",", "StoreProperties", "storeProperties", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "InputStream", "is", "=", "getResourceAsStream", "(", "keyStoreFilename", ")", ";", "if", "(", "is", "==", "null", ")", "{", "throw", "new", "FileNotFoundException", "(", "\"Certificate file not found: \"", "+", "getFilenameInfo", "(", "keyStoreFilename", ")", ")", ";", "}", "try", "{", "return", "getKeyManagerFactory", "(", "is", ",", "storeProperties", ")", ";", "}", "finally", "{", "try", "{", "is", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "// ignore", "}", "}", "}" ]
Get key manager factory @param keyStoreFilename Keystore file name @param storeProperties store properties @return Key manager factory @throws IOException @throws GeneralSecurityException
[ "Get", "key", "manager", "factory" ]
train
https://github.com/wcm-io-caravan/caravan-commons/blob/12e605bdfeb5a1ce7404e30d9f32274552cb8ce8/httpclient/src/main/java/io/wcm/caravan/commons/httpclient/impl/helpers/CertificateLoader.java#L113-L130
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobLauncherFactory.java
JobLauncherFactory.newJobLauncher
public static JobLauncher newJobLauncher(Properties sysProps, Properties jobProps, String launcherTypeValue, SharedResourcesBroker<GobblinScopeTypes> instanceBroker) { """ Creates a new instance for a JobLauncher with a given type @param sysProps the system/environment properties @param jobProps the job properties @param launcherTypeValue the type of the launcher; either a {@link JobLauncherType} value or the name of the class that extends {@link AbstractJobLauncher} and has a constructor that has a single Properties parameter.. @return the JobLauncher instance @throws RuntimeException if the instantiation fails """ return newJobLauncher(sysProps, jobProps, launcherTypeValue, instanceBroker, ImmutableList.of()); }
java
public static JobLauncher newJobLauncher(Properties sysProps, Properties jobProps, String launcherTypeValue, SharedResourcesBroker<GobblinScopeTypes> instanceBroker) { return newJobLauncher(sysProps, jobProps, launcherTypeValue, instanceBroker, ImmutableList.of()); }
[ "public", "static", "JobLauncher", "newJobLauncher", "(", "Properties", "sysProps", ",", "Properties", "jobProps", ",", "String", "launcherTypeValue", ",", "SharedResourcesBroker", "<", "GobblinScopeTypes", ">", "instanceBroker", ")", "{", "return", "newJobLauncher", "(", "sysProps", ",", "jobProps", ",", "launcherTypeValue", ",", "instanceBroker", ",", "ImmutableList", ".", "of", "(", ")", ")", ";", "}" ]
Creates a new instance for a JobLauncher with a given type @param sysProps the system/environment properties @param jobProps the job properties @param launcherTypeValue the type of the launcher; either a {@link JobLauncherType} value or the name of the class that extends {@link AbstractJobLauncher} and has a constructor that has a single Properties parameter.. @return the JobLauncher instance @throws RuntimeException if the instantiation fails
[ "Creates", "a", "new", "instance", "for", "a", "JobLauncher", "with", "a", "given", "type" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobLauncherFactory.java#L120-L123
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/version_matrix_file.java
version_matrix_file.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> """ version_matrix_file_responses result = (version_matrix_file_responses) service.get_payload_formatter().string_to_resource(version_matrix_file_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.version_matrix_file_response_array); } version_matrix_file[] result_version_matrix_file = new version_matrix_file[result.version_matrix_file_response_array.length]; for(int i = 0; i < result.version_matrix_file_response_array.length; i++) { result_version_matrix_file[i] = result.version_matrix_file_response_array[i].version_matrix_file[0]; } return result_version_matrix_file; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { version_matrix_file_responses result = (version_matrix_file_responses) service.get_payload_formatter().string_to_resource(version_matrix_file_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.version_matrix_file_response_array); } version_matrix_file[] result_version_matrix_file = new version_matrix_file[result.version_matrix_file_response_array.length]; for(int i = 0; i < result.version_matrix_file_response_array.length; i++) { result_version_matrix_file[i] = result.version_matrix_file_response_array[i].version_matrix_file[0]; } return result_version_matrix_file; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "version_matrix_file_responses", "result", "=", "(", "version_matrix_file_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "version_matrix_file_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", ".", "version_matrix_file_response_array", ")", ";", "}", "version_matrix_file", "[", "]", "result_version_matrix_file", "=", "new", "version_matrix_file", "[", "result", ".", "version_matrix_file_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "version_matrix_file_response_array", ".", "length", ";", "i", "++", ")", "{", "result_version_matrix_file", "[", "i", "]", "=", "result", ".", "version_matrix_file_response_array", "[", "i", "]", ".", "version_matrix_file", "[", "0", "]", ";", "}", "return", "result_version_matrix_file", ";", "}" ]
<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/mps/version_matrix_file.java#L277-L294
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java
ServletUtil.write
public static void write(HttpServletResponse response, File file) { """ 返回文件给客户端 @param response 响应对象{@link HttpServletResponse} @param file 写出的文件对象 @since 4.1.15 """ final String fileName = file.getName(); final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream"); BufferedInputStream in = null; try { in = FileUtil.getInputStream(file); write(response, in, contentType, fileName); } finally { IoUtil.close(in); } }
java
public static void write(HttpServletResponse response, File file) { final String fileName = file.getName(); final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream"); BufferedInputStream in = null; try { in = FileUtil.getInputStream(file); write(response, in, contentType, fileName); } finally { IoUtil.close(in); } }
[ "public", "static", "void", "write", "(", "HttpServletResponse", "response", ",", "File", "file", ")", "{", "final", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "final", "String", "contentType", "=", "ObjectUtil", ".", "defaultIfNull", "(", "FileUtil", ".", "getMimeType", "(", "fileName", ")", ",", "\"application/octet-stream\"", ")", ";", "BufferedInputStream", "in", "=", "null", ";", "try", "{", "in", "=", "FileUtil", ".", "getInputStream", "(", "file", ")", ";", "write", "(", "response", ",", "in", ",", "contentType", ",", "fileName", ")", ";", "}", "finally", "{", "IoUtil", ".", "close", "(", "in", ")", ";", "}", "}" ]
返回文件给客户端 @param response 响应对象{@link HttpServletResponse} @param file 写出的文件对象 @since 4.1.15
[ "返回文件给客户端" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L501-L511
OpenTSDB/opentsdb
src/tools/UidManager.java
UidManager.metaPurge
private static int metaPurge(final TSDB tsdb) throws Exception { """ Runs through the tsdb-uid table and removes TSMeta, UIDMeta and TSUID counter entries from the table The process is as follows: <ul><li>Fetch the max number of Metric UIDs</li> <li>Split the # of UIDs amongst worker threads</li> <li>Create a delete request with the qualifiers of any matching meta data columns</li></ul> <li>Continue on to the next unprocessed timeseries data row</li></ul> @param tsdb The tsdb to use for processing, including a search plugin @return 0 if completed successfully, something else if it dies """ final long start_time = System.currentTimeMillis() / 1000; final long max_id = CliUtils.getMaxMetricID(tsdb); // now figure out how many IDs to divy up between the workers final int workers = Runtime.getRuntime().availableProcessors() * 2; final double quotient = (double)max_id / (double)workers; long index = 1; LOG.info("Max metric ID is [" + max_id + "]"); LOG.info("Spooling up [" + workers + "] worker threads"); final Thread[] threads = new Thread[workers]; for (int i = 0; i < workers; i++) { threads[i] = new MetaPurge(tsdb, index, quotient, i); threads[i].setName("MetaSync # " + i); threads[i].start(); index += quotient; if (index < max_id) { index++; } } // wait till we're all done for (int i = 0; i < workers; i++) { threads[i].join(); LOG.info("[" + i + "] Finished"); } // make sure buffered data is flushed to storage before exiting tsdb.flush().joinUninterruptibly(); final long duration = (System.currentTimeMillis() / 1000) - start_time; LOG.info("Completed meta data synchronization in [" + duration + "] seconds"); return 0; }
java
private static int metaPurge(final TSDB tsdb) throws Exception { final long start_time = System.currentTimeMillis() / 1000; final long max_id = CliUtils.getMaxMetricID(tsdb); // now figure out how many IDs to divy up between the workers final int workers = Runtime.getRuntime().availableProcessors() * 2; final double quotient = (double)max_id / (double)workers; long index = 1; LOG.info("Max metric ID is [" + max_id + "]"); LOG.info("Spooling up [" + workers + "] worker threads"); final Thread[] threads = new Thread[workers]; for (int i = 0; i < workers; i++) { threads[i] = new MetaPurge(tsdb, index, quotient, i); threads[i].setName("MetaSync # " + i); threads[i].start(); index += quotient; if (index < max_id) { index++; } } // wait till we're all done for (int i = 0; i < workers; i++) { threads[i].join(); LOG.info("[" + i + "] Finished"); } // make sure buffered data is flushed to storage before exiting tsdb.flush().joinUninterruptibly(); final long duration = (System.currentTimeMillis() / 1000) - start_time; LOG.info("Completed meta data synchronization in [" + duration + "] seconds"); return 0; }
[ "private", "static", "int", "metaPurge", "(", "final", "TSDB", "tsdb", ")", "throws", "Exception", "{", "final", "long", "start_time", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "1000", ";", "final", "long", "max_id", "=", "CliUtils", ".", "getMaxMetricID", "(", "tsdb", ")", ";", "// now figure out how many IDs to divy up between the workers", "final", "int", "workers", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", "*", "2", ";", "final", "double", "quotient", "=", "(", "double", ")", "max_id", "/", "(", "double", ")", "workers", ";", "long", "index", "=", "1", ";", "LOG", ".", "info", "(", "\"Max metric ID is [\"", "+", "max_id", "+", "\"]\"", ")", ";", "LOG", ".", "info", "(", "\"Spooling up [\"", "+", "workers", "+", "\"] worker threads\"", ")", ";", "final", "Thread", "[", "]", "threads", "=", "new", "Thread", "[", "workers", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "workers", ";", "i", "++", ")", "{", "threads", "[", "i", "]", "=", "new", "MetaPurge", "(", "tsdb", ",", "index", ",", "quotient", ",", "i", ")", ";", "threads", "[", "i", "]", ".", "setName", "(", "\"MetaSync # \"", "+", "i", ")", ";", "threads", "[", "i", "]", ".", "start", "(", ")", ";", "index", "+=", "quotient", ";", "if", "(", "index", "<", "max_id", ")", "{", "index", "++", ";", "}", "}", "// wait till we're all done", "for", "(", "int", "i", "=", "0", ";", "i", "<", "workers", ";", "i", "++", ")", "{", "threads", "[", "i", "]", ".", "join", "(", ")", ";", "LOG", ".", "info", "(", "\"[\"", "+", "i", "+", "\"] Finished\"", ")", ";", "}", "// make sure buffered data is flushed to storage before exiting", "tsdb", ".", "flush", "(", ")", ".", "joinUninterruptibly", "(", ")", ";", "final", "long", "duration", "=", "(", "System", ".", "currentTimeMillis", "(", ")", "/", "1000", ")", "-", "start_time", ";", "LOG", ".", "info", "(", "\"Completed meta data synchronization in [\"", "+", "duration", "+", "\"] seconds\"", ")", ";", "return", "0", ";", "}" ]
Runs through the tsdb-uid table and removes TSMeta, UIDMeta and TSUID counter entries from the table The process is as follows: <ul><li>Fetch the max number of Metric UIDs</li> <li>Split the # of UIDs amongst worker threads</li> <li>Create a delete request with the qualifiers of any matching meta data columns</li></ul> <li>Continue on to the next unprocessed timeseries data row</li></ul> @param tsdb The tsdb to use for processing, including a search plugin @return 0 if completed successfully, something else if it dies
[ "Runs", "through", "the", "tsdb", "-", "uid", "table", "and", "removes", "TSMeta", "UIDMeta", "and", "TSUID", "counter", "entries", "from", "the", "table", "The", "process", "is", "as", "follows", ":", "<ul", ">", "<li", ">", "Fetch", "the", "max", "number", "of", "Metric", "UIDs<", "/", "li", ">", "<li", ">", "Split", "the", "#", "of", "UIDs", "amongst", "worker", "threads<", "/", "li", ">", "<li", ">", "Create", "a", "delete", "request", "with", "the", "qualifiers", "of", "any", "matching", "meta", "data", "columns<", "/", "li", ">", "<", "/", "ul", ">", "<li", ">", "Continue", "on", "to", "the", "next", "unprocessed", "timeseries", "data", "row<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/UidManager.java#L1055-L1091
ironjacamar/ironjacamar
common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java
AbstractParser.elementAsFlushStrategy
protected FlushStrategy elementAsFlushStrategy(XMLStreamReader reader, Map<String, String> expressions) throws XMLStreamException, ParserException { """ convert an xml element in FlushStrategy value @param reader the StAX reader @param expressions expressions @return the flush strategy represention @throws XMLStreamException StAX exception @throws ParserException in case it isn't a number """ String elementtext = rawElementText(reader); if (expressions != null && elementtext != null && elementtext.indexOf("${") != -1) expressions.put(CommonXML.ELEMENT_FLUSH_STRATEGY, elementtext); FlushStrategy result = FlushStrategy.forName(getSubstitutionValue(elementtext)); if (result != FlushStrategy.UNKNOWN) return result; throw new ParserException(bundle.notValidFlushStrategy(elementtext)); }
java
protected FlushStrategy elementAsFlushStrategy(XMLStreamReader reader, Map<String, String> expressions) throws XMLStreamException, ParserException { String elementtext = rawElementText(reader); if (expressions != null && elementtext != null && elementtext.indexOf("${") != -1) expressions.put(CommonXML.ELEMENT_FLUSH_STRATEGY, elementtext); FlushStrategy result = FlushStrategy.forName(getSubstitutionValue(elementtext)); if (result != FlushStrategy.UNKNOWN) return result; throw new ParserException(bundle.notValidFlushStrategy(elementtext)); }
[ "protected", "FlushStrategy", "elementAsFlushStrategy", "(", "XMLStreamReader", "reader", ",", "Map", "<", "String", ",", "String", ">", "expressions", ")", "throws", "XMLStreamException", ",", "ParserException", "{", "String", "elementtext", "=", "rawElementText", "(", "reader", ")", ";", "if", "(", "expressions", "!=", "null", "&&", "elementtext", "!=", "null", "&&", "elementtext", ".", "indexOf", "(", "\"${\"", ")", "!=", "-", "1", ")", "expressions", ".", "put", "(", "CommonXML", ".", "ELEMENT_FLUSH_STRATEGY", ",", "elementtext", ")", ";", "FlushStrategy", "result", "=", "FlushStrategy", ".", "forName", "(", "getSubstitutionValue", "(", "elementtext", ")", ")", ";", "if", "(", "result", "!=", "FlushStrategy", ".", "UNKNOWN", ")", "return", "result", ";", "throw", "new", "ParserException", "(", "bundle", ".", "notValidFlushStrategy", "(", "elementtext", ")", ")", ";", "}" ]
convert an xml element in FlushStrategy value @param reader the StAX reader @param expressions expressions @return the flush strategy represention @throws XMLStreamException StAX exception @throws ParserException in case it isn't a number
[ "convert", "an", "xml", "element", "in", "FlushStrategy", "value" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java#L316-L330
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/webapp/WebApp.java
WebApp.notifyStart
public void notifyStart() { """ use the started method above for any started specific requirements """ try { eventSource.onApplicationAvailableForService(new ApplicationEvent(this, this, new com.ibm.ws.webcontainer.util.IteratorEnumerator(config.getServletNames()))); // LIBERTY: next line added by V8 sync //this.setInitialized(true); } catch (Exception e) { com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, CLASS_NAME + ".started", "3220", this); // pk435011 logger.logp(Level.SEVERE, CLASS_NAME, "started", "error.on.collaborator.started.call"); } }
java
public void notifyStart() { try { eventSource.onApplicationAvailableForService(new ApplicationEvent(this, this, new com.ibm.ws.webcontainer.util.IteratorEnumerator(config.getServletNames()))); // LIBERTY: next line added by V8 sync //this.setInitialized(true); } catch (Exception e) { com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, CLASS_NAME + ".started", "3220", this); // pk435011 logger.logp(Level.SEVERE, CLASS_NAME, "started", "error.on.collaborator.started.call"); } }
[ "public", "void", "notifyStart", "(", ")", "{", "try", "{", "eventSource", ".", "onApplicationAvailableForService", "(", "new", "ApplicationEvent", "(", "this", ",", "this", ",", "new", "com", ".", "ibm", ".", "ws", ".", "webcontainer", ".", "util", ".", "IteratorEnumerator", "(", "config", ".", "getServletNames", "(", ")", ")", ")", ")", ";", "// LIBERTY: next line added by V8 sync", "//this.setInitialized(true);", "}", "catch", "(", "Exception", "e", ")", "{", "com", ".", "ibm", ".", "wsspi", ".", "webcontainer", ".", "util", ".", "FFDCWrapper", ".", "processException", "(", "e", ",", "CLASS_NAME", "+", "\".started\"", ",", "\"3220\"", ",", "this", ")", ";", "// pk435011", "logger", ".", "logp", "(", "Level", ".", "SEVERE", ",", "CLASS_NAME", ",", "\"started\"", ",", "\"error.on.collaborator.started.call\"", ")", ";", "}", "}" ]
use the started method above for any started specific requirements
[ "use", "the", "started", "method", "above", "for", "any", "started", "specific", "requirements" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/webapp/WebApp.java#L5455-L5465
craftercms/core
src/main/java/org/craftercms/core/cache/impl/CacheImpl.java
CacheImpl.doChecks
protected void doChecks(CacheItem item, List<CacheItem> itemsToRefresh) { """ Checks if the given {@link CacheItem} has expired or needs to be refreshed. @param item @param itemsToRefresh the list of items where to put the specified item if it needs to be refreshed """ boolean expired; boolean willBeRefreshed; try { expired = checkForExpiration(item); if (expired) { if (logger.isDebugEnabled()) { logger.debug(item + " was removed because it expired"); } } else { willBeRefreshed = checkForRefresh(item, itemsToRefresh); if (willBeRefreshed) { if (logger.isDebugEnabled()) { logger.debug(item + " will be refreshed"); } } } } catch (Exception ex) { logger.warn("Exception while checking " + item + " for expiration/refresh", ex); } }
java
protected void doChecks(CacheItem item, List<CacheItem> itemsToRefresh) { boolean expired; boolean willBeRefreshed; try { expired = checkForExpiration(item); if (expired) { if (logger.isDebugEnabled()) { logger.debug(item + " was removed because it expired"); } } else { willBeRefreshed = checkForRefresh(item, itemsToRefresh); if (willBeRefreshed) { if (logger.isDebugEnabled()) { logger.debug(item + " will be refreshed"); } } } } catch (Exception ex) { logger.warn("Exception while checking " + item + " for expiration/refresh", ex); } }
[ "protected", "void", "doChecks", "(", "CacheItem", "item", ",", "List", "<", "CacheItem", ">", "itemsToRefresh", ")", "{", "boolean", "expired", ";", "boolean", "willBeRefreshed", ";", "try", "{", "expired", "=", "checkForExpiration", "(", "item", ")", ";", "if", "(", "expired", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "item", "+", "\" was removed because it expired\"", ")", ";", "}", "}", "else", "{", "willBeRefreshed", "=", "checkForRefresh", "(", "item", ",", "itemsToRefresh", ")", ";", "if", "(", "willBeRefreshed", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "item", "+", "\" will be refreshed\"", ")", ";", "}", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "logger", ".", "warn", "(", "\"Exception while checking \"", "+", "item", "+", "\" for expiration/refresh\"", ",", "ex", ")", ";", "}", "}" ]
Checks if the given {@link CacheItem} has expired or needs to be refreshed. @param item @param itemsToRefresh the list of items where to put the specified item if it needs to be refreshed
[ "Checks", "if", "the", "given", "{", "@link", "CacheItem", "}", "has", "expired", "or", "needs", "to", "be", "refreshed", "." ]
train
https://github.com/craftercms/core/blob/d3ec74d669d3f8cfcf995177615d5f126edfa237/src/main/java/org/craftercms/core/cache/impl/CacheImpl.java#L352-L373
line/armeria
zipkin/src/main/java/com/linecorp/armeria/client/tracing/HttpTracingClient.java
HttpTracingClient.newDecorator
public static Function<Client<HttpRequest, HttpResponse>, HttpTracingClient> newDecorator( Tracing tracing, @Nullable String remoteServiceName) { """ Creates a new tracing {@link Client} decorator using the specified {@link Tracing} instance and remote service name. """ ensureScopeUsesRequestContext(tracing); return delegate -> new HttpTracingClient(delegate, tracing, remoteServiceName); }
java
public static Function<Client<HttpRequest, HttpResponse>, HttpTracingClient> newDecorator( Tracing tracing, @Nullable String remoteServiceName) { ensureScopeUsesRequestContext(tracing); return delegate -> new HttpTracingClient(delegate, tracing, remoteServiceName); }
[ "public", "static", "Function", "<", "Client", "<", "HttpRequest", ",", "HttpResponse", ">", ",", "HttpTracingClient", ">", "newDecorator", "(", "Tracing", "tracing", ",", "@", "Nullable", "String", "remoteServiceName", ")", "{", "ensureScopeUsesRequestContext", "(", "tracing", ")", ";", "return", "delegate", "->", "new", "HttpTracingClient", "(", "delegate", ",", "tracing", ",", "remoteServiceName", ")", ";", "}" ]
Creates a new tracing {@link Client} decorator using the specified {@link Tracing} instance and remote service name.
[ "Creates", "a", "new", "tracing", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/zipkin/src/main/java/com/linecorp/armeria/client/tracing/HttpTracingClient.java#L68-L73
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java
AttributeDefinition.marshallAsElement
public void marshallAsElement(final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException { """ Marshalls the value from the given {@code resourceModel} as an xml element, if it {@link #isMarshallable(org.jboss.dmr.ModelNode, boolean) is marshallable}. @param resourceModel the model, a non-null node of {@link org.jboss.dmr.ModelType#OBJECT}. @param marshallDefault {@code true} if the value should be marshalled even if it matches the default value @param writer stream writer to use for writing the attribute @throws javax.xml.stream.XMLStreamException if thrown by {@code writer} """ if (getMarshaller().isMarshallableAsElement()) { getMarshaller().marshallAsElement(this, resourceModel, marshallDefault, writer); } else { throw ControllerLogger.ROOT_LOGGER.couldNotMarshalAttributeAsElement(getName()); } }
java
public void marshallAsElement(final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException { if (getMarshaller().isMarshallableAsElement()) { getMarshaller().marshallAsElement(this, resourceModel, marshallDefault, writer); } else { throw ControllerLogger.ROOT_LOGGER.couldNotMarshalAttributeAsElement(getName()); } }
[ "public", "void", "marshallAsElement", "(", "final", "ModelNode", "resourceModel", ",", "final", "boolean", "marshallDefault", ",", "final", "XMLStreamWriter", "writer", ")", "throws", "XMLStreamException", "{", "if", "(", "getMarshaller", "(", ")", ".", "isMarshallableAsElement", "(", ")", ")", "{", "getMarshaller", "(", ")", ".", "marshallAsElement", "(", "this", ",", "resourceModel", ",", "marshallDefault", ",", "writer", ")", ";", "}", "else", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "couldNotMarshalAttributeAsElement", "(", "getName", "(", ")", ")", ";", "}", "}" ]
Marshalls the value from the given {@code resourceModel} as an xml element, if it {@link #isMarshallable(org.jboss.dmr.ModelNode, boolean) is marshallable}. @param resourceModel the model, a non-null node of {@link org.jboss.dmr.ModelType#OBJECT}. @param marshallDefault {@code true} if the value should be marshalled even if it matches the default value @param writer stream writer to use for writing the attribute @throws javax.xml.stream.XMLStreamException if thrown by {@code writer}
[ "Marshalls", "the", "value", "from", "the", "given", "{", "@code", "resourceModel", "}", "as", "an", "xml", "element", "if", "it", "{", "@link", "#isMarshallable", "(", "org", ".", "jboss", ".", "dmr", ".", "ModelNode", "boolean", ")", "is", "marshallable", "}", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java#L756-L762
EsotericSoftware/kryo
src/com/esotericsoftware/kryo/unsafe/UnsafeUtil.java
UnsafeUtil.newDirectBuffer
static public ByteBuffer newDirectBuffer (long address, int size) { """ Create a ByteBuffer that uses the specified off-heap memory address instead of allocating a new one. @param address Address of the memory region to be used for a ByteBuffer. @param size Size in bytes of the memory region. @throws UnsupportedOperationException if creating a ByteBuffer this way is not available. """ if (directByteBufferConstructor == null) throw new UnsupportedOperationException("No direct ByteBuffer constructor is available."); try { return directByteBufferConstructor.newInstance(address, size, null); } catch (Exception ex) { throw new KryoException("Error creating a ByteBuffer at address: " + address, ex); } }
java
static public ByteBuffer newDirectBuffer (long address, int size) { if (directByteBufferConstructor == null) throw new UnsupportedOperationException("No direct ByteBuffer constructor is available."); try { return directByteBufferConstructor.newInstance(address, size, null); } catch (Exception ex) { throw new KryoException("Error creating a ByteBuffer at address: " + address, ex); } }
[ "static", "public", "ByteBuffer", "newDirectBuffer", "(", "long", "address", ",", "int", "size", ")", "{", "if", "(", "directByteBufferConstructor", "==", "null", ")", "throw", "new", "UnsupportedOperationException", "(", "\"No direct ByteBuffer constructor is available.\"", ")", ";", "try", "{", "return", "directByteBufferConstructor", ".", "newInstance", "(", "address", ",", "size", ",", "null", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "KryoException", "(", "\"Error creating a ByteBuffer at address: \"", "+", "address", ",", "ex", ")", ";", "}", "}" ]
Create a ByteBuffer that uses the specified off-heap memory address instead of allocating a new one. @param address Address of the memory region to be used for a ByteBuffer. @param size Size in bytes of the memory region. @throws UnsupportedOperationException if creating a ByteBuffer this way is not available.
[ "Create", "a", "ByteBuffer", "that", "uses", "the", "specified", "off", "-", "heap", "memory", "address", "instead", "of", "allocating", "a", "new", "one", "." ]
train
https://github.com/EsotericSoftware/kryo/blob/a8be1ab26f347f299a3c3f7171d6447dd5390845/src/com/esotericsoftware/kryo/unsafe/UnsafeUtil.java#L123-L131
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/MapOutputFile.java
MapOutputFile.getSpillIndexFile
public Path getSpillIndexFile(TaskAttemptID mapTaskId, int spillNumber) throws IOException { """ Return a local map spill index file created earlier @param mapTaskId a map task id @param spillNumber the number """ return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir( jobId.toString(), mapTaskId.toString()) + "/spill" + spillNumber + ".out.index", conf); }
java
public Path getSpillIndexFile(TaskAttemptID mapTaskId, int spillNumber) throws IOException { return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir( jobId.toString(), mapTaskId.toString()) + "/spill" + spillNumber + ".out.index", conf); }
[ "public", "Path", "getSpillIndexFile", "(", "TaskAttemptID", "mapTaskId", ",", "int", "spillNumber", ")", "throws", "IOException", "{", "return", "lDirAlloc", ".", "getLocalPathToRead", "(", "TaskTracker", ".", "getIntermediateOutputDir", "(", "jobId", ".", "toString", "(", ")", ",", "mapTaskId", ".", "toString", "(", ")", ")", "+", "\"/spill\"", "+", "spillNumber", "+", "\".out.index\"", ",", "conf", ")", ";", "}" ]
Return a local map spill index file created earlier @param mapTaskId a map task id @param spillNumber the number
[ "Return", "a", "local", "map", "spill", "index", "file", "created", "earlier" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/MapOutputFile.java#L129-L135
landawn/AbacusUtil
src/com/landawn/abacus/util/IOUtil.java
IOUtil.estimateLineCount
private static long estimateLineCount(final File file, final int byReadingLineNum) throws UncheckedIOException { """ Estimate the total line count of the file by reading the specified line count ahead. @param file @param byReadingLineNum @return """ final Holder<ZipFile> outputZipFile = new Holder<>(); InputStream is = null; BufferedReader br = null; try { is = openFile(outputZipFile, file); br = Objectory.createBufferedReader(is); int cnt = 0; String line = null; long bytes = 0; while (cnt < byReadingLineNum && (line = br.readLine()) != null) { bytes += line.getBytes().length; cnt++; } return cnt == 0 ? 0 : (file.length() / (bytes / cnt == 0 ? 1 : bytes / cnt)); } catch (IOException e) { throw new UncheckedIOException(e); } finally { closeQuietly(is); closeQuietly(outputZipFile.value()); Objectory.recycle(br); } }
java
private static long estimateLineCount(final File file, final int byReadingLineNum) throws UncheckedIOException { final Holder<ZipFile> outputZipFile = new Holder<>(); InputStream is = null; BufferedReader br = null; try { is = openFile(outputZipFile, file); br = Objectory.createBufferedReader(is); int cnt = 0; String line = null; long bytes = 0; while (cnt < byReadingLineNum && (line = br.readLine()) != null) { bytes += line.getBytes().length; cnt++; } return cnt == 0 ? 0 : (file.length() / (bytes / cnt == 0 ? 1 : bytes / cnt)); } catch (IOException e) { throw new UncheckedIOException(e); } finally { closeQuietly(is); closeQuietly(outputZipFile.value()); Objectory.recycle(br); } }
[ "private", "static", "long", "estimateLineCount", "(", "final", "File", "file", ",", "final", "int", "byReadingLineNum", ")", "throws", "UncheckedIOException", "{", "final", "Holder", "<", "ZipFile", ">", "outputZipFile", "=", "new", "Holder", "<>", "(", ")", ";", "InputStream", "is", "=", "null", ";", "BufferedReader", "br", "=", "null", ";", "try", "{", "is", "=", "openFile", "(", "outputZipFile", ",", "file", ")", ";", "br", "=", "Objectory", ".", "createBufferedReader", "(", "is", ")", ";", "int", "cnt", "=", "0", ";", "String", "line", "=", "null", ";", "long", "bytes", "=", "0", ";", "while", "(", "cnt", "<", "byReadingLineNum", "&&", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "bytes", "+=", "line", ".", "getBytes", "(", ")", ".", "length", ";", "cnt", "++", ";", "}", "return", "cnt", "==", "0", "?", "0", ":", "(", "file", ".", "length", "(", ")", "/", "(", "bytes", "/", "cnt", "==", "0", "?", "1", ":", "bytes", "/", "cnt", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "UncheckedIOException", "(", "e", ")", ";", "}", "finally", "{", "closeQuietly", "(", "is", ")", ";", "closeQuietly", "(", "outputZipFile", ".", "value", "(", ")", ")", ";", "Objectory", ".", "recycle", "(", "br", ")", ";", "}", "}" ]
Estimate the total line count of the file by reading the specified line count ahead. @param file @param byReadingLineNum @return
[ "Estimate", "the", "total", "line", "count", "of", "the", "file", "by", "reading", "the", "specified", "line", "count", "ahead", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/IOUtil.java#L3468-L3496
LearnLib/automatalib
util/src/main/java/net/automatalib/util/minimizer/BlockMap.java
BlockMap.put
@Override public V put(Block<?, ?> block, V value) { """ Stores a value. @param block the associated block. @param value the value. """ @SuppressWarnings("unchecked") V old = (V) storage[block.getId()]; storage[block.getId()] = value; return old; }
java
@Override public V put(Block<?, ?> block, V value) { @SuppressWarnings("unchecked") V old = (V) storage[block.getId()]; storage[block.getId()] = value; return old; }
[ "@", "Override", "public", "V", "put", "(", "Block", "<", "?", ",", "?", ">", "block", ",", "V", "value", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "V", "old", "=", "(", "V", ")", "storage", "[", "block", ".", "getId", "(", ")", "]", ";", "storage", "[", "block", ".", "getId", "(", ")", "]", "=", "value", ";", "return", "old", ";", "}" ]
Stores a value. @param block the associated block. @param value the value.
[ "Stores", "a", "value", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/minimizer/BlockMap.java#L70-L76
facebook/fresco
drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java
WrappingUtils.maybeWrapWithMatrix
@Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { """ Wraps the given drawable with a new {@link MatrixDrawable}. <p> If the provided drawable or matrix is null, the given drawable is returned without being wrapped. @return the wrapping matrix drawable, or the original drawable if the wrapping didn't take place """ if (drawable == null || matrix == null) { return drawable; } return new MatrixDrawable(drawable, matrix); }
java
@Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { if (drawable == null || matrix == null) { return drawable; } return new MatrixDrawable(drawable, matrix); }
[ "@", "Nullable", "static", "Drawable", "maybeWrapWithMatrix", "(", "@", "Nullable", "Drawable", "drawable", ",", "@", "Nullable", "Matrix", "matrix", ")", "{", "if", "(", "drawable", "==", "null", "||", "matrix", "==", "null", ")", "{", "return", "drawable", ";", "}", "return", "new", "MatrixDrawable", "(", "drawable", ",", "matrix", ")", ";", "}" ]
Wraps the given drawable with a new {@link MatrixDrawable}. <p> If the provided drawable or matrix is null, the given drawable is returned without being wrapped. @return the wrapping matrix drawable, or the original drawable if the wrapping didn't take place
[ "Wraps", "the", "given", "drawable", "with", "a", "new", "{", "@link", "MatrixDrawable", "}", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java#L113-L121
UrielCh/ovh-java-sdk
ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java
ApiOvhClusterhadoop.orderInformations_GET
public OvhOrderInformations orderInformations_GET() throws IOException { """ Get informations about the order of one cluster REST: GET /cluster/hadoop/orderInformations """ String qPath = "/cluster/hadoop/orderInformations"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrderInformations.class); }
java
public OvhOrderInformations orderInformations_GET() throws IOException { String qPath = "/cluster/hadoop/orderInformations"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrderInformations.class); }
[ "public", "OvhOrderInformations", "orderInformations_GET", "(", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cluster/hadoop/orderInformations\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrderInformations", ".", "class", ")", ";", "}" ]
Get informations about the order of one cluster REST: GET /cluster/hadoop/orderInformations
[ "Get", "informations", "about", "the", "order", "of", "one", "cluster" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java#L639-L644
forge/core
javaee/impl/src/main/java/org/jboss/forge/addon/javaee/rest/generator/dto/DTOCollection.java
DTOCollection.addRootDTO
public void addRootDTO(JavaClass<?> entity, JavaClassSource rootDTO) { """ Registers the root DTO created for a JPA entity @param entity The JPA entity @param rootDTO The root DTO created for the JPA entity """ DTOPair dtoPair = dtos.containsKey(entity) ? dtos.get(entity) : new DTOPair(); dtoPair.rootDTO = rootDTO; dtos.put(entity, dtoPair); }
java
public void addRootDTO(JavaClass<?> entity, JavaClassSource rootDTO) { DTOPair dtoPair = dtos.containsKey(entity) ? dtos.get(entity) : new DTOPair(); dtoPair.rootDTO = rootDTO; dtos.put(entity, dtoPair); }
[ "public", "void", "addRootDTO", "(", "JavaClass", "<", "?", ">", "entity", ",", "JavaClassSource", "rootDTO", ")", "{", "DTOPair", "dtoPair", "=", "dtos", ".", "containsKey", "(", "entity", ")", "?", "dtos", ".", "get", "(", "entity", ")", ":", "new", "DTOPair", "(", ")", ";", "dtoPair", ".", "rootDTO", "=", "rootDTO", ";", "dtos", ".", "put", "(", "entity", ",", "dtoPair", ")", ";", "}" ]
Registers the root DTO created for a JPA entity @param entity The JPA entity @param rootDTO The root DTO created for the JPA entity
[ "Registers", "the", "root", "DTO", "created", "for", "a", "JPA", "entity" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/javaee/impl/src/main/java/org/jboss/forge/addon/javaee/rest/generator/dto/DTOCollection.java#L56-L61
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/RobotiumUtils.java
RobotiumUtils.sortViewsByLocationOnScreen
public static void sortViewsByLocationOnScreen(List<? extends View> views, boolean yAxisFirst) { """ Orders Views by their location on-screen. @param views The views to sort @param yAxisFirst Whether the y-axis should be compared before the x-axis @see ViewLocationComparator """ Collections.sort(views, new ViewLocationComparator(yAxisFirst)); }
java
public static void sortViewsByLocationOnScreen(List<? extends View> views, boolean yAxisFirst) { Collections.sort(views, new ViewLocationComparator(yAxisFirst)); }
[ "public", "static", "void", "sortViewsByLocationOnScreen", "(", "List", "<", "?", "extends", "View", ">", "views", ",", "boolean", "yAxisFirst", ")", "{", "Collections", ".", "sort", "(", "views", ",", "new", "ViewLocationComparator", "(", "yAxisFirst", ")", ")", ";", "}" ]
Orders Views by their location on-screen. @param views The views to sort @param yAxisFirst Whether the y-axis should be compared before the x-axis @see ViewLocationComparator
[ "Orders", "Views", "by", "their", "location", "on", "-", "screen", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/RobotiumUtils.java#L103-L105
vanilladb/vanillacore
src/main/java/org/vanilladb/core/query/algebra/TableScan.java
TableScan.setVal
@Override public void setVal(String fldName, Constant val) { """ Sets the value of the specified field, as a Constant. @param val the constant to be set. Will be casted to the correct type specified in the schema of the table. @see UpdateScan#setVal(java.lang.String, Constant) """ rf.setVal(fldName, val); }
java
@Override public void setVal(String fldName, Constant val) { rf.setVal(fldName, val); }
[ "@", "Override", "public", "void", "setVal", "(", "String", "fldName", ",", "Constant", "val", ")", "{", "rf", ".", "setVal", "(", "fldName", ",", "val", ")", ";", "}" ]
Sets the value of the specified field, as a Constant. @param val the constant to be set. Will be casted to the correct type specified in the schema of the table. @see UpdateScan#setVal(java.lang.String, Constant)
[ "Sets", "the", "value", "of", "the", "specified", "field", "as", "a", "Constant", "." ]
train
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/query/algebra/TableScan.java#L90-L93
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2StreamSourceChannel.java
Http2StreamSourceChannel.updateContentSize
void updateContentSize(long frameLength, boolean last) { """ Checks that the actual content size matches the expected. We check this proactivly, rather than as the data is read @param frameLength The amount of data in the frame @param last If this is the last frame """ if(contentLengthRemaining != -1) { contentLengthRemaining -= frameLength; if(contentLengthRemaining < 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length exceeds content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } else if(last && contentLengthRemaining != 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length was less than content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } } }
java
void updateContentSize(long frameLength, boolean last) { if(contentLengthRemaining != -1) { contentLengthRemaining -= frameLength; if(contentLengthRemaining < 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length exceeds content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } else if(last && contentLengthRemaining != 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length was less than content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } } }
[ "void", "updateContentSize", "(", "long", "frameLength", ",", "boolean", "last", ")", "{", "if", "(", "contentLengthRemaining", "!=", "-", "1", ")", "{", "contentLengthRemaining", "-=", "frameLength", ";", "if", "(", "contentLengthRemaining", "<", "0", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debugf", "(", "\"Closing stream %s on %s as data length exceeds content size\"", ",", "streamId", ",", "getFramedChannel", "(", ")", ")", ";", "getFramedChannel", "(", ")", ".", "sendRstStream", "(", "streamId", ",", "Http2Channel", ".", "ERROR_PROTOCOL_ERROR", ")", ";", "}", "else", "if", "(", "last", "&&", "contentLengthRemaining", "!=", "0", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debugf", "(", "\"Closing stream %s on %s as data length was less than content size\"", ",", "streamId", ",", "getFramedChannel", "(", ")", ")", ";", "getFramedChannel", "(", ")", ".", "sendRstStream", "(", "streamId", ",", "Http2Channel", ".", "ERROR_PROTOCOL_ERROR", ")", ";", "}", "}", "}" ]
Checks that the actual content size matches the expected. We check this proactivly, rather than as the data is read @param frameLength The amount of data in the frame @param last If this is the last frame
[ "Checks", "that", "the", "actual", "content", "size", "matches", "the", "expected", ".", "We", "check", "this", "proactivly", "rather", "than", "as", "the", "data", "is", "read" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2StreamSourceChannel.java#L277-L288
azkaban/azkaban
azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java
FileIOUtils.dumpNumberToFile
public static void dumpNumberToFile(final Path filePath, final long num) throws IOException { """ Dumps a number into a new file. @param filePath the target file @param num the number to dump @throws IOException if file already exists """ try (final BufferedWriter writer = Files .newBufferedWriter(filePath, StandardCharsets.UTF_8)) { writer.write(String.valueOf(num)); } catch (final IOException e) { log.error("Failed to write the number {} to the file {}", num, filePath, e); throw e; } }
java
public static void dumpNumberToFile(final Path filePath, final long num) throws IOException { try (final BufferedWriter writer = Files .newBufferedWriter(filePath, StandardCharsets.UTF_8)) { writer.write(String.valueOf(num)); } catch (final IOException e) { log.error("Failed to write the number {} to the file {}", num, filePath, e); throw e; } }
[ "public", "static", "void", "dumpNumberToFile", "(", "final", "Path", "filePath", ",", "final", "long", "num", ")", "throws", "IOException", "{", "try", "(", "final", "BufferedWriter", "writer", "=", "Files", ".", "newBufferedWriter", "(", "filePath", ",", "StandardCharsets", ".", "UTF_8", ")", ")", "{", "writer", ".", "write", "(", "String", ".", "valueOf", "(", "num", ")", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "log", ".", "error", "(", "\"Failed to write the number {} to the file {}\"", ",", "num", ",", "filePath", ",", "e", ")", ";", "throw", "e", ";", "}", "}" ]
Dumps a number into a new file. @param filePath the target file @param num the number to dump @throws IOException if file already exists
[ "Dumps", "a", "number", "into", "a", "new", "file", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/utils/FileIOUtils.java#L101-L109
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/DefaultApplicationObjectConfigurer.java
DefaultApplicationObjectConfigurer.configureLabel
protected void configureLabel(LabelConfigurable configurable, String objectName) { """ Sets the {@link LabelInfo} of the given object. The label info is created after loading the encoded label string from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.label </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null. """ Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String labelStr = loadMessage(objectName + "." + LABEL_KEY); if (StringUtils.hasText(labelStr)) { LabelInfo labelInfo = LabelInfo.valueOf(labelStr); configurable.setLabelInfo(labelInfo); } }
java
protected void configureLabel(LabelConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String labelStr = loadMessage(objectName + "." + LABEL_KEY); if (StringUtils.hasText(labelStr)) { LabelInfo labelInfo = LabelInfo.valueOf(labelStr); configurable.setLabelInfo(labelInfo); } }
[ "protected", "void", "configureLabel", "(", "LabelConfigurable", "configurable", ",", "String", "objectName", ")", "{", "Assert", ".", "notNull", "(", "configurable", ",", "\"configurable\"", ")", ";", "Assert", ".", "notNull", "(", "objectName", ",", "\"objectName\"", ")", ";", "String", "labelStr", "=", "loadMessage", "(", "objectName", "+", "\".\"", "+", "LABEL_KEY", ")", ";", "if", "(", "StringUtils", ".", "hasText", "(", "labelStr", ")", ")", "{", "LabelInfo", "labelInfo", "=", "LabelInfo", ".", "valueOf", "(", "labelStr", ")", ";", "configurable", ".", "setLabelInfo", "(", "labelInfo", ")", ";", "}", "}" ]
Sets the {@link LabelInfo} of the given object. The label info is created after loading the encoded label string from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.label </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
[ "Sets", "the", "{", "@link", "LabelInfo", "}", "of", "the", "given", "object", ".", "The", "label", "info", "is", "created", "after", "loading", "the", "encoded", "label", "string", "from", "this", "instance", "s", "{", "@link", "MessageSource", "}", "using", "a", "message", "code", "in", "the", "format" ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/DefaultApplicationObjectConfigurer.java#L372-L382
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/Quaternion.java
Quaternion.getAxisAngle
@SuppressWarnings("synthetic-access") @Pure public final AxisAngle getAxisAngle() { """ Replies the rotation axis represented by this quaternion. @return the rotation axis @see #setAxisAngle(Vector3D, double) @see #setAxisAngle(double, double, double, double) @see #getAngle() """ double mag = this.x*this.x + this.y*this.y + this.z*this.z; if ( mag > EPS ) { mag = Math.sqrt(mag); double invMag = 1f/mag; return new AxisAngle( this.x*invMag, this.y*invMag, this.z*invMag, (2.*Math.atan2(mag, this.w))); } return new AxisAngle(0, 0, 1, 0); }
java
@SuppressWarnings("synthetic-access") @Pure public final AxisAngle getAxisAngle() { double mag = this.x*this.x + this.y*this.y + this.z*this.z; if ( mag > EPS ) { mag = Math.sqrt(mag); double invMag = 1f/mag; return new AxisAngle( this.x*invMag, this.y*invMag, this.z*invMag, (2.*Math.atan2(mag, this.w))); } return new AxisAngle(0, 0, 1, 0); }
[ "@", "SuppressWarnings", "(", "\"synthetic-access\"", ")", "@", "Pure", "public", "final", "AxisAngle", "getAxisAngle", "(", ")", "{", "double", "mag", "=", "this", ".", "x", "*", "this", ".", "x", "+", "this", ".", "y", "*", "this", ".", "y", "+", "this", ".", "z", "*", "this", ".", "z", ";", "if", "(", "mag", ">", "EPS", ")", "{", "mag", "=", "Math", ".", "sqrt", "(", "mag", ")", ";", "double", "invMag", "=", "1f", "/", "mag", ";", "return", "new", "AxisAngle", "(", "this", ".", "x", "*", "invMag", ",", "this", ".", "y", "*", "invMag", ",", "this", ".", "z", "*", "invMag", ",", "(", "2.", "*", "Math", ".", "atan2", "(", "mag", ",", "this", ".", "w", ")", ")", ")", ";", "}", "return", "new", "AxisAngle", "(", "0", ",", "0", ",", "1", ",", "0", ")", ";", "}" ]
Replies the rotation axis represented by this quaternion. @return the rotation axis @see #setAxisAngle(Vector3D, double) @see #setAxisAngle(double, double, double, double) @see #getAngle()
[ "Replies", "the", "rotation", "axis", "represented", "by", "this", "quaternion", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Quaternion.java#L713-L729
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java
CPInstancePersistenceImpl.findByC_NotST
@Override public List<CPInstance> findByC_NotST(long CPDefinitionId, int status, int start, int end) { """ Returns a range of all the cp instances where CPDefinitionId = &#63; and status &ne; &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPInstanceModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param CPDefinitionId the cp definition ID @param status the status @param start the lower bound of the range of cp instances @param end the upper bound of the range of cp instances (not inclusive) @return the range of matching cp instances """ return findByC_NotST(CPDefinitionId, status, start, end, null); }
java
@Override public List<CPInstance> findByC_NotST(long CPDefinitionId, int status, int start, int end) { return findByC_NotST(CPDefinitionId, status, start, end, null); }
[ "@", "Override", "public", "List", "<", "CPInstance", ">", "findByC_NotST", "(", "long", "CPDefinitionId", ",", "int", "status", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByC_NotST", "(", "CPDefinitionId", ",", "status", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp instances where CPDefinitionId = &#63; and status &ne; &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPInstanceModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param CPDefinitionId the cp definition ID @param status the status @param start the lower bound of the range of cp instances @param end the upper bound of the range of cp instances (not inclusive) @return the range of matching cp instances
[ "Returns", "a", "range", "of", "all", "the", "cp", "instances", "where", "CPDefinitionId", "=", "&#63", ";", "and", "status", "&ne", ";", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L5146-L5150
looly/hutool
hutool-core/src/main/java/cn/hutool/core/codec/Base64Decoder.java
Base64Decoder.getNextValidDecodeByte
private static byte getNextValidDecodeByte(byte[] in, IntWrapper pos, int maxPos) { """ 获取下一个有效的byte字符 @param in 输入 @param pos 当前位置,调用此方法后此位置保持在有效字符的下一个位置 @param maxPos 最大位置 @return 有效字符,如果达到末尾返回 """ byte base64Byte; byte decodeByte; while (pos.value <= maxPos) { base64Byte = in[pos.value++]; if (base64Byte > -1) { decodeByte = DECODE_TABLE[base64Byte]; if (decodeByte > -1) { return decodeByte; } } } // padding if reached max position return PADDING; }
java
private static byte getNextValidDecodeByte(byte[] in, IntWrapper pos, int maxPos) { byte base64Byte; byte decodeByte; while (pos.value <= maxPos) { base64Byte = in[pos.value++]; if (base64Byte > -1) { decodeByte = DECODE_TABLE[base64Byte]; if (decodeByte > -1) { return decodeByte; } } } // padding if reached max position return PADDING; }
[ "private", "static", "byte", "getNextValidDecodeByte", "(", "byte", "[", "]", "in", ",", "IntWrapper", "pos", ",", "int", "maxPos", ")", "{", "byte", "base64Byte", ";", "byte", "decodeByte", ";", "while", "(", "pos", ".", "value", "<=", "maxPos", ")", "{", "base64Byte", "=", "in", "[", "pos", ".", "value", "++", "]", ";", "if", "(", "base64Byte", ">", "-", "1", ")", "{", "decodeByte", "=", "DECODE_TABLE", "[", "base64Byte", "]", ";", "if", "(", "decodeByte", ">", "-", "1", ")", "{", "return", "decodeByte", ";", "}", "}", "}", "// padding if reached max position\r", "return", "PADDING", ";", "}" ]
获取下一个有效的byte字符 @param in 输入 @param pos 当前位置,调用此方法后此位置保持在有效字符的下一个位置 @param maxPos 最大位置 @return 有效字符,如果达到末尾返回
[ "获取下一个有效的byte字符" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/codec/Base64Decoder.java#L174-L188
blinkfox/zealot
src/main/java/com/blinkfox/zealot/config/scanner/TaggerScanner.java
TaggerScanner.addClassesByFile
private void addClassesByFile(ClassLoader classLoader, String packageName, String packagePath) { """ 以文件的形式来获取包下的所有Class. @param classLoader 类加载器 @param packageName 包名 @param packagePath 包路径 """ // 获取此包的目录 建立一个File,如果不存在或者 也不是目录就直接返回 File dir = new File(packagePath); if (!dir.exists() || !dir.isDirectory()) { return; } // 如果存在,就获取包下的所有文件,包括目录,筛选出目录和.class文件. File[] dirfiles = dir.listFiles(new FileFilter() { @Override public boolean accept(File file) { return (file.isDirectory()) || StringHelper.isClassFile(file.getName()); } }); if (dirfiles == null) { return; } // 循环所有文件,如果是目录 则继续扫描 for (File file : dirfiles) { if (file.isDirectory()) { this.addClassesByFile(classLoader, packageName + "." + file.getName(), file.getAbsolutePath()); continue; } // 如果是java类文件 去掉后面的.class,只留下类名,添加到集合中去. String className = file.getName().substring(0, file.getName().lastIndexOf('.')); this.addClassByName(classLoader, packageName + '.' + className); } }
java
private void addClassesByFile(ClassLoader classLoader, String packageName, String packagePath) { // 获取此包的目录 建立一个File,如果不存在或者 也不是目录就直接返回 File dir = new File(packagePath); if (!dir.exists() || !dir.isDirectory()) { return; } // 如果存在,就获取包下的所有文件,包括目录,筛选出目录和.class文件. File[] dirfiles = dir.listFiles(new FileFilter() { @Override public boolean accept(File file) { return (file.isDirectory()) || StringHelper.isClassFile(file.getName()); } }); if (dirfiles == null) { return; } // 循环所有文件,如果是目录 则继续扫描 for (File file : dirfiles) { if (file.isDirectory()) { this.addClassesByFile(classLoader, packageName + "." + file.getName(), file.getAbsolutePath()); continue; } // 如果是java类文件 去掉后面的.class,只留下类名,添加到集合中去. String className = file.getName().substring(0, file.getName().lastIndexOf('.')); this.addClassByName(classLoader, packageName + '.' + className); } }
[ "private", "void", "addClassesByFile", "(", "ClassLoader", "classLoader", ",", "String", "packageName", ",", "String", "packagePath", ")", "{", "// 获取此包的目录 建立一个File,如果不存在或者 也不是目录就直接返回", "File", "dir", "=", "new", "File", "(", "packagePath", ")", ";", "if", "(", "!", "dir", ".", "exists", "(", ")", "||", "!", "dir", ".", "isDirectory", "(", ")", ")", "{", "return", ";", "}", "// 如果存在,就获取包下的所有文件,包括目录,筛选出目录和.class文件.", "File", "[", "]", "dirfiles", "=", "dir", ".", "listFiles", "(", "new", "FileFilter", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "File", "file", ")", "{", "return", "(", "file", ".", "isDirectory", "(", ")", ")", "||", "StringHelper", ".", "isClassFile", "(", "file", ".", "getName", "(", ")", ")", ";", "}", "}", ")", ";", "if", "(", "dirfiles", "==", "null", ")", "{", "return", ";", "}", "// 循环所有文件,如果是目录 则继续扫描", "for", "(", "File", "file", ":", "dirfiles", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "this", ".", "addClassesByFile", "(", "classLoader", ",", "packageName", "+", "\".\"", "+", "file", ".", "getName", "(", ")", ",", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "continue", ";", "}", "// 如果是java类文件 去掉后面的.class,只留下类名,添加到集合中去.", "String", "className", "=", "file", ".", "getName", "(", ")", ".", "substring", "(", "0", ",", "file", ".", "getName", "(", ")", ".", "lastIndexOf", "(", "'", "'", ")", ")", ";", "this", ".", "addClassByName", "(", "classLoader", ",", "packageName", "+", "'", "'", "+", "className", ")", ";", "}", "}" ]
以文件的形式来获取包下的所有Class. @param classLoader 类加载器 @param packageName 包名 @param packagePath 包路径
[ "以文件的形式来获取包下的所有Class", "." ]
train
https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/config/scanner/TaggerScanner.java#L155-L184
qspin/qtaste
kernel/src/main/java/com/qspin/qtaste/tcom/jmx/impl/JMXClient.java
JMXClient.removeNotificationListener
public boolean removeNotificationListener(String mbeanName, NotificationListener listener) throws Exception { """ Removes listener as notification and connection notification listener. @return true if successful, false otherwise @throws java.lang.Exception """ if (isConnected()) { ObjectName objectName = new ObjectName(mbeanName); mbsc.removeNotificationListener(objectName, listener, null, null); jmxc.removeConnectionNotificationListener(listener); return true; } else { return false; } }
java
public boolean removeNotificationListener(String mbeanName, NotificationListener listener) throws Exception { if (isConnected()) { ObjectName objectName = new ObjectName(mbeanName); mbsc.removeNotificationListener(objectName, listener, null, null); jmxc.removeConnectionNotificationListener(listener); return true; } else { return false; } }
[ "public", "boolean", "removeNotificationListener", "(", "String", "mbeanName", ",", "NotificationListener", "listener", ")", "throws", "Exception", "{", "if", "(", "isConnected", "(", ")", ")", "{", "ObjectName", "objectName", "=", "new", "ObjectName", "(", "mbeanName", ")", ";", "mbsc", ".", "removeNotificationListener", "(", "objectName", ",", "listener", ",", "null", ",", "null", ")", ";", "jmxc", ".", "removeConnectionNotificationListener", "(", "listener", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Removes listener as notification and connection notification listener. @return true if successful, false otherwise @throws java.lang.Exception
[ "Removes", "listener", "as", "notification", "and", "connection", "notification", "listener", "." ]
train
https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/kernel/src/main/java/com/qspin/qtaste/tcom/jmx/impl/JMXClient.java#L113-L122
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java
ValueRange.checkValidIntValue
public int checkValidIntValue(long value, TemporalField field) { """ Checks that the specified value is valid and fits in an {@code int}. <p> This validates that the value is within the valid range of values and that all valid values are within the bounds of an {@code int}. The field is only used to improve the error message. @param value the value to check @param field the field being checked, may be null @return the value that was passed in @see #isValidIntValue(long) """ if (isValidIntValue(value) == false) { throw new DateTimeException(genInvalidFieldMessage(field, value)); } return (int) value; }
java
public int checkValidIntValue(long value, TemporalField field) { if (isValidIntValue(value) == false) { throw new DateTimeException(genInvalidFieldMessage(field, value)); } return (int) value; }
[ "public", "int", "checkValidIntValue", "(", "long", "value", ",", "TemporalField", "field", ")", "{", "if", "(", "isValidIntValue", "(", "value", ")", "==", "false", ")", "{", "throw", "new", "DateTimeException", "(", "genInvalidFieldMessage", "(", "field", ",", "value", ")", ")", ";", "}", "return", "(", "int", ")", "value", ";", "}" ]
Checks that the specified value is valid and fits in an {@code int}. <p> This validates that the value is within the valid range of values and that all valid values are within the bounds of an {@code int}. The field is only used to improve the error message. @param value the value to check @param field the field being checked, may be null @return the value that was passed in @see #isValidIntValue(long)
[ "Checks", "that", "the", "specified", "value", "is", "valid", "and", "fits", "in", "an", "{", "@code", "int", "}", ".", "<p", ">", "This", "validates", "that", "the", "value", "is", "within", "the", "valid", "range", "of", "values", "and", "that", "all", "valid", "values", "are", "within", "the", "bounds", "of", "an", "{", "@code", "int", "}", ".", "The", "field", "is", "only", "used", "to", "improve", "the", "error", "message", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java#L328-L333