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
att/AAF
cadi/aaf/src/main/java/com/att/cadi/aaf/v2_0/AAFAuthn.java
AAFAuthn.validate
public String validate(String user, String password) throws IOException, CadiException { """ Returns null if ok, or an Error String; @param user @param password @return @throws IOException @throws CadiException @throws Exception """ User<AAFPermission> usr = getUser(user); if(password.startsWith("enc:???")) { password = access.decrypt(password, true); } byte[] bytes = password.getBytes(); if(usr != null && usr.principal != null && usr.principal.getName().equals(user) && usr.principal instanceof GetCred) { if(Hash.isEqual(((GetCred)usr.principal).getCred(),bytes)) { return null; } else { remove(usr); usr = null; } } AAFCachedPrincipal cp = new AAFCachedPrincipal(this,con.app, user, bytes, con.cleanInterval); // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch // Statement switch(cp.revalidate()) { case REVALIDATED: if(usr!=null) { usr.principal = cp; } else { addUser(new User<AAFPermission>(cp,con.timeout)); } return null; case INACCESSIBLE: return "AAF Inaccessible"; case UNVALIDATED: return "User/Pass combo invalid for " + user; case DENIED: return "AAF denies API for " + user; default: return "AAFAuthn doesn't handle Principal " + user; } }
java
public String validate(String user, String password) throws IOException, CadiException { User<AAFPermission> usr = getUser(user); if(password.startsWith("enc:???")) { password = access.decrypt(password, true); } byte[] bytes = password.getBytes(); if(usr != null && usr.principal != null && usr.principal.getName().equals(user) && usr.principal instanceof GetCred) { if(Hash.isEqual(((GetCred)usr.principal).getCred(),bytes)) { return null; } else { remove(usr); usr = null; } } AAFCachedPrincipal cp = new AAFCachedPrincipal(this,con.app, user, bytes, con.cleanInterval); // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch // Statement switch(cp.revalidate()) { case REVALIDATED: if(usr!=null) { usr.principal = cp; } else { addUser(new User<AAFPermission>(cp,con.timeout)); } return null; case INACCESSIBLE: return "AAF Inaccessible"; case UNVALIDATED: return "User/Pass combo invalid for " + user; case DENIED: return "AAF denies API for " + user; default: return "AAFAuthn doesn't handle Principal " + user; } }
[ "public", "String", "validate", "(", "String", "user", ",", "String", "password", ")", "throws", "IOException", ",", "CadiException", "{", "User", "<", "AAFPermission", ">", "usr", "=", "getUser", "(", "user", ")", ";", "if", "(", "password", ".", "startsWith", "(", "\"enc:???\"", ")", ")", "{", "password", "=", "access", ".", "decrypt", "(", "password", ",", "true", ")", ";", "}", "byte", "[", "]", "bytes", "=", "password", ".", "getBytes", "(", ")", ";", "if", "(", "usr", "!=", "null", "&&", "usr", ".", "principal", "!=", "null", "&&", "usr", ".", "principal", ".", "getName", "(", ")", ".", "equals", "(", "user", ")", "&&", "usr", ".", "principal", "instanceof", "GetCred", ")", "{", "if", "(", "Hash", ".", "isEqual", "(", "(", "(", "GetCred", ")", "usr", ".", "principal", ")", ".", "getCred", "(", ")", ",", "bytes", ")", ")", "{", "return", "null", ";", "}", "else", "{", "remove", "(", "usr", ")", ";", "usr", "=", "null", ";", "}", "}", "AAFCachedPrincipal", "cp", "=", "new", "AAFCachedPrincipal", "(", "this", ",", "con", ".", "app", ",", "user", ",", "bytes", ",", "con", ".", "cleanInterval", ")", ";", "// Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch", "// Statement", "switch", "(", "cp", ".", "revalidate", "(", ")", ")", "{", "case", "REVALIDATED", ":", "if", "(", "usr", "!=", "null", ")", "{", "usr", ".", "principal", "=", "cp", ";", "}", "else", "{", "addUser", "(", "new", "User", "<", "AAFPermission", ">", "(", "cp", ",", "con", ".", "timeout", ")", ")", ";", "}", "return", "null", ";", "case", "INACCESSIBLE", ":", "return", "\"AAF Inaccessible\"", ";", "case", "UNVALIDATED", ":", "return", "\"User/Pass combo invalid for \"", "+", "user", ";", "case", "DENIED", ":", "return", "\"AAF denies API for \"", "+", "user", ";", "default", ":", "return", "\"AAFAuthn doesn't handle Principal \"", "+", "user", ";", "}", "}" ]
Returns null if ok, or an Error String; @param user @param password @return @throws IOException @throws CadiException @throws Exception
[ "Returns", "null", "if", "ok", "or", "an", "Error", "String", ";" ]
train
https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/cadi/aaf/src/main/java/com/att/cadi/aaf/v2_0/AAFAuthn.java#L104-L142
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getDownloadUrlRequest
public BoxRequestsFile.DownloadFile getDownloadUrlRequest(File target, String url) throws IOException { """ Gets a request that downloads a given asset from the url to a target file This is used to download miscellaneous url assets for instance from the representations endpoint. @param target target file to download to, target can be either a directory or a file @param url url of the asset to download @return request to download a file to a target file @throws IOException throws FileNotFoundException if target file does not exist. """ if (!target.exists()){ throw new FileNotFoundException(); } BoxRequestsFile.DownloadFile request = new BoxRequestsFile.DownloadFile(target, url,mSession); return request; }
java
public BoxRequestsFile.DownloadFile getDownloadUrlRequest(File target, String url) throws IOException{ if (!target.exists()){ throw new FileNotFoundException(); } BoxRequestsFile.DownloadFile request = new BoxRequestsFile.DownloadFile(target, url,mSession); return request; }
[ "public", "BoxRequestsFile", ".", "DownloadFile", "getDownloadUrlRequest", "(", "File", "target", ",", "String", "url", ")", "throws", "IOException", "{", "if", "(", "!", "target", ".", "exists", "(", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", ")", ";", "}", "BoxRequestsFile", ".", "DownloadFile", "request", "=", "new", "BoxRequestsFile", ".", "DownloadFile", "(", "target", ",", "url", ",", "mSession", ")", ";", "return", "request", ";", "}" ]
Gets a request that downloads a given asset from the url to a target file This is used to download miscellaneous url assets for instance from the representations endpoint. @param target target file to download to, target can be either a directory or a file @param url url of the asset to download @return request to download a file to a target file @throws IOException throws FileNotFoundException if target file does not exist.
[ "Gets", "a", "request", "that", "downloads", "a", "given", "asset", "from", "the", "url", "to", "a", "target", "file", "This", "is", "used", "to", "download", "miscellaneous", "url", "assets", "for", "instance", "from", "the", "representations", "endpoint", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L383-L389
thombergs/docx-stamper
src/main/java/org/wickedsource/docxstamper/replace/PlaceholderReplacer.java
PlaceholderReplacer.resolveExpressions
public void resolveExpressions(final WordprocessingMLPackage document, ProxyBuilder<T> proxyBuilder) { """ Finds expressions in a document and resolves them against the specified context object. The expressions in the document are then replaced by the resolved values. @param document the document in which to replace all expressions. @param proxyBuilder builder for a proxy around the context root to customize its interface """ try { final T expressionContext = proxyBuilder.build(); CoordinatesWalker walker = new BaseCoordinatesWalker(document) { @Override protected void onParagraph(ParagraphCoordinates paragraphCoordinates) { resolveExpressionsForParagraph(paragraphCoordinates.getParagraph(), expressionContext, document); } }; walker.walk(); } catch (ProxyException e) { throw new DocxStamperException("could not create proxy around context root!", e); } }
java
public void resolveExpressions(final WordprocessingMLPackage document, ProxyBuilder<T> proxyBuilder) { try { final T expressionContext = proxyBuilder.build(); CoordinatesWalker walker = new BaseCoordinatesWalker(document) { @Override protected void onParagraph(ParagraphCoordinates paragraphCoordinates) { resolveExpressionsForParagraph(paragraphCoordinates.getParagraph(), expressionContext, document); } }; walker.walk(); } catch (ProxyException e) { throw new DocxStamperException("could not create proxy around context root!", e); } }
[ "public", "void", "resolveExpressions", "(", "final", "WordprocessingMLPackage", "document", ",", "ProxyBuilder", "<", "T", ">", "proxyBuilder", ")", "{", "try", "{", "final", "T", "expressionContext", "=", "proxyBuilder", ".", "build", "(", ")", ";", "CoordinatesWalker", "walker", "=", "new", "BaseCoordinatesWalker", "(", "document", ")", "{", "@", "Override", "protected", "void", "onParagraph", "(", "ParagraphCoordinates", "paragraphCoordinates", ")", "{", "resolveExpressionsForParagraph", "(", "paragraphCoordinates", ".", "getParagraph", "(", ")", ",", "expressionContext", ",", "document", ")", ";", "}", "}", ";", "walker", ".", "walk", "(", ")", ";", "}", "catch", "(", "ProxyException", "e", ")", "{", "throw", "new", "DocxStamperException", "(", "\"could not create proxy around context root!\"", ",", "e", ")", ";", "}", "}" ]
Finds expressions in a document and resolves them against the specified context object. The expressions in the document are then replaced by the resolved values. @param document the document in which to replace all expressions. @param proxyBuilder builder for a proxy around the context root to customize its interface
[ "Finds", "expressions", "in", "a", "document", "and", "resolves", "them", "against", "the", "specified", "context", "object", ".", "The", "expressions", "in", "the", "document", "are", "then", "replaced", "by", "the", "resolved", "values", "." ]
train
https://github.com/thombergs/docx-stamper/blob/f1a7e3e92a59abaffac299532fe49450c3b041eb/src/main/java/org/wickedsource/docxstamper/replace/PlaceholderReplacer.java#L75-L88
betfair/cougar
cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinEmitter.java
ZipkinEmitter.emitAnnotation
public void emitAnnotation(@Nonnull ZipkinData zipkinData, @Nonnull String s) { """ Emits a single annotation to Zipkin. @param zipkinData Zipkin request data @param s The annotation to emit """ long timestampMillis = clock.millis(); long timestampMicros = TimeUnit.MILLISECONDS.toMicros(timestampMillis); ZipkinAnnotationsStore store = prepareEmission(zipkinData, s).addAnnotation(timestampMicros, s); emitAnnotations(store); }
java
public void emitAnnotation(@Nonnull ZipkinData zipkinData, @Nonnull String s) { long timestampMillis = clock.millis(); long timestampMicros = TimeUnit.MILLISECONDS.toMicros(timestampMillis); ZipkinAnnotationsStore store = prepareEmission(zipkinData, s).addAnnotation(timestampMicros, s); emitAnnotations(store); }
[ "public", "void", "emitAnnotation", "(", "@", "Nonnull", "ZipkinData", "zipkinData", ",", "@", "Nonnull", "String", "s", ")", "{", "long", "timestampMillis", "=", "clock", ".", "millis", "(", ")", ";", "long", "timestampMicros", "=", "TimeUnit", ".", "MILLISECONDS", ".", "toMicros", "(", "timestampMillis", ")", ";", "ZipkinAnnotationsStore", "store", "=", "prepareEmission", "(", "zipkinData", ",", "s", ")", ".", "addAnnotation", "(", "timestampMicros", ",", "s", ")", ";", "emitAnnotations", "(", "store", ")", ";", "}" ]
Emits a single annotation to Zipkin. @param zipkinData Zipkin request data @param s The annotation to emit
[ "Emits", "a", "single", "annotation", "to", "Zipkin", "." ]
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinEmitter.java#L163-L169
zandero/rest.vertx
src/main/java/com/zandero/rest/data/ArgumentProvider.java
ArgumentProvider.removeMatrixFromPath
private static String removeMatrixFromPath(String path, RouteDefinition definition) { """ Removes matrix params from path @param path to clean up @param definition to check if matrix params are present @return cleaned up path """ // simple removal ... we don't care what matrix attributes were given if (definition.hasMatrixParams()) { int index = path.indexOf(";"); if (index > 0) { return path.substring(0, index); } } return path; }
java
private static String removeMatrixFromPath(String path, RouteDefinition definition) { // simple removal ... we don't care what matrix attributes were given if (definition.hasMatrixParams()) { int index = path.indexOf(";"); if (index > 0) { return path.substring(0, index); } } return path; }
[ "private", "static", "String", "removeMatrixFromPath", "(", "String", "path", ",", "RouteDefinition", "definition", ")", "{", "// simple removal ... we don't care what matrix attributes were given", "if", "(", "definition", ".", "hasMatrixParams", "(", ")", ")", "{", "int", "index", "=", "path", ".", "indexOf", "(", "\";\"", ")", ";", "if", "(", "index", ">", "0", ")", "{", "return", "path", ".", "substring", "(", "0", ",", "index", ")", ";", "}", "}", "return", "path", ";", "}" ]
Removes matrix params from path @param path to clean up @param definition to check if matrix params are present @return cleaned up path
[ "Removes", "matrix", "params", "from", "path" ]
train
https://github.com/zandero/rest.vertx/blob/ba458720cf59e076953eab9dac7227eeaf9e58ce/src/main/java/com/zandero/rest/data/ArgumentProvider.java#L268-L279
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.lookAtLH
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { """ Apply a "lookat" transformation to this matrix for a left-handed coordinate system, that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a lookat transformation without post-multiplying it, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. @see #lookAtLH(Vector3fc, Vector3fc, Vector3fc) @see #setLookAtLH(float, float, float, float, float, float, float, float, float) @param eyeX the x-coordinate of the eye/camera location @param eyeY the y-coordinate of the eye/camera location @param eyeZ the z-coordinate of the eye/camera location @param centerX the x-coordinate of the point to look at @param centerY the y-coordinate of the point to look at @param centerZ the z-coordinate of the point to look at @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @param dest will hold the result @return dest """ if ((properties & PROPERTY_IDENTITY) != 0) return dest.setLookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); else if ((properties & PROPERTY_PERSPECTIVE) != 0) return lookAtPerspectiveLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); return lookAtLHGeneric(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); }
java
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.setLookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); else if ((properties & PROPERTY_PERSPECTIVE) != 0) return lookAtPerspectiveLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); return lookAtLHGeneric(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); }
[ "public", "Matrix4f", "lookAtLH", "(", "float", "eyeX", ",", "float", "eyeY", ",", "float", "eyeZ", ",", "float", "centerX", ",", "float", "centerY", ",", "float", "centerZ", ",", "float", "upX", ",", "float", "upY", ",", "float", "upZ", ",", "Matrix4f", "dest", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "!=", "0", ")", "return", "dest", ".", "setLookAtLH", "(", "eyeX", ",", "eyeY", ",", "eyeZ", ",", "centerX", ",", "centerY", ",", "centerZ", ",", "upX", ",", "upY", ",", "upZ", ")", ";", "else", "if", "(", "(", "properties", "&", "PROPERTY_PERSPECTIVE", ")", "!=", "0", ")", "return", "lookAtPerspectiveLH", "(", "eyeX", ",", "eyeY", ",", "eyeZ", ",", "centerX", ",", "centerY", ",", "centerZ", ",", "upX", ",", "upY", ",", "upZ", ",", "dest", ")", ";", "return", "lookAtLHGeneric", "(", "eyeX", ",", "eyeY", ",", "eyeZ", ",", "centerX", ",", "centerY", ",", "centerZ", ",", "upX", ",", "upY", ",", "upZ", ",", "dest", ")", ";", "}" ]
Apply a "lookat" transformation to this matrix for a left-handed coordinate system, that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a lookat transformation without post-multiplying it, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. @see #lookAtLH(Vector3fc, Vector3fc, Vector3fc) @see #setLookAtLH(float, float, float, float, float, float, float, float, float) @param eyeX the x-coordinate of the eye/camera location @param eyeY the y-coordinate of the eye/camera location @param eyeZ the z-coordinate of the eye/camera location @param centerX the x-coordinate of the point to look at @param centerY the y-coordinate of the point to look at @param centerZ the z-coordinate of the point to look at @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @param dest will hold the result @return dest
[ "Apply", "a", "lookat", "transformation", "to", "this", "matrix", "for", "a", "left", "-", "handed", "coordinate", "system", "that", "aligns", "<code", ">", "+", "z<", "/", "code", ">", "with", "<code", ">", "center", "-", "eye<", "/", "code", ">", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "L<", "/", "code", ">", "the", "lookat", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "L<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "L", "*", "v<", "/", "code", ">", "the", "lookat", "transformation", "will", "be", "applied", "first!", "<p", ">", "In", "order", "to", "set", "the", "matrix", "to", "a", "lookat", "transformation", "without", "post", "-", "multiplying", "it", "use", "{", "@link", "#setLookAtLH", "(", "float", "float", "float", "float", "float", "float", "float", "float", "float", ")", "setLookAtLH", "()", "}", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L8972-L8980
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java
FuncExtFunction.setArg
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { """ Set an argument expression for a function. This method is called by the XPath compiler. @param arg non-null expression that represents the argument. @param argNum The argument number index. @throws WrongNumberArgsException If the argNum parameter is beyond what is specified for this function. """ m_argVec.addElement(arg); arg.exprSetParent(this); }
java
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { m_argVec.addElement(arg); arg.exprSetParent(this); }
[ "public", "void", "setArg", "(", "Expression", "arg", ",", "int", "argNum", ")", "throws", "WrongNumberArgsException", "{", "m_argVec", ".", "addElement", "(", "arg", ")", ";", "arg", ".", "exprSetParent", "(", "this", ")", ";", "}" ]
Set an argument expression for a function. This method is called by the XPath compiler. @param arg non-null expression that represents the argument. @param argNum The argument number index. @throws WrongNumberArgsException If the argNum parameter is beyond what is specified for this function.
[ "Set", "an", "argument", "expression", "for", "a", "function", ".", "This", "method", "is", "called", "by", "the", "XPath", "compiler", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java#L232-L237
Harium/keel
src/main/java/com/harium/keel/effect/ContrastCorrection.java
ContrastCorrection.setFactor
public void setFactor(int factor) { """ Set Contrast adjusting factor, [-127, 127]. @param factor Contrast factor. """ this.factor = factor = Math.max(-127, Math.min(127, factor)); if (factor > 1) { baseFilter.setInRed(new IntRange(factor, 255 - factor)); baseFilter.setInGreen(new IntRange(factor, 255 - factor)); baseFilter.setInBlue(new IntRange(factor, 255 - factor)); baseFilter.setInGray(new IntRange(factor, 255 - factor)); baseFilter.setOutRed(new IntRange(0, 255)); baseFilter.setOutGreen(new IntRange(0, 255)); baseFilter.setOutBlue(new IntRange(0, 255)); baseFilter.setOutGray(new IntRange(0, 255)); } else { baseFilter.setInRed(new IntRange(-factor, 255 + factor)); baseFilter.setInGreen(new IntRange(-factor, 255 + factor)); baseFilter.setInBlue(new IntRange(-factor, 255 + factor)); baseFilter.setInGray(new IntRange(-factor, 255 + factor)); baseFilter.setOutRed(new IntRange(0, 255)); baseFilter.setOutGreen(new IntRange(0, 255)); baseFilter.setOutBlue(new IntRange(0, 255)); baseFilter.setOutGray(new IntRange(0, 255)); } }
java
public void setFactor(int factor) { this.factor = factor = Math.max(-127, Math.min(127, factor)); if (factor > 1) { baseFilter.setInRed(new IntRange(factor, 255 - factor)); baseFilter.setInGreen(new IntRange(factor, 255 - factor)); baseFilter.setInBlue(new IntRange(factor, 255 - factor)); baseFilter.setInGray(new IntRange(factor, 255 - factor)); baseFilter.setOutRed(new IntRange(0, 255)); baseFilter.setOutGreen(new IntRange(0, 255)); baseFilter.setOutBlue(new IntRange(0, 255)); baseFilter.setOutGray(new IntRange(0, 255)); } else { baseFilter.setInRed(new IntRange(-factor, 255 + factor)); baseFilter.setInGreen(new IntRange(-factor, 255 + factor)); baseFilter.setInBlue(new IntRange(-factor, 255 + factor)); baseFilter.setInGray(new IntRange(-factor, 255 + factor)); baseFilter.setOutRed(new IntRange(0, 255)); baseFilter.setOutGreen(new IntRange(0, 255)); baseFilter.setOutBlue(new IntRange(0, 255)); baseFilter.setOutGray(new IntRange(0, 255)); } }
[ "public", "void", "setFactor", "(", "int", "factor", ")", "{", "this", ".", "factor", "=", "factor", "=", "Math", ".", "max", "(", "-", "127", ",", "Math", ".", "min", "(", "127", ",", "factor", ")", ")", ";", "if", "(", "factor", ">", "1", ")", "{", "baseFilter", ".", "setInRed", "(", "new", "IntRange", "(", "factor", ",", "255", "-", "factor", ")", ")", ";", "baseFilter", ".", "setInGreen", "(", "new", "IntRange", "(", "factor", ",", "255", "-", "factor", ")", ")", ";", "baseFilter", ".", "setInBlue", "(", "new", "IntRange", "(", "factor", ",", "255", "-", "factor", ")", ")", ";", "baseFilter", ".", "setInGray", "(", "new", "IntRange", "(", "factor", ",", "255", "-", "factor", ")", ")", ";", "baseFilter", ".", "setOutRed", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutGreen", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutBlue", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutGray", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "}", "else", "{", "baseFilter", ".", "setInRed", "(", "new", "IntRange", "(", "-", "factor", ",", "255", "+", "factor", ")", ")", ";", "baseFilter", ".", "setInGreen", "(", "new", "IntRange", "(", "-", "factor", ",", "255", "+", "factor", ")", ")", ";", "baseFilter", ".", "setInBlue", "(", "new", "IntRange", "(", "-", "factor", ",", "255", "+", "factor", ")", ")", ";", "baseFilter", ".", "setInGray", "(", "new", "IntRange", "(", "-", "factor", ",", "255", "+", "factor", ")", ")", ";", "baseFilter", ".", "setOutRed", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutGreen", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutBlue", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "baseFilter", ".", "setOutGray", "(", "new", "IntRange", "(", "0", ",", "255", ")", ")", ";", "}", "}" ]
Set Contrast adjusting factor, [-127, 127]. @param factor Contrast factor.
[ "Set", "Contrast", "adjusting", "factor", "[", "-", "127", "127", "]", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/effect/ContrastCorrection.java#L59-L83
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArrayList.java
CopyOnWriteArrayList.lastIndexOf
public int lastIndexOf(E object, int to) { """ Searches this list for {@code object} and returns the index of the last occurrence that is before {@code to}. @return the index or -1 if the object was not found. """ Object[] snapshot = elements; return lastIndexOf(object, snapshot, 0, to); }
java
public int lastIndexOf(E object, int to) { Object[] snapshot = elements; return lastIndexOf(object, snapshot, 0, to); }
[ "public", "int", "lastIndexOf", "(", "E", "object", ",", "int", "to", ")", "{", "Object", "[", "]", "snapshot", "=", "elements", ";", "return", "lastIndexOf", "(", "object", ",", "snapshot", ",", "0", ",", "to", ")", ";", "}" ]
Searches this list for {@code object} and returns the index of the last occurrence that is before {@code to}. @return the index or -1 if the object was not found.
[ "Searches", "this", "list", "for", "{", "@code", "object", "}", "and", "returns", "the", "index", "of", "the", "last", "occurrence", "that", "is", "before", "{", "@code", "to", "}", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArrayList.java#L182-L185
cdk/cdk
legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java
MassToFormulaTool.calculateMassT
private double calculateMassT(List<IIsotope> isoToCond_new, int[] value_In) { """ Calculate the mass total given the elements and their respective occurrences. @param elemToCond_new The IIsotope to calculate @param value_In Array matrix with occurrences @return The sum total """ double result = 0; for (int i = 0; i < isoToCond_new.size(); i++) { if (value_In[i] != 0) { result += isoToCond_new.get(i).getExactMass() * value_In[i]; } } return result; }
java
private double calculateMassT(List<IIsotope> isoToCond_new, int[] value_In) { double result = 0; for (int i = 0; i < isoToCond_new.size(); i++) { if (value_In[i] != 0) { result += isoToCond_new.get(i).getExactMass() * value_In[i]; } } return result; }
[ "private", "double", "calculateMassT", "(", "List", "<", "IIsotope", ">", "isoToCond_new", ",", "int", "[", "]", "value_In", ")", "{", "double", "result", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "isoToCond_new", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "value_In", "[", "i", "]", "!=", "0", ")", "{", "result", "+=", "isoToCond_new", ".", "get", "(", "i", ")", ".", "getExactMass", "(", ")", "*", "value_In", "[", "i", "]", ";", "}", "}", "return", "result", ";", "}" ]
Calculate the mass total given the elements and their respective occurrences. @param elemToCond_new The IIsotope to calculate @param value_In Array matrix with occurrences @return The sum total
[ "Calculate", "the", "mass", "total", "given", "the", "elements", "and", "their", "respective", "occurrences", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java#L528-L536
jimmoores/quandl4j
core/src/main/java/com/jimmoores/quandl/util/PrettyPrinter.java
PrettyPrinter.toPrettyPrintedString
public static String toPrettyPrintedString(final JSONObject jsonObject) { """ Pretty print a JSONObject as an indented piece of JSON code. Throws a QuandlRuntimeException if it can't render the JSONObject to a String. @param jsonObject the pre-parsed JSON object to pretty-print, not null @return a String representation of the object, probably multi-line. """ ArgumentChecker.notNull(jsonObject, "jsonObject"); try { return jsonObject.toString(JSON_INDENT) + LINE_SEPARATOR; } catch (JSONException ex) { s_logger.error("Problem converting JSONObject to String", ex); throw new QuandlRuntimeException("Problem converting JSONObject to String", ex); } }
java
public static String toPrettyPrintedString(final JSONObject jsonObject) { ArgumentChecker.notNull(jsonObject, "jsonObject"); try { return jsonObject.toString(JSON_INDENT) + LINE_SEPARATOR; } catch (JSONException ex) { s_logger.error("Problem converting JSONObject to String", ex); throw new QuandlRuntimeException("Problem converting JSONObject to String", ex); } }
[ "public", "static", "String", "toPrettyPrintedString", "(", "final", "JSONObject", "jsonObject", ")", "{", "ArgumentChecker", ".", "notNull", "(", "jsonObject", ",", "\"jsonObject\"", ")", ";", "try", "{", "return", "jsonObject", ".", "toString", "(", "JSON_INDENT", ")", "+", "LINE_SEPARATOR", ";", "}", "catch", "(", "JSONException", "ex", ")", "{", "s_logger", ".", "error", "(", "\"Problem converting JSONObject to String\"", ",", "ex", ")", ";", "throw", "new", "QuandlRuntimeException", "(", "\"Problem converting JSONObject to String\"", ",", "ex", ")", ";", "}", "}" ]
Pretty print a JSONObject as an indented piece of JSON code. Throws a QuandlRuntimeException if it can't render the JSONObject to a String. @param jsonObject the pre-parsed JSON object to pretty-print, not null @return a String representation of the object, probably multi-line.
[ "Pretty", "print", "a", "JSONObject", "as", "an", "indented", "piece", "of", "JSON", "code", ".", "Throws", "a", "QuandlRuntimeException", "if", "it", "can", "t", "render", "the", "JSONObject", "to", "a", "String", "." ]
train
https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/util/PrettyPrinter.java#L60-L68
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WButton.java
WButton.setPressed
protected void setPressed(final boolean pressed, final Request request) { """ Sets whether this button is pressed. You probably do not want to invoke this manually, it is called from {@link #handleRequest}. If the button is pressed its Action is queued so it is invoked after the entire request has been handled. @param pressed true for pressed, false for not pressed @param request the Request that is being responded to """ if (pressed && isDisabled()) { // Protect against client-side tampering of disabled/read-only fields. LOG.warn("A disabled button has been triggered. " + getText() + ". " + getId()); return; } if (pressed != isPressed()) { getOrCreateComponentModel().isPressed = pressed; } // If an action has been supplied then execute it, but only after // handle request has been performed on the entire component tree. if (pressed) { final Action action = getAction(); if (action == null) { // Reset focus only if the current Request is an Ajax request. if (AjaxHelper.isCurrentAjaxTrigger(this)) { // Need to run the "afterActionExecute" as late as possible. Runnable later = new Runnable() { @Override public void run() { focusMe(); } }; invokeLater(later); } } else { final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject()); Runnable later = new Runnable() { @Override public void run() { beforeActionExecute(request); action.execute(event); afterActionExecute(request); } }; invokeLater(later); } } }
java
protected void setPressed(final boolean pressed, final Request request) { if (pressed && isDisabled()) { // Protect against client-side tampering of disabled/read-only fields. LOG.warn("A disabled button has been triggered. " + getText() + ". " + getId()); return; } if (pressed != isPressed()) { getOrCreateComponentModel().isPressed = pressed; } // If an action has been supplied then execute it, but only after // handle request has been performed on the entire component tree. if (pressed) { final Action action = getAction(); if (action == null) { // Reset focus only if the current Request is an Ajax request. if (AjaxHelper.isCurrentAjaxTrigger(this)) { // Need to run the "afterActionExecute" as late as possible. Runnable later = new Runnable() { @Override public void run() { focusMe(); } }; invokeLater(later); } } else { final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject()); Runnable later = new Runnable() { @Override public void run() { beforeActionExecute(request); action.execute(event); afterActionExecute(request); } }; invokeLater(later); } } }
[ "protected", "void", "setPressed", "(", "final", "boolean", "pressed", ",", "final", "Request", "request", ")", "{", "if", "(", "pressed", "&&", "isDisabled", "(", ")", ")", "{", "// Protect against client-side tampering of disabled/read-only fields.", "LOG", ".", "warn", "(", "\"A disabled button has been triggered. \"", "+", "getText", "(", ")", "+", "\". \"", "+", "getId", "(", ")", ")", ";", "return", ";", "}", "if", "(", "pressed", "!=", "isPressed", "(", ")", ")", "{", "getOrCreateComponentModel", "(", ")", ".", "isPressed", "=", "pressed", ";", "}", "// If an action has been supplied then execute it, but only after", "// handle request has been performed on the entire component tree.", "if", "(", "pressed", ")", "{", "final", "Action", "action", "=", "getAction", "(", ")", ";", "if", "(", "action", "==", "null", ")", "{", "// Reset focus only if the current Request is an Ajax request.", "if", "(", "AjaxHelper", ".", "isCurrentAjaxTrigger", "(", "this", ")", ")", "{", "// Need to run the \"afterActionExecute\" as late as possible.", "Runnable", "later", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "focusMe", "(", ")", ";", "}", "}", ";", "invokeLater", "(", "later", ")", ";", "}", "}", "else", "{", "final", "ActionEvent", "event", "=", "new", "ActionEvent", "(", "this", ",", "getActionCommand", "(", ")", ",", "getActionObject", "(", ")", ")", ";", "Runnable", "later", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "beforeActionExecute", "(", "request", ")", ";", "action", ".", "execute", "(", "event", ")", ";", "afterActionExecute", "(", "request", ")", ";", "}", "}", ";", "invokeLater", "(", "later", ")", ";", "}", "}", "}" ]
Sets whether this button is pressed. You probably do not want to invoke this manually, it is called from {@link #handleRequest}. If the button is pressed its Action is queued so it is invoked after the entire request has been handled. @param pressed true for pressed, false for not pressed @param request the Request that is being responded to
[ "Sets", "whether", "this", "button", "is", "pressed", ".", "You", "probably", "do", "not", "want", "to", "invoke", "this", "manually", "it", "is", "called", "from", "{", "@link", "#handleRequest", "}", ".", "If", "the", "button", "is", "pressed", "its", "Action", "is", "queued", "so", "it", "is", "invoked", "after", "the", "entire", "request", "has", "been", "handled", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WButton.java#L194-L237
meertensinstituut/mtas
src/main/java/mtas/search/spans/MtasSpanRecurrenceSpans.java
MtasSpanRecurrenceSpans.expandWithIgnoreItem
private List<Match> expandWithIgnoreItem(int docId, Match match) { """ Expand with ignore item. @param docId the doc id @param match the match @return the list """ List<Match> list = new ArrayList<>(); try { Set<Integer> ignoreList = ignoreItem.getFullEndPositionList(docId, match.endPosition); if (ignoreList != null) { for (Integer endPosition : ignoreList) { list.add(new Match(match.startPosition, endPosition)); } } } catch (IOException e) { log.debug(e); } return list; }
java
private List<Match> expandWithIgnoreItem(int docId, Match match) { List<Match> list = new ArrayList<>(); try { Set<Integer> ignoreList = ignoreItem.getFullEndPositionList(docId, match.endPosition); if (ignoreList != null) { for (Integer endPosition : ignoreList) { list.add(new Match(match.startPosition, endPosition)); } } } catch (IOException e) { log.debug(e); } return list; }
[ "private", "List", "<", "Match", ">", "expandWithIgnoreItem", "(", "int", "docId", ",", "Match", "match", ")", "{", "List", "<", "Match", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "Set", "<", "Integer", ">", "ignoreList", "=", "ignoreItem", ".", "getFullEndPositionList", "(", "docId", ",", "match", ".", "endPosition", ")", ";", "if", "(", "ignoreList", "!=", "null", ")", "{", "for", "(", "Integer", "endPosition", ":", "ignoreList", ")", "{", "list", ".", "add", "(", "new", "Match", "(", "match", ".", "startPosition", ",", "endPosition", ")", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "debug", "(", "e", ")", ";", "}", "return", "list", ";", "}" ]
Expand with ignore item. @param docId the doc id @param match the match @return the list
[ "Expand", "with", "ignore", "item", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/search/spans/MtasSpanRecurrenceSpans.java#L353-L367
alibaba/java-dns-cache-manipulator
library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java
DnsCacheManipulator.getDnsCache
@Nullable public static DnsCacheEntry getDnsCache(String host) { """ Get dns cache. @return dns cache. return {@code null} if no entry for host or dns cache is expired. @throws DnsCacheManipulatorException Operation fail """ try { return InetAddressCacheUtil.getInetAddressCache(host); } catch (Exception e) { throw new DnsCacheManipulatorException("Fail to getDnsCache, cause: " + e.toString(), e); } }
java
@Nullable public static DnsCacheEntry getDnsCache(String host) { try { return InetAddressCacheUtil.getInetAddressCache(host); } catch (Exception e) { throw new DnsCacheManipulatorException("Fail to getDnsCache, cause: " + e.toString(), e); } }
[ "@", "Nullable", "public", "static", "DnsCacheEntry", "getDnsCache", "(", "String", "host", ")", "{", "try", "{", "return", "InetAddressCacheUtil", ".", "getInetAddressCache", "(", "host", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DnsCacheManipulatorException", "(", "\"Fail to getDnsCache, cause: \"", "+", "e", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "}" ]
Get dns cache. @return dns cache. return {@code null} if no entry for host or dns cache is expired. @throws DnsCacheManipulatorException Operation fail
[ "Get", "dns", "cache", "." ]
train
https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java#L133-L140
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/scheduler/SecondsBasedEntryTaskScheduler.java
SecondsBasedEntryTaskScheduler.cleanUpScheduledFuturesIfEmpty
private void cleanUpScheduledFuturesIfEmpty(Integer second, Map<Object, ScheduledEntry<K, V>> entries) { """ Cancels the scheduled future and removes the entries map for the given second If no entries are left <p/> Cleans up parent container (second -> entries map) if it doesn't hold anymore items this second. <p/> Cancels associated scheduler (second -> scheduler map ) if there are no more items to remove for this second. @param second second at which this entry was scheduled to be evicted @param entries entries which were already scheduled to be evicted for this second """ if (entries.isEmpty()) { scheduledEntries.remove(second); ScheduledFuture removedFeature = scheduledTaskMap.remove(second); if (removedFeature != null) { removedFeature.cancel(false); } } }
java
private void cleanUpScheduledFuturesIfEmpty(Integer second, Map<Object, ScheduledEntry<K, V>> entries) { if (entries.isEmpty()) { scheduledEntries.remove(second); ScheduledFuture removedFeature = scheduledTaskMap.remove(second); if (removedFeature != null) { removedFeature.cancel(false); } } }
[ "private", "void", "cleanUpScheduledFuturesIfEmpty", "(", "Integer", "second", ",", "Map", "<", "Object", ",", "ScheduledEntry", "<", "K", ",", "V", ">", ">", "entries", ")", "{", "if", "(", "entries", ".", "isEmpty", "(", ")", ")", "{", "scheduledEntries", ".", "remove", "(", "second", ")", ";", "ScheduledFuture", "removedFeature", "=", "scheduledTaskMap", ".", "remove", "(", "second", ")", ";", "if", "(", "removedFeature", "!=", "null", ")", "{", "removedFeature", ".", "cancel", "(", "false", ")", ";", "}", "}", "}" ]
Cancels the scheduled future and removes the entries map for the given second If no entries are left <p/> Cleans up parent container (second -> entries map) if it doesn't hold anymore items this second. <p/> Cancels associated scheduler (second -> scheduler map ) if there are no more items to remove for this second. @param second second at which this entry was scheduled to be evicted @param entries entries which were already scheduled to be evicted for this second
[ "Cancels", "the", "scheduled", "future", "and", "removes", "the", "entries", "map", "for", "the", "given", "second", "If", "no", "entries", "are", "left", "<p", "/", ">", "Cleans", "up", "parent", "container", "(", "second", "-", ">", "entries", "map", ")", "if", "it", "doesn", "t", "hold", "anymore", "items", "this", "second", ".", "<p", "/", ">", "Cancels", "associated", "scheduler", "(", "second", "-", ">", "scheduler", "map", ")", "if", "there", "are", "no", "more", "items", "to", "remove", "for", "this", "second", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/scheduler/SecondsBasedEntryTaskScheduler.java#L348-L357
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java
DomainsInner.createOrUpdateAsync
public Observable<DomainInner> createOrUpdateAsync(String resourceGroupName, String domainName, DomainInner domainInfo) { """ Create a domain. Asynchronously creates a new domain with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param domainInfo Domain information @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, domainName, domainInfo).map(new Func1<ServiceResponse<DomainInner>, DomainInner>() { @Override public DomainInner call(ServiceResponse<DomainInner> response) { return response.body(); } }); }
java
public Observable<DomainInner> createOrUpdateAsync(String resourceGroupName, String domainName, DomainInner domainInfo) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, domainName, domainInfo).map(new Func1<ServiceResponse<DomainInner>, DomainInner>() { @Override public DomainInner call(ServiceResponse<DomainInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DomainInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "domainName", ",", "DomainInner", "domainInfo", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "domainName", ",", "domainInfo", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DomainInner", ">", ",", "DomainInner", ">", "(", ")", "{", "@", "Override", "public", "DomainInner", "call", "(", "ServiceResponse", "<", "DomainInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create a domain. Asynchronously creates a new domain with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param domainInfo Domain information @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "a", "domain", ".", "Asynchronously", "creates", "a", "new", "domain", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java#L246-L253
knowm/XChange
xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java
WexAdapters.adaptTrade
public static Trade adaptTrade(WexTrade bTCETrade, CurrencyPair currencyPair) { """ Adapts a BTCETradeV3 to a Trade Object @param bTCETrade Wex trade object v.3 @param currencyPair the currency pair @return The XChange Trade """ OrderType orderType = bTCETrade.getTradeType().equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK; BigDecimal amount = bTCETrade.getAmount(); BigDecimal price = bTCETrade.getPrice(); Date date = DateUtils.fromMillisUtc(bTCETrade.getDate() * 1000L); final String tradeId = String.valueOf(bTCETrade.getTid()); return new Trade(orderType, amount, currencyPair, price, date, tradeId); }
java
public static Trade adaptTrade(WexTrade bTCETrade, CurrencyPair currencyPair) { OrderType orderType = bTCETrade.getTradeType().equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK; BigDecimal amount = bTCETrade.getAmount(); BigDecimal price = bTCETrade.getPrice(); Date date = DateUtils.fromMillisUtc(bTCETrade.getDate() * 1000L); final String tradeId = String.valueOf(bTCETrade.getTid()); return new Trade(orderType, amount, currencyPair, price, date, tradeId); }
[ "public", "static", "Trade", "adaptTrade", "(", "WexTrade", "bTCETrade", ",", "CurrencyPair", "currencyPair", ")", "{", "OrderType", "orderType", "=", "bTCETrade", ".", "getTradeType", "(", ")", ".", "equalsIgnoreCase", "(", "\"bid\"", ")", "?", "OrderType", ".", "BID", ":", "OrderType", ".", "ASK", ";", "BigDecimal", "amount", "=", "bTCETrade", ".", "getAmount", "(", ")", ";", "BigDecimal", "price", "=", "bTCETrade", ".", "getPrice", "(", ")", ";", "Date", "date", "=", "DateUtils", ".", "fromMillisUtc", "(", "bTCETrade", ".", "getDate", "(", ")", "*", "1000L", ")", ";", "final", "String", "tradeId", "=", "String", ".", "valueOf", "(", "bTCETrade", ".", "getTid", "(", ")", ")", ";", "return", "new", "Trade", "(", "orderType", ",", "amount", ",", "currencyPair", ",", "price", ",", "date", ",", "tradeId", ")", ";", "}" ]
Adapts a BTCETradeV3 to a Trade Object @param bTCETrade Wex trade object v.3 @param currencyPair the currency pair @return The XChange Trade
[ "Adapts", "a", "BTCETradeV3", "to", "a", "Trade", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java#L103-L113
gallandarakhneorg/afc
core/maths/mathstochastic/src/main/java/org/arakhne/afc/math/stochastic/MathFunctionRange.java
MathFunctionRange.createSet
@Pure public static MathFunctionRange[] createSet(double... values) { """ Create a set of bounds that correspond to the specified values. <p>The first value is the minimal value of the first bounds, the second value is the maximal value of the first bounds, the third value is the minimal value of the second bounds, the forth value is the maximal value of the second bounds, and so on. @param values are put in there own bounds object @return the set of bounds """ final MathFunctionRange[] bounds = new MathFunctionRange[values.length / 2]; for (int i = 0, j = 0; i < values.length; i += 2, ++j) { bounds[j] = new MathFunctionRange(values[i], values[i + 1]); } return bounds; }
java
@Pure public static MathFunctionRange[] createSet(double... values) { final MathFunctionRange[] bounds = new MathFunctionRange[values.length / 2]; for (int i = 0, j = 0; i < values.length; i += 2, ++j) { bounds[j] = new MathFunctionRange(values[i], values[i + 1]); } return bounds; }
[ "@", "Pure", "public", "static", "MathFunctionRange", "[", "]", "createSet", "(", "double", "...", "values", ")", "{", "final", "MathFunctionRange", "[", "]", "bounds", "=", "new", "MathFunctionRange", "[", "values", ".", "length", "/", "2", "]", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "+=", "2", ",", "++", "j", ")", "{", "bounds", "[", "j", "]", "=", "new", "MathFunctionRange", "(", "values", "[", "i", "]", ",", "values", "[", "i", "+", "1", "]", ")", ";", "}", "return", "bounds", ";", "}" ]
Create a set of bounds that correspond to the specified values. <p>The first value is the minimal value of the first bounds, the second value is the maximal value of the first bounds, the third value is the minimal value of the second bounds, the forth value is the maximal value of the second bounds, and so on. @param values are put in there own bounds object @return the set of bounds
[ "Create", "a", "set", "of", "bounds", "that", "correspond", "to", "the", "specified", "values", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathstochastic/src/main/java/org/arakhne/afc/math/stochastic/MathFunctionRange.java#L104-L111
diirt/util
src/main/java/org/epics/util/text/NumberFormats.java
NumberFormats.createFormatter
private static DecimalFormat createFormatter(int precision) { """ Creates a new number format that formats a number with the given number of precision digits. @param precision number of digits past the decimal point @return a number format """ if (precision < 0) throw new IllegalArgumentException("Precision must be non-negative"); if (precision == 0) return new DecimalFormat("0", symbols); StringBuilder sb = new StringBuilder("0."); for (int i = 0; i < precision; i++) { sb.append("0"); } return new DecimalFormat(sb.toString(), symbols); }
java
private static DecimalFormat createFormatter(int precision) { if (precision < 0) throw new IllegalArgumentException("Precision must be non-negative"); if (precision == 0) return new DecimalFormat("0", symbols); StringBuilder sb = new StringBuilder("0."); for (int i = 0; i < precision; i++) { sb.append("0"); } return new DecimalFormat(sb.toString(), symbols); }
[ "private", "static", "DecimalFormat", "createFormatter", "(", "int", "precision", ")", "{", "if", "(", "precision", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Precision must be non-negative\"", ")", ";", "if", "(", "precision", "==", "0", ")", "return", "new", "DecimalFormat", "(", "\"0\"", ",", "symbols", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"0.\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "precision", ";", "i", "++", ")", "{", "sb", ".", "append", "(", "\"0\"", ")", ";", "}", "return", "new", "DecimalFormat", "(", "sb", ".", "toString", "(", ")", ",", "symbols", ")", ";", "}" ]
Creates a new number format that formats a number with the given number of precision digits. @param precision number of digits past the decimal point @return a number format
[ "Creates", "a", "new", "number", "format", "that", "formats", "a", "number", "with", "the", "given", "number", "of", "precision", "digits", "." ]
train
https://github.com/diirt/util/blob/24aca0a173a635aaf0b78d213a3fee8d4f91c077/src/main/java/org/epics/util/text/NumberFormats.java#L93-L105
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/util/ZaurusChoice.java
ZaurusChoice.add
public void add(String item, String value) { """ restrict strings for the choice to MaxLenInZChoice characters """ int maxChar = MaxLenInZChoice; if (item.length() < MaxLenInZChoice) { maxChar = item.length(); } super.add(item.substring(0, maxChar)); values.addElement(value); }
java
public void add(String item, String value) { int maxChar = MaxLenInZChoice; if (item.length() < MaxLenInZChoice) { maxChar = item.length(); } super.add(item.substring(0, maxChar)); values.addElement(value); }
[ "public", "void", "add", "(", "String", "item", ",", "String", "value", ")", "{", "int", "maxChar", "=", "MaxLenInZChoice", ";", "if", "(", "item", ".", "length", "(", ")", "<", "MaxLenInZChoice", ")", "{", "maxChar", "=", "item", ".", "length", "(", ")", ";", "}", "super", ".", "add", "(", "item", ".", "substring", "(", "0", ",", "maxChar", ")", ")", ";", "values", ".", "addElement", "(", "value", ")", ";", "}" ]
restrict strings for the choice to MaxLenInZChoice characters
[ "restrict", "strings", "for", "the", "choice", "to", "MaxLenInZChoice", "characters" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/util/ZaurusChoice.java#L68-L78
google/closure-compiler
src/com/google/javascript/jscomp/ReplaceMessages.java
ReplaceMessages.updateFunctionNode
private void updateFunctionNode(JsMessage message, Node functionNode) throws MalformedException { """ Updates the descendants of a FUNCTION node to represent a message's value. <p> The tree looks something like: <pre> function |-- name |-- lp | |-- name <arg1> | -- name <arg2> -- block | --return | --add |-- string foo -- name <arg1> </pre> @param message a message @param functionNode the message's original FUNCTION value node @throws MalformedException if the passed node's subtree structure is not as expected """ checkNode(functionNode, Token.FUNCTION); Node nameNode = functionNode.getFirstChild(); checkNode(nameNode, Token.NAME); Node argListNode = nameNode.getNext(); checkNode(argListNode, Token.PARAM_LIST); Node oldBlockNode = argListNode.getNext(); checkNode(oldBlockNode, Token.BLOCK); Iterator<CharSequence> iterator = message.parts().iterator(); Node valueNode = constructAddOrStringNode(iterator, argListNode); Node newBlockNode = IR.block(IR.returnNode(valueNode)); if (!newBlockNode.isEquivalentTo( oldBlockNode, /* compareType= */ false, /* recurse= */ true, /* jsDoc= */ false, /* sideEffect= */ false)) { newBlockNode.useSourceInfoIfMissingFromForTree(oldBlockNode); functionNode.replaceChild(oldBlockNode, newBlockNode); compiler.reportChangeToEnclosingScope(newBlockNode); } }
java
private void updateFunctionNode(JsMessage message, Node functionNode) throws MalformedException { checkNode(functionNode, Token.FUNCTION); Node nameNode = functionNode.getFirstChild(); checkNode(nameNode, Token.NAME); Node argListNode = nameNode.getNext(); checkNode(argListNode, Token.PARAM_LIST); Node oldBlockNode = argListNode.getNext(); checkNode(oldBlockNode, Token.BLOCK); Iterator<CharSequence> iterator = message.parts().iterator(); Node valueNode = constructAddOrStringNode(iterator, argListNode); Node newBlockNode = IR.block(IR.returnNode(valueNode)); if (!newBlockNode.isEquivalentTo( oldBlockNode, /* compareType= */ false, /* recurse= */ true, /* jsDoc= */ false, /* sideEffect= */ false)) { newBlockNode.useSourceInfoIfMissingFromForTree(oldBlockNode); functionNode.replaceChild(oldBlockNode, newBlockNode); compiler.reportChangeToEnclosingScope(newBlockNode); } }
[ "private", "void", "updateFunctionNode", "(", "JsMessage", "message", ",", "Node", "functionNode", ")", "throws", "MalformedException", "{", "checkNode", "(", "functionNode", ",", "Token", ".", "FUNCTION", ")", ";", "Node", "nameNode", "=", "functionNode", ".", "getFirstChild", "(", ")", ";", "checkNode", "(", "nameNode", ",", "Token", ".", "NAME", ")", ";", "Node", "argListNode", "=", "nameNode", ".", "getNext", "(", ")", ";", "checkNode", "(", "argListNode", ",", "Token", ".", "PARAM_LIST", ")", ";", "Node", "oldBlockNode", "=", "argListNode", ".", "getNext", "(", ")", ";", "checkNode", "(", "oldBlockNode", ",", "Token", ".", "BLOCK", ")", ";", "Iterator", "<", "CharSequence", ">", "iterator", "=", "message", ".", "parts", "(", ")", ".", "iterator", "(", ")", ";", "Node", "valueNode", "=", "constructAddOrStringNode", "(", "iterator", ",", "argListNode", ")", ";", "Node", "newBlockNode", "=", "IR", ".", "block", "(", "IR", ".", "returnNode", "(", "valueNode", ")", ")", ";", "if", "(", "!", "newBlockNode", ".", "isEquivalentTo", "(", "oldBlockNode", ",", "/* compareType= */", "false", ",", "/* recurse= */", "true", ",", "/* jsDoc= */", "false", ",", "/* sideEffect= */", "false", ")", ")", "{", "newBlockNode", ".", "useSourceInfoIfMissingFromForTree", "(", "oldBlockNode", ")", ";", "functionNode", ".", "replaceChild", "(", "oldBlockNode", ",", "newBlockNode", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "newBlockNode", ")", ";", "}", "}" ]
Updates the descendants of a FUNCTION node to represent a message's value. <p> The tree looks something like: <pre> function |-- name |-- lp | |-- name <arg1> | -- name <arg2> -- block | --return | --add |-- string foo -- name <arg1> </pre> @param message a message @param functionNode the message's original FUNCTION value node @throws MalformedException if the passed node's subtree structure is not as expected
[ "Updates", "the", "descendants", "of", "a", "FUNCTION", "node", "to", "represent", "a", "message", "s", "value", ".", "<p", ">", "The", "tree", "looks", "something", "like", ":", "<pre", ">", "function", "|", "--", "name", "|", "--", "lp", "|", "|", "--", "name", "<arg1", ">", "|", "--", "name", "<arg2", ">", "--", "block", "|", "--", "return", "|", "--", "add", "|", "--", "string", "foo", "--", "name", "<arg1", ">", "<", "/", "pre", ">" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ReplaceMessages.java#L172-L196
casmi/casmi
src/main/java/casmi/graphics/element/Polygon.java
Polygon.setCornerColor
public void setCornerColor(int index, Color color) { """ Sets the color of a corner. @param index The index number of a corner. @param color The color of a corner. """ if (cornerColor == null) { for (int i = 0; i < cornerX.size(); i++) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } setGradation(true); } if (cornerColor.size() < cornerX.size()) { while (cornerColor.size() != cornerX.size()) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } } cornerColor.set(index, color); }
java
public void setCornerColor(int index, Color color) { if (cornerColor == null) { for (int i = 0; i < cornerX.size(); i++) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } setGradation(true); } if (cornerColor.size() < cornerX.size()) { while (cornerColor.size() != cornerX.size()) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } } cornerColor.set(index, color); }
[ "public", "void", "setCornerColor", "(", "int", "index", ",", "Color", "color", ")", "{", "if", "(", "cornerColor", "==", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cornerX", ".", "size", "(", ")", ";", "i", "++", ")", "{", "cornerColor", ".", "add", "(", "new", "RGBColor", "(", "this", ".", "fillColor", ".", "getRed", "(", ")", ",", "this", ".", "fillColor", ".", "getGreen", "(", ")", ",", "this", ".", "fillColor", ".", "getBlue", "(", ")", ",", "this", ".", "fillColor", ".", "getAlpha", "(", ")", ")", ")", ";", "}", "setGradation", "(", "true", ")", ";", "}", "if", "(", "cornerColor", ".", "size", "(", ")", "<", "cornerX", ".", "size", "(", ")", ")", "{", "while", "(", "cornerColor", ".", "size", "(", ")", "!=", "cornerX", ".", "size", "(", ")", ")", "{", "cornerColor", ".", "add", "(", "new", "RGBColor", "(", "this", ".", "fillColor", ".", "getRed", "(", ")", ",", "this", ".", "fillColor", ".", "getGreen", "(", ")", ",", "this", ".", "fillColor", ".", "getBlue", "(", ")", ",", "this", ".", "fillColor", ".", "getAlpha", "(", ")", ")", ")", ";", "}", "}", "cornerColor", ".", "set", "(", "index", ",", "color", ")", ";", "}" ]
Sets the color of a corner. @param index The index number of a corner. @param color The color of a corner.
[ "Sets", "the", "color", "of", "a", "corner", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Polygon.java#L286-L301
autermann/yaml
src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java
YamlMappingNode.put
public T put(YamlNode key, BigInteger value) { """ Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this} """ return put(key, getNodeFactory().bigIntegerNode(value)); }
java
public T put(YamlNode key, BigInteger value) { return put(key, getNodeFactory().bigIntegerNode(value)); }
[ "public", "T", "put", "(", "YamlNode", "key", ",", "BigInteger", "value", ")", "{", "return", "put", "(", "key", ",", "getNodeFactory", "(", ")", ".", "bigIntegerNode", "(", "value", ")", ")", ";", "}" ]
Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this}
[ "Adds", "the", "specified", "{", "@code", "key", "}", "/", "{", "@code", "value", "}", "pair", "to", "this", "mapping", "." ]
train
https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L588-L590
bazaarvoice/jersey-hmac-auth
client/src/main/java/com/bazaarvoice/auth/hmac/client/RequestEncoder.java
RequestEncoder.getSerializedEntity
private byte[] getSerializedEntity(ClientRequest request) { """ Get the serialized representation of the request entity. This is used when generating the client signature, because this is the representation that the server will receive and use when it generates the server-side signature to compare to the client-side signature. @see com.sun.jersey.client.urlconnection.URLConnectionClientHandler """ final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // By using the RequestWriter parent class, we match the behavior of entity writing from // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler. writeRequestEntity(request, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) throws IOException { } public OutputStream onGetOutputStream() throws IOException { return outputStream; } }); } catch (IOException e) { throw new ClientHandlerException("Unable to serialize request entity", e); } return outputStream.toByteArray(); }
java
private byte[] getSerializedEntity(ClientRequest request) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // By using the RequestWriter parent class, we match the behavior of entity writing from // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler. writeRequestEntity(request, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) throws IOException { } public OutputStream onGetOutputStream() throws IOException { return outputStream; } }); } catch (IOException e) { throw new ClientHandlerException("Unable to serialize request entity", e); } return outputStream.toByteArray(); }
[ "private", "byte", "[", "]", "getSerializedEntity", "(", "ClientRequest", "request", ")", "{", "final", "ByteArrayOutputStream", "outputStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "// By using the RequestWriter parent class, we match the behavior of entity writing from", "// for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler.", "writeRequestEntity", "(", "request", ",", "new", "RequestEntityWriterListener", "(", ")", "{", "public", "void", "onRequestEntitySize", "(", "long", "size", ")", "throws", "IOException", "{", "}", "public", "OutputStream", "onGetOutputStream", "(", ")", "throws", "IOException", "{", "return", "outputStream", ";", "}", "}", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ClientHandlerException", "(", "\"Unable to serialize request entity\"", ",", "e", ")", ";", "}", "return", "outputStream", ".", "toByteArray", "(", ")", ";", "}" ]
Get the serialized representation of the request entity. This is used when generating the client signature, because this is the representation that the server will receive and use when it generates the server-side signature to compare to the client-side signature. @see com.sun.jersey.client.urlconnection.URLConnectionClientHandler
[ "Get", "the", "serialized", "representation", "of", "the", "request", "entity", ".", "This", "is", "used", "when", "generating", "the", "client", "signature", "because", "this", "is", "the", "representation", "that", "the", "server", "will", "receive", "and", "use", "when", "it", "generates", "the", "server", "-", "side", "signature", "to", "compare", "to", "the", "client", "-", "side", "signature", "." ]
train
https://github.com/bazaarvoice/jersey-hmac-auth/blob/17e2a40a4b7b783de4d77ad97f8a623af6baf688/client/src/main/java/com/bazaarvoice/auth/hmac/client/RequestEncoder.java#L98-L118
landawn/AbacusUtil
src/com/landawn/abacus/dataSource/PoolableConnection.java
PoolableConnection.prepareStatement
@Override public PoolablePreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { """ Method prepareStatement. @param sql @param resultSetType @param resultSetConcurrency @return PreparedStatement @throws SQLException @see java.sql.Connection#prepareStatement(String, int, int) """ return prepareStatement(sql, -1, resultSetType, resultSetConcurrency, -1); }
java
@Override public PoolablePreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, -1, resultSetType, resultSetConcurrency, -1); }
[ "@", "Override", "public", "PoolablePreparedStatement", "prepareStatement", "(", "String", "sql", ",", "int", "resultSetType", ",", "int", "resultSetConcurrency", ")", "throws", "SQLException", "{", "return", "prepareStatement", "(", "sql", ",", "-", "1", ",", "resultSetType", ",", "resultSetConcurrency", ",", "-", "1", ")", ";", "}" ]
Method prepareStatement. @param sql @param resultSetType @param resultSetConcurrency @return PreparedStatement @throws SQLException @see java.sql.Connection#prepareStatement(String, int, int)
[ "Method", "prepareStatement", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/dataSource/PoolableConnection.java#L551-L554
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/Popups.java
Popups.newPopup
public static PopupPanel newPopup (String styleName, Widget contents) { """ Creates and returns a new popup with the specified style name and contents. """ PopupPanel panel = new PopupPanel(); panel.setStyleName(styleName); panel.setWidget(contents); return panel; }
java
public static PopupPanel newPopup (String styleName, Widget contents) { PopupPanel panel = new PopupPanel(); panel.setStyleName(styleName); panel.setWidget(contents); return panel; }
[ "public", "static", "PopupPanel", "newPopup", "(", "String", "styleName", ",", "Widget", "contents", ")", "{", "PopupPanel", "panel", "=", "new", "PopupPanel", "(", ")", ";", "panel", ".", "setStyleName", "(", "styleName", ")", ";", "panel", ".", "setWidget", "(", "contents", ")", ";", "return", "panel", ";", "}" ]
Creates and returns a new popup with the specified style name and contents.
[ "Creates", "and", "returns", "a", "new", "popup", "with", "the", "specified", "style", "name", "and", "contents", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Popups.java#L269-L275
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java
JournalCreator.addDatastream
public String addDatastream(Context context, String pid, String dsID, String[] altIDs, String dsLabel, boolean versionable, String MIMEType, String formatURI, String location, String controlGroup, String dsState, String checksumType, String checksum, String logMessage) throws ServerException { """ Create a journal entry, add the arguments, and invoke the method. """ try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_ADD_DATASTREAM, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_VERSIONABLE, versionable); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, MIMEType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_LOCATION, location); cje.addArgument(ARGUMENT_NAME_CONTROL_GROUP, controlGroup); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (String) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
java
public String addDatastream(Context context, String pid, String dsID, String[] altIDs, String dsLabel, boolean versionable, String MIMEType, String formatURI, String location, String controlGroup, String dsState, String checksumType, String checksum, String logMessage) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_ADD_DATASTREAM, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_VERSIONABLE, versionable); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, MIMEType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_LOCATION, location); cje.addArgument(ARGUMENT_NAME_CONTROL_GROUP, controlGroup); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (String) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
[ "public", "String", "addDatastream", "(", "Context", "context", ",", "String", "pid", ",", "String", "dsID", ",", "String", "[", "]", "altIDs", ",", "String", "dsLabel", ",", "boolean", "versionable", ",", "String", "MIMEType", ",", "String", "formatURI", ",", "String", "location", ",", "String", "controlGroup", ",", "String", "dsState", ",", "String", "checksumType", ",", "String", "checksum", ",", "String", "logMessage", ")", "throws", "ServerException", "{", "try", "{", "CreatorJournalEntry", "cje", "=", "new", "CreatorJournalEntry", "(", "METHOD_ADD_DATASTREAM", ",", "context", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_PID", ",", "pid", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_DS_ID", ",", "dsID", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_ALT_IDS", ",", "altIDs", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_DS_LABEL", ",", "dsLabel", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_VERSIONABLE", ",", "versionable", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_MIME_TYPE", ",", "MIMEType", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_FORMAT_URI", ",", "formatURI", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_LOCATION", ",", "location", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_CONTROL_GROUP", ",", "controlGroup", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_DS_STATE", ",", "dsState", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_CHECKSUM_TYPE", ",", "checksumType", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_CHECKSUM", ",", "checksum", ")", ";", "cje", ".", "addArgument", "(", "ARGUMENT_NAME_LOG_MESSAGE", ",", "logMessage", ")", ";", "return", "(", "String", ")", "cje", ".", "invokeAndClose", "(", "delegate", ",", "writer", ")", ";", "}", "catch", "(", "JournalException", "e", ")", "{", "throw", "new", "GeneralException", "(", "\"Problem creating the Journal\"", ",", "e", ")", ";", "}", "}" ]
Create a journal entry, add the arguments, and invoke the method.
[ "Create", "a", "journal", "entry", "add", "the", "arguments", "and", "invoke", "the", "method", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java#L165-L199
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/util/ChartModelProvider.java
ChartModelProvider.addMarkerLine
private static void addMarkerLine(String label, Double value, Double offset, Axis axis) { """ Creates a marker line into specified axis if value is not null. @param label line label @param value value @param offset value offset @param axis axis """ if (value != null) { MarkerLine markerLine = MarkerLineImpl.create(axis, NumberDataElementImpl.create(value + (offset != null ? offset : 0d))); markerLine.getLineAttributes().setStyle(LineStyle.DASHED_LITERAL); markerLine.getLabel().getCaption().setValue(label); markerLine.setLabelAnchor(Anchor.NORTH_EAST_LITERAL); } }
java
private static void addMarkerLine(String label, Double value, Double offset, Axis axis) { if (value != null) { MarkerLine markerLine = MarkerLineImpl.create(axis, NumberDataElementImpl.create(value + (offset != null ? offset : 0d))); markerLine.getLineAttributes().setStyle(LineStyle.DASHED_LITERAL); markerLine.getLabel().getCaption().setValue(label); markerLine.setLabelAnchor(Anchor.NORTH_EAST_LITERAL); } }
[ "private", "static", "void", "addMarkerLine", "(", "String", "label", ",", "Double", "value", ",", "Double", "offset", ",", "Axis", "axis", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "MarkerLine", "markerLine", "=", "MarkerLineImpl", ".", "create", "(", "axis", ",", "NumberDataElementImpl", ".", "create", "(", "value", "+", "(", "offset", "!=", "null", "?", "offset", ":", "0d", ")", ")", ")", ";", "markerLine", ".", "getLineAttributes", "(", ")", ".", "setStyle", "(", "LineStyle", ".", "DASHED_LITERAL", ")", ";", "markerLine", ".", "getLabel", "(", ")", ".", "getCaption", "(", ")", ".", "setValue", "(", "label", ")", ";", "markerLine", ".", "setLabelAnchor", "(", "Anchor", ".", "NORTH_EAST_LITERAL", ")", ";", "}", "}" ]
Creates a marker line into specified axis if value is not null. @param label line label @param value value @param offset value offset @param axis axis
[ "Creates", "a", "marker", "line", "into", "specified", "axis", "if", "value", "is", "not", "null", "." ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/util/ChartModelProvider.java#L763-L770
hankcs/HanLP
src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java
MDAG.createMDAGNode
private void createMDAGNode(SimpleMDAGNode current, int fromIndex, MDAGNode[] toNodeArray, MDAGNode[] fromNodeArray) { """ 递归创建节点<br> @param current 当前简易节点 @param fromIndex 起点下标 @param toNodeArray 终点数组 @param fromNodeArray 起点数组,它们两个按照下标一一对应 """ MDAGNode from = (fromIndex == -1 ? sourceNode : toNodeArray[fromIndex]); int transitionSetBegin = current.getTransitionSetBeginIndex(); int onePastTransitionSetEnd = transitionSetBegin + current.getOutgoingTransitionSetSize(); for (int i = transitionSetBegin; i < onePastTransitionSetEnd; i++) { SimpleMDAGNode targetNode = mdagDataArray[i]; if (toNodeArray[i] != null) { fromNodeArray[fromIndex].addOutgoingTransition(current.getLetter(), fromNodeArray[i]); toNodeArray[fromIndex] = fromNodeArray[i]; continue; } toNodeArray[i] = from.addOutgoingTransition(targetNode.getLetter(), targetNode.isAcceptNode()); fromNodeArray[i] = from; createMDAGNode(targetNode, i, toNodeArray, fromNodeArray); } }
java
private void createMDAGNode(SimpleMDAGNode current, int fromIndex, MDAGNode[] toNodeArray, MDAGNode[] fromNodeArray) { MDAGNode from = (fromIndex == -1 ? sourceNode : toNodeArray[fromIndex]); int transitionSetBegin = current.getTransitionSetBeginIndex(); int onePastTransitionSetEnd = transitionSetBegin + current.getOutgoingTransitionSetSize(); for (int i = transitionSetBegin; i < onePastTransitionSetEnd; i++) { SimpleMDAGNode targetNode = mdagDataArray[i]; if (toNodeArray[i] != null) { fromNodeArray[fromIndex].addOutgoingTransition(current.getLetter(), fromNodeArray[i]); toNodeArray[fromIndex] = fromNodeArray[i]; continue; } toNodeArray[i] = from.addOutgoingTransition(targetNode.getLetter(), targetNode.isAcceptNode()); fromNodeArray[i] = from; createMDAGNode(targetNode, i, toNodeArray, fromNodeArray); } }
[ "private", "void", "createMDAGNode", "(", "SimpleMDAGNode", "current", ",", "int", "fromIndex", ",", "MDAGNode", "[", "]", "toNodeArray", ",", "MDAGNode", "[", "]", "fromNodeArray", ")", "{", "MDAGNode", "from", "=", "(", "fromIndex", "==", "-", "1", "?", "sourceNode", ":", "toNodeArray", "[", "fromIndex", "]", ")", ";", "int", "transitionSetBegin", "=", "current", ".", "getTransitionSetBeginIndex", "(", ")", ";", "int", "onePastTransitionSetEnd", "=", "transitionSetBegin", "+", "current", ".", "getOutgoingTransitionSetSize", "(", ")", ";", "for", "(", "int", "i", "=", "transitionSetBegin", ";", "i", "<", "onePastTransitionSetEnd", ";", "i", "++", ")", "{", "SimpleMDAGNode", "targetNode", "=", "mdagDataArray", "[", "i", "]", ";", "if", "(", "toNodeArray", "[", "i", "]", "!=", "null", ")", "{", "fromNodeArray", "[", "fromIndex", "]", ".", "addOutgoingTransition", "(", "current", ".", "getLetter", "(", ")", ",", "fromNodeArray", "[", "i", "]", ")", ";", "toNodeArray", "[", "fromIndex", "]", "=", "fromNodeArray", "[", "i", "]", ";", "continue", ";", "}", "toNodeArray", "[", "i", "]", "=", "from", ".", "addOutgoingTransition", "(", "targetNode", ".", "getLetter", "(", ")", ",", "targetNode", ".", "isAcceptNode", "(", ")", ")", ";", "fromNodeArray", "[", "i", "]", "=", "from", ";", "createMDAGNode", "(", "targetNode", ",", "i", ",", "toNodeArray", ",", "fromNodeArray", ")", ";", "}", "}" ]
递归创建节点<br> @param current 当前简易节点 @param fromIndex 起点下标 @param toNodeArray 终点数组 @param fromNodeArray 起点数组,它们两个按照下标一一对应
[ "递归创建节点<br", ">" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java#L804-L823
caelum/vraptor4
vraptor-core/src/main/java/br/com/caelum/vraptor/http/route/DefaultRouteBuilder.java
DefaultRouteBuilder.getRouteStrategy
protected Route getRouteStrategy(ControllerMethod controllerMethod, Parameter[] parameterNames) { """ Override this method to change the default Route implementation @param controllerMethod The ControllerMethod @param parameterNames parameters of the method @return Route representation """ return new FixedMethodStrategy(originalUri, controllerMethod, this.supportedMethods, builder.build(), priority, parameterNames); }
java
protected Route getRouteStrategy(ControllerMethod controllerMethod, Parameter[] parameterNames) { return new FixedMethodStrategy(originalUri, controllerMethod, this.supportedMethods, builder.build(), priority, parameterNames); }
[ "protected", "Route", "getRouteStrategy", "(", "ControllerMethod", "controllerMethod", ",", "Parameter", "[", "]", "parameterNames", ")", "{", "return", "new", "FixedMethodStrategy", "(", "originalUri", ",", "controllerMethod", ",", "this", ".", "supportedMethods", ",", "builder", ".", "build", "(", ")", ",", "priority", ",", "parameterNames", ")", ";", "}" ]
Override this method to change the default Route implementation @param controllerMethod The ControllerMethod @param parameterNames parameters of the method @return Route representation
[ "Override", "this", "method", "to", "change", "the", "default", "Route", "implementation" ]
train
https://github.com/caelum/vraptor4/blob/593ce9ad60f9d38c360881b2132417c56b8cc093/vraptor-core/src/main/java/br/com/caelum/vraptor/http/route/DefaultRouteBuilder.java#L200-L202
opengeospatial/teamengine
teamengine-core/src/main/java/com/occamlab/te/util/ZipUtils.java
ZipUtils.zipDir
public static void zipDir( File zipFile, File directoryToZip ) throws Exception { """ Zips the directory and all of it's sub directories @param zipFile the file to write the files into, never <code>null</code> @param directoryToZip the directory to zip, never <code>null</code> @throws Exception if the zip file could not be created @throws IllegalArgumentException if the directoryToZip is not a directory """ if ( !directoryToZip.isDirectory() ) { throw new IllegalArgumentException( "Directory to zip is not a directory" ); } try { ZipOutputStream out = new ZipOutputStream( new FileOutputStream( zipFile ) ); File parentDir = new File( directoryToZip.toURI().resolve( ".." ) ); for ( File file : directoryToZip.listFiles() ) { zip( parentDir, file, out ); } out.flush(); out.close(); } catch ( IOException e ) { throw new Exception( e.getMessage() ); } }
java
public static void zipDir( File zipFile, File directoryToZip ) throws Exception { if ( !directoryToZip.isDirectory() ) { throw new IllegalArgumentException( "Directory to zip is not a directory" ); } try { ZipOutputStream out = new ZipOutputStream( new FileOutputStream( zipFile ) ); File parentDir = new File( directoryToZip.toURI().resolve( ".." ) ); for ( File file : directoryToZip.listFiles() ) { zip( parentDir, file, out ); } out.flush(); out.close(); } catch ( IOException e ) { throw new Exception( e.getMessage() ); } }
[ "public", "static", "void", "zipDir", "(", "File", "zipFile", ",", "File", "directoryToZip", ")", "throws", "Exception", "{", "if", "(", "!", "directoryToZip", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Directory to zip is not a directory\"", ")", ";", "}", "try", "{", "ZipOutputStream", "out", "=", "new", "ZipOutputStream", "(", "new", "FileOutputStream", "(", "zipFile", ")", ")", ";", "File", "parentDir", "=", "new", "File", "(", "directoryToZip", ".", "toURI", "(", ")", ".", "resolve", "(", "\"..\"", ")", ")", ";", "for", "(", "File", "file", ":", "directoryToZip", ".", "listFiles", "(", ")", ")", "{", "zip", "(", "parentDir", ",", "file", ",", "out", ")", ";", "}", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "Exception", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Zips the directory and all of it's sub directories @param zipFile the file to write the files into, never <code>null</code> @param directoryToZip the directory to zip, never <code>null</code> @throws Exception if the zip file could not be created @throws IllegalArgumentException if the directoryToZip is not a directory
[ "Zips", "the", "directory", "and", "all", "of", "it", "s", "sub", "directories" ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/ZipUtils.java#L24-L41
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java
UriReader.readString
public String readString(URI uri, Charset charset) { """ Reads all characters from uri, using the given character set. It throws an unchecked exception if an error occurs. """ return searchForSupportedProcessor(uri).readString(uri, charset); }
java
public String readString(URI uri, Charset charset) { return searchForSupportedProcessor(uri).readString(uri, charset); }
[ "public", "String", "readString", "(", "URI", "uri", ",", "Charset", "charset", ")", "{", "return", "searchForSupportedProcessor", "(", "uri", ")", ".", "readString", "(", "uri", ",", "charset", ")", ";", "}" ]
Reads all characters from uri, using the given character set. It throws an unchecked exception if an error occurs.
[ "Reads", "all", "characters", "from", "uri", "using", "the", "given", "character", "set", ".", "It", "throws", "an", "unchecked", "exception", "if", "an", "error", "occurs", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java#L69-L71
yidongnan/grpc-spring-boot-starter
grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/autoconfigure/GrpcClientAutoConfiguration.java
GrpcClientAutoConfiguration.grpcNameResolverFactory
@ConditionalOnMissingBean @Lazy // Not needed for InProcessChannelFactories @Bean public NameResolver.Factory grpcNameResolverFactory(final GrpcChannelsProperties channelProperties) { """ Creates a new name resolver factory with the given channel properties. The properties are used to map the client name to the actual service addresses. If you want to add more name resolver schemes or modify existing ones, you can do that in the following ways: <ul> <li>If you only rely on the client properties or other static beans, then you can simply add an entry to java's service discovery for {@link io.grpc.NameResolverProvider}s.</li> <li>If you need access to other beans, then you have to redefine this bean and use a {@link CompositeNameResolverFactory} as the delegate for the {@link ConfigMappedNameResolverFactory}.</li> </ul> @param channelProperties The properties for the channels. @return The default config mapped name resolver factory. """ return new ConfigMappedNameResolverFactory(channelProperties, NameResolverProvider.asFactory(), StaticNameResolverProvider.STATIC_DEFAULT_URI_MAPPER); }
java
@ConditionalOnMissingBean @Lazy // Not needed for InProcessChannelFactories @Bean public NameResolver.Factory grpcNameResolverFactory(final GrpcChannelsProperties channelProperties) { return new ConfigMappedNameResolverFactory(channelProperties, NameResolverProvider.asFactory(), StaticNameResolverProvider.STATIC_DEFAULT_URI_MAPPER); }
[ "@", "ConditionalOnMissingBean", "@", "Lazy", "// Not needed for InProcessChannelFactories", "@", "Bean", "public", "NameResolver", ".", "Factory", "grpcNameResolverFactory", "(", "final", "GrpcChannelsProperties", "channelProperties", ")", "{", "return", "new", "ConfigMappedNameResolverFactory", "(", "channelProperties", ",", "NameResolverProvider", ".", "asFactory", "(", ")", ",", "StaticNameResolverProvider", ".", "STATIC_DEFAULT_URI_MAPPER", ")", ";", "}" ]
Creates a new name resolver factory with the given channel properties. The properties are used to map the client name to the actual service addresses. If you want to add more name resolver schemes or modify existing ones, you can do that in the following ways: <ul> <li>If you only rely on the client properties or other static beans, then you can simply add an entry to java's service discovery for {@link io.grpc.NameResolverProvider}s.</li> <li>If you need access to other beans, then you have to redefine this bean and use a {@link CompositeNameResolverFactory} as the delegate for the {@link ConfigMappedNameResolverFactory}.</li> </ul> @param channelProperties The properties for the channels. @return The default config mapped name resolver factory.
[ "Creates", "a", "new", "name", "resolver", "factory", "with", "the", "given", "channel", "properties", ".", "The", "properties", "are", "used", "to", "map", "the", "client", "name", "to", "the", "actual", "service", "addresses", ".", "If", "you", "want", "to", "add", "more", "name", "resolver", "schemes", "or", "modify", "existing", "ones", "you", "can", "do", "that", "in", "the", "following", "ways", ":" ]
train
https://github.com/yidongnan/grpc-spring-boot-starter/blob/07f8853cfafc9707584f2371aff012e590217b85/grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/autoconfigure/GrpcClientAutoConfiguration.java#L125-L131
google/closure-templates
java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java
ExpressionCompiler.createBasicCompiler
static BasicExpressionCompiler createBasicCompiler( TemplateParameterLookup parameters, TemplateVariableManager varManager, ErrorReporter reporter, SoyTypeRegistry registry) { """ Create a basic compiler with trivial detaching logic. <p>All generated detach points are implemented as {@code return} statements and the returned value is boxed, so it is only valid for use by the {@link LazyClosureCompiler}. """ return new BasicExpressionCompiler(parameters, varManager, reporter, registry); }
java
static BasicExpressionCompiler createBasicCompiler( TemplateParameterLookup parameters, TemplateVariableManager varManager, ErrorReporter reporter, SoyTypeRegistry registry) { return new BasicExpressionCompiler(parameters, varManager, reporter, registry); }
[ "static", "BasicExpressionCompiler", "createBasicCompiler", "(", "TemplateParameterLookup", "parameters", ",", "TemplateVariableManager", "varManager", ",", "ErrorReporter", "reporter", ",", "SoyTypeRegistry", "registry", ")", "{", "return", "new", "BasicExpressionCompiler", "(", "parameters", ",", "varManager", ",", "reporter", ",", "registry", ")", ";", "}" ]
Create a basic compiler with trivial detaching logic. <p>All generated detach points are implemented as {@code return} statements and the returned value is boxed, so it is only valid for use by the {@link LazyClosureCompiler}.
[ "Create", "a", "basic", "compiler", "with", "trivial", "detaching", "logic", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ExpressionCompiler.java#L190-L196
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/engine/decision/DefaultProfileStorageDecision.java
DefaultProfileStorageDecision.mustLoadProfilesFromSession
@Override public boolean mustLoadProfilesFromSession(final C context, final List<Client> currentClients) { """ Load the profiles from the web session if no clients are defined or if the first client is an indirect one or if the first client is the anonymous one. @param context the web context @param currentClients the current clients @return whether the profiles must be loaded from the web session """ return isEmpty(currentClients) || currentClients.get(0) instanceof IndirectClient || currentClients.get(0) instanceof AnonymousClient; }
java
@Override public boolean mustLoadProfilesFromSession(final C context, final List<Client> currentClients) { return isEmpty(currentClients) || currentClients.get(0) instanceof IndirectClient || currentClients.get(0) instanceof AnonymousClient; }
[ "@", "Override", "public", "boolean", "mustLoadProfilesFromSession", "(", "final", "C", "context", ",", "final", "List", "<", "Client", ">", "currentClients", ")", "{", "return", "isEmpty", "(", "currentClients", ")", "||", "currentClients", ".", "get", "(", "0", ")", "instanceof", "IndirectClient", "||", "currentClients", ".", "get", "(", "0", ")", "instanceof", "AnonymousClient", ";", "}" ]
Load the profiles from the web session if no clients are defined or if the first client is an indirect one or if the first client is the anonymous one. @param context the web context @param currentClients the current clients @return whether the profiles must be loaded from the web session
[ "Load", "the", "profiles", "from", "the", "web", "session", "if", "no", "clients", "are", "defined", "or", "if", "the", "first", "client", "is", "an", "indirect", "one", "or", "if", "the", "first", "client", "is", "the", "anonymous", "one", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/engine/decision/DefaultProfileStorageDecision.java#L30-L34
Microsoft/spring-data-cosmosdb
src/main/java/com/microsoft/azure/spring/data/cosmosdb/core/generator/AbstractQueryGenerator.java
AbstractQueryGenerator.generateQuery
protected SqlQuerySpec generateQuery(@NonNull DocumentQuery query, @NonNull String queryHead) { """ Generate SqlQuerySpec with given DocumentQuery and query head. @param query DocumentQuery represent one query method. @param queryHead @return The SqlQuerySpec for DocumentClient. """ Assert.hasText(queryHead, "query head should have text."); final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getValue1(); final SqlParameterCollection sqlParameters = new SqlParameterCollection(); sqlParameters.addAll( parameters.stream() .map(p -> new SqlParameter("@" + p.getValue0(), toDocumentDBValue(p.getValue1()))) .collect(Collectors.toList()) ); return new SqlQuerySpec(queryString, sqlParameters); }
java
protected SqlQuerySpec generateQuery(@NonNull DocumentQuery query, @NonNull String queryHead) { Assert.hasText(queryHead, "query head should have text."); final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getValue1(); final SqlParameterCollection sqlParameters = new SqlParameterCollection(); sqlParameters.addAll( parameters.stream() .map(p -> new SqlParameter("@" + p.getValue0(), toDocumentDBValue(p.getValue1()))) .collect(Collectors.toList()) ); return new SqlQuerySpec(queryString, sqlParameters); }
[ "protected", "SqlQuerySpec", "generateQuery", "(", "@", "NonNull", "DocumentQuery", "query", ",", "@", "NonNull", "String", "queryHead", ")", "{", "Assert", ".", "hasText", "(", "queryHead", ",", "\"query head should have text.\"", ")", ";", "final", "Pair", "<", "String", ",", "List", "<", "Pair", "<", "String", ",", "Object", ">", ">", ">", "queryBody", "=", "generateQueryBody", "(", "query", ")", ";", "final", "String", "queryString", "=", "String", ".", "join", "(", "\" \"", ",", "queryHead", ",", "queryBody", ".", "getValue0", "(", ")", ",", "generateQueryTail", "(", "query", ")", ")", ";", "final", "List", "<", "Pair", "<", "String", ",", "Object", ">", ">", "parameters", "=", "queryBody", ".", "getValue1", "(", ")", ";", "final", "SqlParameterCollection", "sqlParameters", "=", "new", "SqlParameterCollection", "(", ")", ";", "sqlParameters", ".", "addAll", "(", "parameters", ".", "stream", "(", ")", ".", "map", "(", "p", "->", "new", "SqlParameter", "(", "\"@\"", "+", "p", ".", "getValue0", "(", ")", ",", "toDocumentDBValue", "(", "p", ".", "getValue1", "(", ")", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "return", "new", "SqlQuerySpec", "(", "queryString", ",", "sqlParameters", ")", ";", "}" ]
Generate SqlQuerySpec with given DocumentQuery and query head. @param query DocumentQuery represent one query method. @param queryHead @return The SqlQuerySpec for DocumentClient.
[ "Generate", "SqlQuerySpec", "with", "given", "DocumentQuery", "and", "query", "head", "." ]
train
https://github.com/Microsoft/spring-data-cosmosdb/blob/f349fce5892f225794eae865ca9a12191cac243c/src/main/java/com/microsoft/azure/spring/data/cosmosdb/core/generator/AbstractQueryGenerator.java#L210-L225
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsEntityAttribute.java
CmsEntityAttribute.createSimpleAttribute
public static CmsEntityAttribute createSimpleAttribute(String name, List<String> values) { """ Creates a simple type attribute.<p> @param name the attribute name @param values the attribute values @return the newly created attribute """ CmsEntityAttribute result = new CmsEntityAttribute(); result.m_name = name; result.m_simpleValues = Collections.unmodifiableList(values); return result; }
java
public static CmsEntityAttribute createSimpleAttribute(String name, List<String> values) { CmsEntityAttribute result = new CmsEntityAttribute(); result.m_name = name; result.m_simpleValues = Collections.unmodifiableList(values); return result; }
[ "public", "static", "CmsEntityAttribute", "createSimpleAttribute", "(", "String", "name", ",", "List", "<", "String", ">", "values", ")", "{", "CmsEntityAttribute", "result", "=", "new", "CmsEntityAttribute", "(", ")", ";", "result", ".", "m_name", "=", "name", ";", "result", ".", "m_simpleValues", "=", "Collections", ".", "unmodifiableList", "(", "values", ")", ";", "return", "result", ";", "}" ]
Creates a simple type attribute.<p> @param name the attribute name @param values the attribute values @return the newly created attribute
[ "Creates", "a", "simple", "type", "attribute", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsEntityAttribute.java#L83-L89
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java
TransformerRegistry.resolveHost
public OperationTransformerRegistry resolveHost(final ModelVersion mgmtVersion, final Map<PathAddress, ModelVersion> subsystems) { """ Resolve the host registry. @param mgmtVersion the mgmt version @param subsystems the subsystems @return the transformer registry """ // The domain / host / servers final OperationTransformerRegistry root = domain.create(mgmtVersion, Collections.<PathAddress, ModelVersion>emptyMap()); subsystem.mergeSubtree(root, PathAddress.pathAddress(PROFILE), subsystems); subsystem.mergeSubtree(root, PathAddress.pathAddress(HOST, SERVER), subsystems); return root; }
java
public OperationTransformerRegistry resolveHost(final ModelVersion mgmtVersion, final Map<PathAddress, ModelVersion> subsystems) { // The domain / host / servers final OperationTransformerRegistry root = domain.create(mgmtVersion, Collections.<PathAddress, ModelVersion>emptyMap()); subsystem.mergeSubtree(root, PathAddress.pathAddress(PROFILE), subsystems); subsystem.mergeSubtree(root, PathAddress.pathAddress(HOST, SERVER), subsystems); return root; }
[ "public", "OperationTransformerRegistry", "resolveHost", "(", "final", "ModelVersion", "mgmtVersion", ",", "final", "Map", "<", "PathAddress", ",", "ModelVersion", ">", "subsystems", ")", "{", "// The domain / host / servers", "final", "OperationTransformerRegistry", "root", "=", "domain", ".", "create", "(", "mgmtVersion", ",", "Collections", ".", "<", "PathAddress", ",", "ModelVersion", ">", "emptyMap", "(", ")", ")", ";", "subsystem", ".", "mergeSubtree", "(", "root", ",", "PathAddress", ".", "pathAddress", "(", "PROFILE", ")", ",", "subsystems", ")", ";", "subsystem", ".", "mergeSubtree", "(", "root", ",", "PathAddress", ".", "pathAddress", "(", "HOST", ",", "SERVER", ")", ",", "subsystems", ")", ";", "return", "root", ";", "}" ]
Resolve the host registry. @param mgmtVersion the mgmt version @param subsystems the subsystems @return the transformer registry
[ "Resolve", "the", "host", "registry", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java#L209-L215
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowsInner.java
WorkflowsInner.validateWorkflow
public void validateWorkflow(String resourceGroupName, String workflowName, WorkflowInner validate) { """ Validates the workflow. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param validate The workflow. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ validateWorkflowWithServiceResponseAsync(resourceGroupName, workflowName, validate).toBlocking().single().body(); }
java
public void validateWorkflow(String resourceGroupName, String workflowName, WorkflowInner validate) { validateWorkflowWithServiceResponseAsync(resourceGroupName, workflowName, validate).toBlocking().single().body(); }
[ "public", "void", "validateWorkflow", "(", "String", "resourceGroupName", ",", "String", "workflowName", ",", "WorkflowInner", "validate", ")", "{", "validateWorkflowWithServiceResponseAsync", "(", "resourceGroupName", ",", "workflowName", ",", "validate", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Validates the workflow. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param validate The workflow. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Validates", "the", "workflow", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowsInner.java#L1758-L1760
GoSimpleLLC/nbvcxz
src/main/java/me/gosimple/nbvcxz/Nbvcxz.java
Nbvcxz.guessEntropy
private Result guessEntropy(final Configuration configuration, final String password) { """ Calculates the minimum entropy for a given password and returns that as a Result. <br><br> This method attempts to find the minimum entropy at each position of the password, and then does a backwards pass to remove overlapping matches. The end result is a list of matches that when their tokens are added up, should equal the original password. <br><br> The result object is guaranteed to match the original password, or throw an exception if it doesn't. @param configuration the configuration file used to estimate entropy. @param password the password you are guessing entropy for. @return the {@code Result} of this estimate. """ resetVariables(); Result final_result = new Result(configuration, password, getBestCombination(configuration, password)); return final_result; }
java
private Result guessEntropy(final Configuration configuration, final String password) { resetVariables(); Result final_result = new Result(configuration, password, getBestCombination(configuration, password)); return final_result; }
[ "private", "Result", "guessEntropy", "(", "final", "Configuration", "configuration", ",", "final", "String", "password", ")", "{", "resetVariables", "(", ")", ";", "Result", "final_result", "=", "new", "Result", "(", "configuration", ",", "password", ",", "getBestCombination", "(", "configuration", ",", "password", ")", ")", ";", "return", "final_result", ";", "}" ]
Calculates the minimum entropy for a given password and returns that as a Result. <br><br> This method attempts to find the minimum entropy at each position of the password, and then does a backwards pass to remove overlapping matches. The end result is a list of matches that when their tokens are added up, should equal the original password. <br><br> The result object is guaranteed to match the original password, or throw an exception if it doesn't. @param configuration the configuration file used to estimate entropy. @param password the password you are guessing entropy for. @return the {@code Result} of this estimate.
[ "Calculates", "the", "minimum", "entropy", "for", "a", "given", "password", "and", "returns", "that", "as", "a", "Result", ".", "<br", ">", "<br", ">", "This", "method", "attempts", "to", "find", "the", "minimum", "entropy", "at", "each", "position", "of", "the", "password", "and", "then", "does", "a", "backwards", "pass", "to", "remove", "overlapping", "matches", ".", "The", "end", "result", "is", "a", "list", "of", "matches", "that", "when", "their", "tokens", "are", "added", "up", "should", "equal", "the", "original", "password", ".", "<br", ">", "<br", ">", "The", "result", "object", "is", "guaranteed", "to", "match", "the", "original", "password", "or", "throw", "an", "exception", "if", "it", "doesn", "t", "." ]
train
https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/Nbvcxz.java#L235-L241
qiujuer/Genius-Android
caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java
UiCompat.getColor
public static int getColor(Resources resources, int id) { """ Returns a themed color integer associated with a particular resource ID. If the resource holds a complex {@link ColorStateList}, then the default color from the set is returned. @param resources Resources @param id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier. @return A single color value in the form 0xAARRGGBB. """ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return resources.getColor(id, null); } else { return resources.getColor(id); } }
java
public static int getColor(Resources resources, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return resources.getColor(id, null); } else { return resources.getColor(id); } }
[ "public", "static", "int", "getColor", "(", "Resources", "resources", ",", "int", "id", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "M", ")", "{", "return", "resources", ".", "getColor", "(", "id", ",", "null", ")", ";", "}", "else", "{", "return", "resources", ".", "getColor", "(", "id", ")", ";", "}", "}" ]
Returns a themed color integer associated with a particular resource ID. If the resource holds a complex {@link ColorStateList}, then the default color from the set is returned. @param resources Resources @param id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier. @return A single color value in the form 0xAARRGGBB.
[ "Returns", "a", "themed", "color", "integer", "associated", "with", "a", "particular", "resource", "ID", ".", "If", "the", "resource", "holds", "a", "complex", "{", "@link", "ColorStateList", "}", "then", "the", "default", "color", "from", "the", "set", "is", "returned", "." ]
train
https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java#L110-L116
bazaarvoice/emodb
databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java
DatabusClient.replayAsync
@Override public String replayAsync(String apiKey, String subscription) { """ Any server can initiate a replay request, no need for @PartitionKey """ return replayAsyncSince(apiKey, subscription, null); }
java
@Override public String replayAsync(String apiKey, String subscription) { return replayAsyncSince(apiKey, subscription, null); }
[ "@", "Override", "public", "String", "replayAsync", "(", "String", "apiKey", ",", "String", "subscription", ")", "{", "return", "replayAsyncSince", "(", "apiKey", ",", "subscription", ",", "null", ")", ";", "}" ]
Any server can initiate a replay request, no need for @PartitionKey
[ "Any", "server", "can", "initiate", "a", "replay", "request", "no", "need", "for" ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java#L289-L292
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.paceFormat
public static String paceFormat(final Number value, final PaceParameters params) { """ Matches a pace (value and interval) with a logical time frame. Very useful for slow paces. @param value The number of occurrences within the specified interval @param params The pace format parameterization @return an human readable textual representation of the pace """ params.checkArguments(); Pace args = pace(value, params.interval); ResourceBundle bundle = context.get().getBundle(); String accuracy = bundle.getString(args.getAccuracy()); String timeUnit = bundle.getString(args.getTimeUnit()); params.exts(accuracy, timeUnit); return capitalize(pluralize(args.getValue(), params.plural)); }
java
public static String paceFormat(final Number value, final PaceParameters params) { params.checkArguments(); Pace args = pace(value, params.interval); ResourceBundle bundle = context.get().getBundle(); String accuracy = bundle.getString(args.getAccuracy()); String timeUnit = bundle.getString(args.getTimeUnit()); params.exts(accuracy, timeUnit); return capitalize(pluralize(args.getValue(), params.plural)); }
[ "public", "static", "String", "paceFormat", "(", "final", "Number", "value", ",", "final", "PaceParameters", "params", ")", "{", "params", ".", "checkArguments", "(", ")", ";", "Pace", "args", "=", "pace", "(", "value", ",", "params", ".", "interval", ")", ";", "ResourceBundle", "bundle", "=", "context", ".", "get", "(", ")", ".", "getBundle", "(", ")", ";", "String", "accuracy", "=", "bundle", ".", "getString", "(", "args", ".", "getAccuracy", "(", ")", ")", ";", "String", "timeUnit", "=", "bundle", ".", "getString", "(", "args", ".", "getTimeUnit", "(", ")", ")", ";", "params", ".", "exts", "(", "accuracy", ",", "timeUnit", ")", ";", "return", "capitalize", "(", "pluralize", "(", "args", ".", "getValue", "(", ")", ",", "params", ".", "plural", ")", ")", ";", "}" ]
Matches a pace (value and interval) with a logical time frame. Very useful for slow paces. @param value The number of occurrences within the specified interval @param params The pace format parameterization @return an human readable textual representation of the pace
[ "Matches", "a", "pace", "(", "value", "and", "interval", ")", "with", "a", "logical", "time", "frame", ".", "Very", "useful", "for", "slow", "paces", "." ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2093-L2107
tianjing/tgtools.web.develop
src/main/java/tgtools/web/develop/util/ValidHelper.java
ValidHelper.validString
public static void validString(String pContent, String pParamName) throws APPErrorException { """ 验证字符串 不能为空 @param pContent 文本 @param pParamName 参数名称 @throws APPErrorException """ if (StringUtil.isNullOrEmpty(pContent)) { throw new APPErrorException(pParamName + " 不能为空"); } }
java
public static void validString(String pContent, String pParamName) throws APPErrorException { if (StringUtil.isNullOrEmpty(pContent)) { throw new APPErrorException(pParamName + " 不能为空"); } }
[ "public", "static", "void", "validString", "(", "String", "pContent", ",", "String", "pParamName", ")", "throws", "APPErrorException", "{", "if", "(", "StringUtil", ".", "isNullOrEmpty", "(", "pContent", ")", ")", "{", "throw", "new", "APPErrorException", "(", "pParamName", "+", "\" 不能为空\");", "", "", "}", "}" ]
验证字符串 不能为空 @param pContent 文本 @param pParamName 参数名称 @throws APPErrorException
[ "验证字符串", "不能为空" ]
train
https://github.com/tianjing/tgtools.web.develop/blob/a18567f3ccf877249f2e33028d1e7c479900e4eb/src/main/java/tgtools/web/develop/util/ValidHelper.java#L36-L40
haifengl/smile
data/src/main/java/smile/data/parser/ArffParser.java
ArffParser.getLastToken
private void getLastToken(StreamTokenizer tokenizer, boolean endOfFileOk) throws IOException, ParseException { """ Gets token and checks if it's end of line. @param endOfFileOk true if EOF is OK @throws IllegalStateException if it doesn't find an end of line """ if ((tokenizer.nextToken() != StreamTokenizer.TT_EOL) && ((tokenizer.ttype != StreamTokenizer.TT_EOF) || !endOfFileOk)) { throw new ParseException("end of line expected", tokenizer.lineno()); } }
java
private void getLastToken(StreamTokenizer tokenizer, boolean endOfFileOk) throws IOException, ParseException { if ((tokenizer.nextToken() != StreamTokenizer.TT_EOL) && ((tokenizer.ttype != StreamTokenizer.TT_EOF) || !endOfFileOk)) { throw new ParseException("end of line expected", tokenizer.lineno()); } }
[ "private", "void", "getLastToken", "(", "StreamTokenizer", "tokenizer", ",", "boolean", "endOfFileOk", ")", "throws", "IOException", ",", "ParseException", "{", "if", "(", "(", "tokenizer", ".", "nextToken", "(", ")", "!=", "StreamTokenizer", ".", "TT_EOL", ")", "&&", "(", "(", "tokenizer", ".", "ttype", "!=", "StreamTokenizer", ".", "TT_EOF", ")", "||", "!", "endOfFileOk", ")", ")", "{", "throw", "new", "ParseException", "(", "\"end of line expected\"", ",", "tokenizer", ".", "lineno", "(", ")", ")", ";", "}", "}" ]
Gets token and checks if it's end of line. @param endOfFileOk true if EOF is OK @throws IllegalStateException if it doesn't find an end of line
[ "Gets", "token", "and", "checks", "if", "it", "s", "end", "of", "line", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/ArffParser.java#L153-L157
davidmarquis/fluent-interface-proxy
src/main/java/com/fluentinterface/beans/ObjectWrapper.java
ObjectWrapper.getPropertyOrThrow
private static Property getPropertyOrThrow(Bean bean, String propertyName) { """ Internal: Static version of {@link #getProperty(String)}, throws an exception instead of return null. @param bean the bean object whose property is to be searched @param propertyName the name of the property to search @return the property with the given name, if found @throws NullPointerException if the bean object does not have a property with the given name """ Property property = bean.getProperty(propertyName); if (property == null) { throw new PropertyNotFoundException("Cannot find property with name '" + propertyName + "' in " + bean + "."); } return property; }
java
private static Property getPropertyOrThrow(Bean bean, String propertyName) { Property property = bean.getProperty(propertyName); if (property == null) { throw new PropertyNotFoundException("Cannot find property with name '" + propertyName + "' in " + bean + "."); } return property; }
[ "private", "static", "Property", "getPropertyOrThrow", "(", "Bean", "bean", ",", "String", "propertyName", ")", "{", "Property", "property", "=", "bean", ".", "getProperty", "(", "propertyName", ")", ";", "if", "(", "property", "==", "null", ")", "{", "throw", "new", "PropertyNotFoundException", "(", "\"Cannot find property with name '\"", "+", "propertyName", "+", "\"' in \"", "+", "bean", "+", "\".\"", ")", ";", "}", "return", "property", ";", "}" ]
Internal: Static version of {@link #getProperty(String)}, throws an exception instead of return null. @param bean the bean object whose property is to be searched @param propertyName the name of the property to search @return the property with the given name, if found @throws NullPointerException if the bean object does not have a property with the given name
[ "Internal", ":", "Static", "version", "of", "{", "@link", "#getProperty", "(", "String", ")", "}", "throws", "an", "exception", "instead", "of", "return", "null", "." ]
train
https://github.com/davidmarquis/fluent-interface-proxy/blob/8e72fff6cd1f496c76a01773269caead994fea65/src/main/java/com/fluentinterface/beans/ObjectWrapper.java#L420-L428
zaproxy/zaproxy
src/org/zaproxy/zap/view/DynamicFieldsPanel.java
DynamicFieldsPanel.getFieldValues
public Map<String, String> getFieldValues() { """ Gets a mapping of the field names to the configured field values. @return the field values """ Map<String, String> values = new HashMap<>(requiredFields.length + optionalFields.length); for (Entry<String, ZapTextField> f : textFields.entrySet()) values.put(f.getKey(), f.getValue().getText()); return values; } /** * Bind a mapping of field names/values to the fields in this panel. All the fields whose names * have a value provided in the map get set to that value, the others get cleared. * * @param fieldValues the field values */ public void bindFieldValues(Map<String, String> fieldValues) { for (Entry<String, ZapTextField> f : textFields.entrySet()) { ZapTextField field = f.getValue(); field.setText(fieldValues.get(f.getKey())); field.discardAllEdits(); } }
java
public Map<String, String> getFieldValues() { Map<String, String> values = new HashMap<>(requiredFields.length + optionalFields.length); for (Entry<String, ZapTextField> f : textFields.entrySet()) values.put(f.getKey(), f.getValue().getText()); return values; } /** * Bind a mapping of field names/values to the fields in this panel. All the fields whose names * have a value provided in the map get set to that value, the others get cleared. * * @param fieldValues the field values */ public void bindFieldValues(Map<String, String> fieldValues) { for (Entry<String, ZapTextField> f : textFields.entrySet()) { ZapTextField field = f.getValue(); field.setText(fieldValues.get(f.getKey())); field.discardAllEdits(); } }
[ "public", "Map", "<", "String", ",", "String", ">", "getFieldValues", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "values", "=", "new", "HashMap", "<>", "(", "requiredFields", ".", "length", "+", "optionalFields", ".", "length", ")", ";", "for", "(", "Entry", "<", "String", ",", "ZapTextField", ">", "f", ":", "textFields", ".", "entrySet", "(", ")", ")", "values", ".", "put", "(", "f", ".", "getKey", "(", ")", ",", "f", ".", "getValue", "(", ")", ".", "getText", "(", ")", ")", ";", "return", "values", ";", "}", "/**\n\t * Bind a mapping of field names/values to the fields in this panel. All the fields whose names\n\t * have a value provided in the map get set to that value, the others get cleared.\n\t * \n\t * @param fieldValues the field values\n\t */", "public", "void", "bindFieldValues", "(", "Map", "<", "String", ",", "String", ">", "fieldValues", ")", "{", "for", "(", "Entry", "<", "String", ",", "ZapTextField", ">", "f", ":", "textFields", ".", "entrySet", "(", ")", ")", "{", "ZapTextField", "field", "=", "f", ".", "getValue", "(", ")", ";", "field", ".", "setText", "(", "fieldValues", ".", "get", "(", "f", ".", "getKey", "(", ")", ")", ")", ";", "field", ".", "discardAllEdits", "(", ")", ";", "}", "}" ]
Gets a mapping of the field names to the configured field values. @return the field values
[ "Gets", "a", "mapping", "of", "the", "field", "names", "to", "the", "configured", "field", "values", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/DynamicFieldsPanel.java#L146-L165
Jasig/uPortal
uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java
TemplateDataTenantOperationsListener.importWithResources
public TenantOperationResponse importWithResources( final ITenant tenant, final Set<Resource> resources) { """ High-level implementation method that brokers the queuing, importing, and reporting that is common to Create and Update. """ /* * First load dom4j Documents and sort the entity files into the proper order */ final Map<PortalDataKey, Set<BucketTuple>> importQueue; try { importQueue = prepareImportQueue(tenant, resources); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage( createLocalizedMessage( FAILED_TO_LOAD_TENANT_TEMPLATE, new String[] {tenant.getName()})); return error; } log.trace( "Ready to import data entity templates for new tenant '{}'; importQueue={}", tenant.getName(), importQueue); // We're going to report on every item imported; TODO it would be better // if we could display human-friendly entity type name + sysid (fname, etc.) final StringBuilder importReport = new StringBuilder(); /* * Now import the identified entities each bucket in turn */ try { importQueue(tenant, importQueue, importReport); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage(finalizeImportReport(importReport)); error.addMessage( createLocalizedMessage( FAILED_TO_IMPORT_TENANT_TEMPLATE_DATA, new String[] {tenant.getName()})); return error; } TenantOperationResponse rslt = new TenantOperationResponse(this, TenantOperationResponse.Result.SUCCESS); rslt.addMessage(finalizeImportReport(importReport)); rslt.addMessage( createLocalizedMessage(TENANT_ENTITIES_IMPORTED, new String[] {tenant.getName()})); return rslt; }
java
public TenantOperationResponse importWithResources( final ITenant tenant, final Set<Resource> resources) { /* * First load dom4j Documents and sort the entity files into the proper order */ final Map<PortalDataKey, Set<BucketTuple>> importQueue; try { importQueue = prepareImportQueue(tenant, resources); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage( createLocalizedMessage( FAILED_TO_LOAD_TENANT_TEMPLATE, new String[] {tenant.getName()})); return error; } log.trace( "Ready to import data entity templates for new tenant '{}'; importQueue={}", tenant.getName(), importQueue); // We're going to report on every item imported; TODO it would be better // if we could display human-friendly entity type name + sysid (fname, etc.) final StringBuilder importReport = new StringBuilder(); /* * Now import the identified entities each bucket in turn */ try { importQueue(tenant, importQueue, importReport); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage(finalizeImportReport(importReport)); error.addMessage( createLocalizedMessage( FAILED_TO_IMPORT_TENANT_TEMPLATE_DATA, new String[] {tenant.getName()})); return error; } TenantOperationResponse rslt = new TenantOperationResponse(this, TenantOperationResponse.Result.SUCCESS); rslt.addMessage(finalizeImportReport(importReport)); rslt.addMessage( createLocalizedMessage(TENANT_ENTITIES_IMPORTED, new String[] {tenant.getName()})); return rslt; }
[ "public", "TenantOperationResponse", "importWithResources", "(", "final", "ITenant", "tenant", ",", "final", "Set", "<", "Resource", ">", "resources", ")", "{", "/*\n * First load dom4j Documents and sort the entity files into the proper order\n */", "final", "Map", "<", "PortalDataKey", ",", "Set", "<", "BucketTuple", ">", ">", "importQueue", ";", "try", "{", "importQueue", "=", "prepareImportQueue", "(", "tenant", ",", "resources", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "final", "TenantOperationResponse", "error", "=", "new", "TenantOperationResponse", "(", "this", ",", "TenantOperationResponse", ".", "Result", ".", "ABORT", ")", ";", "error", ".", "addMessage", "(", "createLocalizedMessage", "(", "FAILED_TO_LOAD_TENANT_TEMPLATE", ",", "new", "String", "[", "]", "{", "tenant", ".", "getName", "(", ")", "}", ")", ")", ";", "return", "error", ";", "}", "log", ".", "trace", "(", "\"Ready to import data entity templates for new tenant '{}'; importQueue={}\"", ",", "tenant", ".", "getName", "(", ")", ",", "importQueue", ")", ";", "// We're going to report on every item imported; TODO it would be better", "// if we could display human-friendly entity type name + sysid (fname, etc.)", "final", "StringBuilder", "importReport", "=", "new", "StringBuilder", "(", ")", ";", "/*\n * Now import the identified entities each bucket in turn\n */", "try", "{", "importQueue", "(", "tenant", ",", "importQueue", ",", "importReport", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "final", "TenantOperationResponse", "error", "=", "new", "TenantOperationResponse", "(", "this", ",", "TenantOperationResponse", ".", "Result", ".", "ABORT", ")", ";", "error", ".", "addMessage", "(", "finalizeImportReport", "(", "importReport", ")", ")", ";", "error", ".", "addMessage", "(", "createLocalizedMessage", "(", "FAILED_TO_IMPORT_TENANT_TEMPLATE_DATA", ",", "new", "String", "[", "]", "{", "tenant", ".", "getName", "(", ")", "}", ")", ")", ";", "return", "error", ";", "}", "TenantOperationResponse", "rslt", "=", "new", "TenantOperationResponse", "(", "this", ",", "TenantOperationResponse", ".", "Result", ".", "SUCCESS", ")", ";", "rslt", ".", "addMessage", "(", "finalizeImportReport", "(", "importReport", ")", ")", ";", "rslt", ".", "addMessage", "(", "createLocalizedMessage", "(", "TENANT_ENTITIES_IMPORTED", ",", "new", "String", "[", "]", "{", "tenant", ".", "getName", "(", ")", "}", ")", ")", ";", "return", "rslt", ";", "}" ]
High-level implementation method that brokers the queuing, importing, and reporting that is common to Create and Update.
[ "High", "-", "level", "implementation", "method", "that", "brokers", "the", "queuing", "importing", "and", "reporting", "that", "is", "common", "to", "Create", "and", "Update", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java#L319-L367
zandero/rest.vertx
src/main/java/com/zandero/rest/exception/ConstraintException.java
ConstraintException.createMessage
private static String createMessage(RouteDefinition definition, Set<? extends ConstraintViolation<?>> constraintViolations) { """ Tries to produce some sensible message to make some informed decision @param definition route definition to get parameter information @param constraintViolations list of violations @return message describing violation """ List<String> messages = new ArrayList<>(); for (ConstraintViolation<?> violation : constraintViolations) { StringBuilder message = new StringBuilder(); for (Path.Node next : violation.getPropertyPath()) { if (next instanceof Path.ParameterNode && next.getKind().equals(ElementKind.PARAMETER)) { Path.ParameterNode paramNode = (Path.ParameterNode) next; int index = paramNode.getParameterIndex(); if (index < definition.getParameters().size()) { MethodParameter param = definition.getParameters().get(index); switch (param.getType()) { case body: message.append(param.toString()); message.append(" ").append(param.getDataType().getSimpleName()); break; default: message.append(param.toString()); break; } } } if (next instanceof Path.PropertyNode && next.getKind().equals(ElementKind.PROPERTY)) { Path.PropertyNode propertyNode = (Path.PropertyNode) next; message.append(".").append(propertyNode.getName()); } } message.append(": ").append(violation.getMessage()); messages.add(message.toString()); } return StringUtils.join(messages, ", "); }
java
private static String createMessage(RouteDefinition definition, Set<? extends ConstraintViolation<?>> constraintViolations) { List<String> messages = new ArrayList<>(); for (ConstraintViolation<?> violation : constraintViolations) { StringBuilder message = new StringBuilder(); for (Path.Node next : violation.getPropertyPath()) { if (next instanceof Path.ParameterNode && next.getKind().equals(ElementKind.PARAMETER)) { Path.ParameterNode paramNode = (Path.ParameterNode) next; int index = paramNode.getParameterIndex(); if (index < definition.getParameters().size()) { MethodParameter param = definition.getParameters().get(index); switch (param.getType()) { case body: message.append(param.toString()); message.append(" ").append(param.getDataType().getSimpleName()); break; default: message.append(param.toString()); break; } } } if (next instanceof Path.PropertyNode && next.getKind().equals(ElementKind.PROPERTY)) { Path.PropertyNode propertyNode = (Path.PropertyNode) next; message.append(".").append(propertyNode.getName()); } } message.append(": ").append(violation.getMessage()); messages.add(message.toString()); } return StringUtils.join(messages, ", "); }
[ "private", "static", "String", "createMessage", "(", "RouteDefinition", "definition", ",", "Set", "<", "?", "extends", "ConstraintViolation", "<", "?", ">", ">", "constraintViolations", ")", "{", "List", "<", "String", ">", "messages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "ConstraintViolation", "<", "?", ">", "violation", ":", "constraintViolations", ")", "{", "StringBuilder", "message", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Path", ".", "Node", "next", ":", "violation", ".", "getPropertyPath", "(", ")", ")", "{", "if", "(", "next", "instanceof", "Path", ".", "ParameterNode", "&&", "next", ".", "getKind", "(", ")", ".", "equals", "(", "ElementKind", ".", "PARAMETER", ")", ")", "{", "Path", ".", "ParameterNode", "paramNode", "=", "(", "Path", ".", "ParameterNode", ")", "next", ";", "int", "index", "=", "paramNode", ".", "getParameterIndex", "(", ")", ";", "if", "(", "index", "<", "definition", ".", "getParameters", "(", ")", ".", "size", "(", ")", ")", "{", "MethodParameter", "param", "=", "definition", ".", "getParameters", "(", ")", ".", "get", "(", "index", ")", ";", "switch", "(", "param", ".", "getType", "(", ")", ")", "{", "case", "body", ":", "message", ".", "append", "(", "param", ".", "toString", "(", ")", ")", ";", "message", ".", "append", "(", "\" \"", ")", ".", "append", "(", "param", ".", "getDataType", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "break", ";", "default", ":", "message", ".", "append", "(", "param", ".", "toString", "(", ")", ")", ";", "break", ";", "}", "}", "}", "if", "(", "next", "instanceof", "Path", ".", "PropertyNode", "&&", "next", ".", "getKind", "(", ")", ".", "equals", "(", "ElementKind", ".", "PROPERTY", ")", ")", "{", "Path", ".", "PropertyNode", "propertyNode", "=", "(", "Path", ".", "PropertyNode", ")", "next", ";", "message", ".", "append", "(", "\".\"", ")", ".", "append", "(", "propertyNode", ".", "getName", "(", ")", ")", ";", "}", "}", "message", ".", "append", "(", "\": \"", ")", ".", "append", "(", "violation", ".", "getMessage", "(", ")", ")", ";", "messages", ".", "add", "(", "message", ".", "toString", "(", ")", ")", ";", "}", "return", "StringUtils", ".", "join", "(", "messages", ",", "\", \"", ")", ";", "}" ]
Tries to produce some sensible message to make some informed decision @param definition route definition to get parameter information @param constraintViolations list of violations @return message describing violation
[ "Tries", "to", "produce", "some", "sensible", "message", "to", "make", "some", "informed", "decision" ]
train
https://github.com/zandero/rest.vertx/blob/ba458720cf59e076953eab9dac7227eeaf9e58ce/src/main/java/com/zandero/rest/exception/ConstraintException.java#L39-L82
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/chess/ChessboardCornerClusterFinder.java
ChessboardCornerClusterFinder.growCluster
private void growCluster(List<ChessboardCorner> corners, int seedIdx, ChessboardCornerGraph graph) { """ Given the initial seed, add all connected nodes to the output cluster while keeping track of how to convert one node index into another one, between the two graphs """ // open contains corner list indexes open.add(seedIdx); while( open.size > 0 ) { int cornerIdx = open.pop(); Vertex v = vertexes.get(cornerIdx); // make sure it hasn't already been processed if( v.marked) continue; v.marked = true; // Create the node in the output cluster for this corner ChessboardCornerGraph.Node gn = graph.growCorner(); c2n.data[cornerIdx] = gn.index; n2c.data[gn.index] = cornerIdx; gn.set(corners.get(cornerIdx)); // Add to the open list all the edges which haven't been processed yet; for (int i = 0; i < v.connections.size(); i++) { Vertex dst = v.connections.get(i).dst; if( dst.marked) continue; open.add( dst.index ); } } }
java
private void growCluster(List<ChessboardCorner> corners, int seedIdx, ChessboardCornerGraph graph) { // open contains corner list indexes open.add(seedIdx); while( open.size > 0 ) { int cornerIdx = open.pop(); Vertex v = vertexes.get(cornerIdx); // make sure it hasn't already been processed if( v.marked) continue; v.marked = true; // Create the node in the output cluster for this corner ChessboardCornerGraph.Node gn = graph.growCorner(); c2n.data[cornerIdx] = gn.index; n2c.data[gn.index] = cornerIdx; gn.set(corners.get(cornerIdx)); // Add to the open list all the edges which haven't been processed yet; for (int i = 0; i < v.connections.size(); i++) { Vertex dst = v.connections.get(i).dst; if( dst.marked) continue; open.add( dst.index ); } } }
[ "private", "void", "growCluster", "(", "List", "<", "ChessboardCorner", ">", "corners", ",", "int", "seedIdx", ",", "ChessboardCornerGraph", "graph", ")", "{", "// open contains corner list indexes", "open", ".", "add", "(", "seedIdx", ")", ";", "while", "(", "open", ".", "size", ">", "0", ")", "{", "int", "cornerIdx", "=", "open", ".", "pop", "(", ")", ";", "Vertex", "v", "=", "vertexes", ".", "get", "(", "cornerIdx", ")", ";", "// make sure it hasn't already been processed", "if", "(", "v", ".", "marked", ")", "continue", ";", "v", ".", "marked", "=", "true", ";", "// Create the node in the output cluster for this corner", "ChessboardCornerGraph", ".", "Node", "gn", "=", "graph", ".", "growCorner", "(", ")", ";", "c2n", ".", "data", "[", "cornerIdx", "]", "=", "gn", ".", "index", ";", "n2c", ".", "data", "[", "gn", ".", "index", "]", "=", "cornerIdx", ";", "gn", ".", "set", "(", "corners", ".", "get", "(", "cornerIdx", ")", ")", ";", "// Add to the open list all the edges which haven't been processed yet;", "for", "(", "int", "i", "=", "0", ";", "i", "<", "v", ".", "connections", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Vertex", "dst", "=", "v", ".", "connections", ".", "get", "(", "i", ")", ".", "dst", ";", "if", "(", "dst", ".", "marked", ")", "continue", ";", "open", ".", "add", "(", "dst", ".", "index", ")", ";", "}", "}", "}" ]
Given the initial seed, add all connected nodes to the output cluster while keeping track of how to convert one node index into another one, between the two graphs
[ "Given", "the", "initial", "seed", "add", "all", "connected", "nodes", "to", "the", "output", "cluster", "while", "keeping", "track", "of", "how", "to", "convert", "one", "node", "index", "into", "another", "one", "between", "the", "two", "graphs" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/chess/ChessboardCornerClusterFinder.java#L821-L847
groovy/groovy-core
src/main/groovy/lang/Binding.java
Binding.setVariable
public void setVariable(String name, Object value) { """ Sets the value of the given variable @param name the name of the variable to set @param value the new value for the given variable """ if (variables == null) variables = new LinkedHashMap(); variables.put(name, value); }
java
public void setVariable(String name, Object value) { if (variables == null) variables = new LinkedHashMap(); variables.put(name, value); }
[ "public", "void", "setVariable", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "variables", "==", "null", ")", "variables", "=", "new", "LinkedHashMap", "(", ")", ";", "variables", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Sets the value of the given variable @param name the name of the variable to set @param value the new value for the given variable
[ "Sets", "the", "value", "of", "the", "given", "variable" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/Binding.java#L76-L80
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuRefactorUtil.java
GosuRefactorUtil.boundingParent
public static IParsedElement boundingParent( List<IParseTree> locations, int position, Class<? extends IParsedElement>... possibleTypes ) { """ Finds a bounding parent of any of the possible types passed in from the list of locations, starting at the position given. """ IParseTree location = IParseTree.Search.getDeepestLocation( locations, position, true ); IParsedElement pe = null; if( location != null ) { pe = location.getParsedElement(); while( pe != null && !isOneOfTypes( pe, possibleTypes ) ) { pe = pe.getParent(); } } return pe; }
java
public static IParsedElement boundingParent( List<IParseTree> locations, int position, Class<? extends IParsedElement>... possibleTypes ) { IParseTree location = IParseTree.Search.getDeepestLocation( locations, position, true ); IParsedElement pe = null; if( location != null ) { pe = location.getParsedElement(); while( pe != null && !isOneOfTypes( pe, possibleTypes ) ) { pe = pe.getParent(); } } return pe; }
[ "public", "static", "IParsedElement", "boundingParent", "(", "List", "<", "IParseTree", ">", "locations", ",", "int", "position", ",", "Class", "<", "?", "extends", "IParsedElement", ">", "...", "possibleTypes", ")", "{", "IParseTree", "location", "=", "IParseTree", ".", "Search", ".", "getDeepestLocation", "(", "locations", ",", "position", ",", "true", ")", ";", "IParsedElement", "pe", "=", "null", ";", "if", "(", "location", "!=", "null", ")", "{", "pe", "=", "location", ".", "getParsedElement", "(", ")", ";", "while", "(", "pe", "!=", "null", "&&", "!", "isOneOfTypes", "(", "pe", ",", "possibleTypes", ")", ")", "{", "pe", "=", "pe", ".", "getParent", "(", ")", ";", "}", "}", "return", "pe", ";", "}" ]
Finds a bounding parent of any of the possible types passed in from the list of locations, starting at the position given.
[ "Finds", "a", "bounding", "parent", "of", "any", "of", "the", "possible", "types", "passed", "in", "from", "the", "list", "of", "locations", "starting", "at", "the", "position", "given", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuRefactorUtil.java#L23-L37
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.updateSecretAsync
public ServiceFuture<SecretBundle> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback<SecretBundle> serviceCallback) { """ Updates the attributes associated with a specified secret in a given key vault. The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the secrets/set permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param secretName The name of the secret. @param secretVersion The version of the secret. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return ServiceFuture.fromResponse(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); }
java
public ServiceFuture<SecretBundle> updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, final ServiceCallback<SecretBundle> serviceCallback) { return ServiceFuture.fromResponse(updateSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion), serviceCallback); }
[ "public", "ServiceFuture", "<", "SecretBundle", ">", "updateSecretAsync", "(", "String", "vaultBaseUrl", ",", "String", "secretName", ",", "String", "secretVersion", ",", "final", "ServiceCallback", "<", "SecretBundle", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "updateSecretWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "secretName", ",", "secretVersion", ")", ",", "serviceCallback", ")", ";", "}" ]
Updates the attributes associated with a specified secret in a given key vault. The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the secrets/set permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param secretName The name of the secret. @param secretVersion The version of the secret. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Updates", "the", "attributes", "associated", "with", "a", "specified", "secret", "in", "a", "given", "key", "vault", ".", "The", "UPDATE", "operation", "changes", "specified", "attributes", "of", "an", "existing", "stored", "secret", ".", "Attributes", "that", "are", "not", "specified", "in", "the", "request", "are", "left", "unchanged", ".", "The", "value", "of", "a", "secret", "itself", "cannot", "be", "changed", ".", "This", "operation", "requires", "the", "secrets", "/", "set", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L3635-L3637
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.findAny
public <T> T findAny(Class<T> classType, String uri) { """ This method finds any document given a URI. <p>The URI must be URI-encoded. @param classType The class of type T. @param uri The URI as string. @return An object of type T. """ assertNotEmpty(classType, "Class"); assertNotEmpty(uri, "uri"); return couchDbClient.get(URI.create(uri), classType); }
java
public <T> T findAny(Class<T> classType, String uri) { assertNotEmpty(classType, "Class"); assertNotEmpty(uri, "uri"); return couchDbClient.get(URI.create(uri), classType); }
[ "public", "<", "T", ">", "T", "findAny", "(", "Class", "<", "T", ">", "classType", ",", "String", "uri", ")", "{", "assertNotEmpty", "(", "classType", ",", "\"Class\"", ")", ";", "assertNotEmpty", "(", "uri", ",", "\"uri\"", ")", ";", "return", "couchDbClient", ".", "get", "(", "URI", ".", "create", "(", "uri", ")", ",", "classType", ")", ";", "}" ]
This method finds any document given a URI. <p>The URI must be URI-encoded. @param classType The class of type T. @param uri The URI as string. @return An object of type T.
[ "This", "method", "finds", "any", "document", "given", "a", "URI", ".", "<p", ">", "The", "URI", "must", "be", "URI", "-", "encoded", "." ]
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L131-L135
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/cs/cspolicylabel_binding.java
cspolicylabel_binding.get
public static cspolicylabel_binding get(nitro_service service, String labelname) throws Exception { """ Use this API to fetch cspolicylabel_binding resource of given name . """ cspolicylabel_binding obj = new cspolicylabel_binding(); obj.set_labelname(labelname); cspolicylabel_binding response = (cspolicylabel_binding) obj.get_resource(service); return response; }
java
public static cspolicylabel_binding get(nitro_service service, String labelname) throws Exception{ cspolicylabel_binding obj = new cspolicylabel_binding(); obj.set_labelname(labelname); cspolicylabel_binding response = (cspolicylabel_binding) obj.get_resource(service); return response; }
[ "public", "static", "cspolicylabel_binding", "get", "(", "nitro_service", "service", ",", "String", "labelname", ")", "throws", "Exception", "{", "cspolicylabel_binding", "obj", "=", "new", "cspolicylabel_binding", "(", ")", ";", "obj", ".", "set_labelname", "(", "labelname", ")", ";", "cspolicylabel_binding", "response", "=", "(", "cspolicylabel_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch cspolicylabel_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "cspolicylabel_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/cs/cspolicylabel_binding.java#L103-L108
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdx_backup_restore.java
sdx_backup_restore.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> """ sdx_backup_restore_responses result = (sdx_backup_restore_responses) service.get_payload_formatter().string_to_resource(sdx_backup_restore_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.sdx_backup_restore_response_array); } sdx_backup_restore[] result_sdx_backup_restore = new sdx_backup_restore[result.sdx_backup_restore_response_array.length]; for(int i = 0; i < result.sdx_backup_restore_response_array.length; i++) { result_sdx_backup_restore[i] = result.sdx_backup_restore_response_array[i].sdx_backup_restore[0]; } return result_sdx_backup_restore; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sdx_backup_restore_responses result = (sdx_backup_restore_responses) service.get_payload_formatter().string_to_resource(sdx_backup_restore_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.sdx_backup_restore_response_array); } sdx_backup_restore[] result_sdx_backup_restore = new sdx_backup_restore[result.sdx_backup_restore_response_array.length]; for(int i = 0; i < result.sdx_backup_restore_response_array.length; i++) { result_sdx_backup_restore[i] = result.sdx_backup_restore_response_array[i].sdx_backup_restore[0]; } return result_sdx_backup_restore; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "sdx_backup_restore_responses", "result", "=", "(", "sdx_backup_restore_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "sdx_backup_restore_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", ".", "sdx_backup_restore_response_array", ")", ";", "}", "sdx_backup_restore", "[", "]", "result_sdx_backup_restore", "=", "new", "sdx_backup_restore", "[", "result", ".", "sdx_backup_restore_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "sdx_backup_restore_response_array", ".", "length", ";", "i", "++", ")", "{", "result_sdx_backup_restore", "[", "i", "]", "=", "result", ".", "sdx_backup_restore_response_array", "[", "i", "]", ".", "sdx_backup_restore", "[", "0", "]", ";", "}", "return", "result_sdx_backup_restore", ";", "}" ]
<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/sdx_backup_restore.java#L265-L282
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ValueDataUtil.java
ValueDataUtil.readValueData
public static ValueDataWrapper readValueData(int type, int orderNumber, File file, SpoolConfig spoolConfig) throws IOException { """ Read value data from file. @param type property type, {@link PropertyType} @param file File @param orderNumber value data order number @param spoolConfig contains threshold for spooling @return PersistedValueData @throws IOException if any error is occurred """ ValueDataWrapper vdDataWrapper = new ValueDataWrapper(); long fileSize = file.length(); vdDataWrapper.size = fileSize; if (fileSize > spoolConfig.maxBufferSize) { vdDataWrapper.value = new FilePersistedValueData(orderNumber, file, spoolConfig); } else { // JCR-2463 In case the file was renamed to be removed/changed, // but the transaction wasn't rollbacked cleanly file = fixFileName(file); FileInputStream is = new FileInputStream(file); try { byte[] data = new byte[(int)fileSize]; byte[] buff = new byte[ValueFileIOHelper.IOBUFFER_SIZE > fileSize ? ValueFileIOHelper.IOBUFFER_SIZE : (int)fileSize]; int rpos = 0; int read; while ((read = is.read(buff)) >= 0) { System.arraycopy(buff, 0, data, rpos, read); rpos += read; } vdDataWrapper.value = createValueData(type, orderNumber, data); } finally { is.close(); } } return vdDataWrapper; }
java
public static ValueDataWrapper readValueData(int type, int orderNumber, File file, SpoolConfig spoolConfig) throws IOException { ValueDataWrapper vdDataWrapper = new ValueDataWrapper(); long fileSize = file.length(); vdDataWrapper.size = fileSize; if (fileSize > spoolConfig.maxBufferSize) { vdDataWrapper.value = new FilePersistedValueData(orderNumber, file, spoolConfig); } else { // JCR-2463 In case the file was renamed to be removed/changed, // but the transaction wasn't rollbacked cleanly file = fixFileName(file); FileInputStream is = new FileInputStream(file); try { byte[] data = new byte[(int)fileSize]; byte[] buff = new byte[ValueFileIOHelper.IOBUFFER_SIZE > fileSize ? ValueFileIOHelper.IOBUFFER_SIZE : (int)fileSize]; int rpos = 0; int read; while ((read = is.read(buff)) >= 0) { System.arraycopy(buff, 0, data, rpos, read); rpos += read; } vdDataWrapper.value = createValueData(type, orderNumber, data); } finally { is.close(); } } return vdDataWrapper; }
[ "public", "static", "ValueDataWrapper", "readValueData", "(", "int", "type", ",", "int", "orderNumber", ",", "File", "file", ",", "SpoolConfig", "spoolConfig", ")", "throws", "IOException", "{", "ValueDataWrapper", "vdDataWrapper", "=", "new", "ValueDataWrapper", "(", ")", ";", "long", "fileSize", "=", "file", ".", "length", "(", ")", ";", "vdDataWrapper", ".", "size", "=", "fileSize", ";", "if", "(", "fileSize", ">", "spoolConfig", ".", "maxBufferSize", ")", "{", "vdDataWrapper", ".", "value", "=", "new", "FilePersistedValueData", "(", "orderNumber", ",", "file", ",", "spoolConfig", ")", ";", "}", "else", "{", "// JCR-2463 In case the file was renamed to be removed/changed,", "// but the transaction wasn't rollbacked cleanly", "file", "=", "fixFileName", "(", "file", ")", ";", "FileInputStream", "is", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "byte", "[", "]", "data", "=", "new", "byte", "[", "(", "int", ")", "fileSize", "]", ";", "byte", "[", "]", "buff", "=", "new", "byte", "[", "ValueFileIOHelper", ".", "IOBUFFER_SIZE", ">", "fileSize", "?", "ValueFileIOHelper", ".", "IOBUFFER_SIZE", ":", "(", "int", ")", "fileSize", "]", ";", "int", "rpos", "=", "0", ";", "int", "read", ";", "while", "(", "(", "read", "=", "is", ".", "read", "(", "buff", ")", ")", ">=", "0", ")", "{", "System", ".", "arraycopy", "(", "buff", ",", "0", ",", "data", ",", "rpos", ",", "read", ")", ";", "rpos", "+=", "read", ";", "}", "vdDataWrapper", ".", "value", "=", "createValueData", "(", "type", ",", "orderNumber", ",", "data", ")", ";", "}", "finally", "{", "is", ".", "close", "(", ")", ";", "}", "}", "return", "vdDataWrapper", ";", "}" ]
Read value data from file. @param type property type, {@link PropertyType} @param file File @param orderNumber value data order number @param spoolConfig contains threshold for spooling @return PersistedValueData @throws IOException if any error is occurred
[ "Read", "value", "data", "from", "file", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ValueDataUtil.java#L174-L216
MenoData/Time4J
base/src/main/java/net/time4j/engine/ChronoEntity.java
ChronoEntity.get
public final <R> R get(ChronoFunction<? super T, R> function) { """ /*[deutsch] <p>L&auml;&szlig;t die angegebene Abfrage diese Entit&auml;t auswerten. </p> <p>Entspricht {@code function.apply(this)}. Hier&uuml;ber wird der Vorgang der Zeitinterpretation externalisiert und erm&ouml;glicht so benutzerdefinierte Abfragen mit beliebigen Ergebnistypen. Anders als bei chronologischen Elementen ist hier nur ein Lesezugriff m&ouml;glich. In der Dokumentation der jeweiligen {@code ChronoFunction} ist nachzuschauen, ob diese Methode im Fall undefinierter Ergebnisse {@code null} zur&uuml;ckgibt oder eine Ausnahme wirft. </p> @param <R> generic type of result of query @param function time query @return result of query or {@code null} if undefined @throws ChronoException if the given query is not executable """ return function.apply(this.getContext()); }
java
public final <R> R get(ChronoFunction<? super T, R> function) { return function.apply(this.getContext()); }
[ "public", "final", "<", "R", ">", "R", "get", "(", "ChronoFunction", "<", "?", "super", "T", ",", "R", ">", "function", ")", "{", "return", "function", ".", "apply", "(", "this", ".", "getContext", "(", ")", ")", ";", "}" ]
/*[deutsch] <p>L&auml;&szlig;t die angegebene Abfrage diese Entit&auml;t auswerten. </p> <p>Entspricht {@code function.apply(this)}. Hier&uuml;ber wird der Vorgang der Zeitinterpretation externalisiert und erm&ouml;glicht so benutzerdefinierte Abfragen mit beliebigen Ergebnistypen. Anders als bei chronologischen Elementen ist hier nur ein Lesezugriff m&ouml;glich. In der Dokumentation der jeweiligen {@code ChronoFunction} ist nachzuschauen, ob diese Methode im Fall undefinierter Ergebnisse {@code null} zur&uuml;ckgibt oder eine Ausnahme wirft. </p> @param <R> generic type of result of query @param function time query @return result of query or {@code null} if undefined @throws ChronoException if the given query is not executable
[ "/", "*", "[", "deutsch", "]", "<p", ">", "L&auml", ";", "&szlig", ";", "t", "die", "angegebene", "Abfrage", "diese", "Entit&auml", ";", "t", "auswerten", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/engine/ChronoEntity.java#L154-L158
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatProvider.java
ChatProvider.deliverTell
public void deliverTell (UserMessage message, Name target, TellListener listener) throws InvocationException { """ Delivers a tell message to the specified target and notifies the supplied listener of the result. It is assumed that the teller has already been permissions checked. """ // make sure the target user is online BodyObject tobj = _locator.lookupBody(target); if (tobj == null) { // if we have a forwarder configured, try forwarding the tell if (_chatForwarder != null && _chatForwarder.forwardTell(message, target, listener)) { return; } throw new InvocationException(ChatCodes.USER_NOT_ONLINE); } if (tobj.status == OccupantInfo.DISCONNECTED) { String errmsg = MessageBundle.compose( ChatCodes.USER_DISCONNECTED, TimeUtil.getTimeOrderString( System.currentTimeMillis() - tobj.getLocal(BodyLocal.class).statusTime, TimeUtil.SECOND)); throw new InvocationException(errmsg); } // deliver a tell notification to the target player deliverTell(tobj, message); // let the teller know it went ok long idle = 0L; if (tobj.status == OccupantInfo.IDLE) { idle = System.currentTimeMillis() - tobj.getLocal(BodyLocal.class).statusTime; } String awayMessage = null; if (!StringUtil.isBlank(tobj.awayMessage)) { awayMessage = tobj.awayMessage; } listener.tellSucceeded(idle, awayMessage); }
java
public void deliverTell (UserMessage message, Name target, TellListener listener) throws InvocationException { // make sure the target user is online BodyObject tobj = _locator.lookupBody(target); if (tobj == null) { // if we have a forwarder configured, try forwarding the tell if (_chatForwarder != null && _chatForwarder.forwardTell(message, target, listener)) { return; } throw new InvocationException(ChatCodes.USER_NOT_ONLINE); } if (tobj.status == OccupantInfo.DISCONNECTED) { String errmsg = MessageBundle.compose( ChatCodes.USER_DISCONNECTED, TimeUtil.getTimeOrderString( System.currentTimeMillis() - tobj.getLocal(BodyLocal.class).statusTime, TimeUtil.SECOND)); throw new InvocationException(errmsg); } // deliver a tell notification to the target player deliverTell(tobj, message); // let the teller know it went ok long idle = 0L; if (tobj.status == OccupantInfo.IDLE) { idle = System.currentTimeMillis() - tobj.getLocal(BodyLocal.class).statusTime; } String awayMessage = null; if (!StringUtil.isBlank(tobj.awayMessage)) { awayMessage = tobj.awayMessage; } listener.tellSucceeded(idle, awayMessage); }
[ "public", "void", "deliverTell", "(", "UserMessage", "message", ",", "Name", "target", ",", "TellListener", "listener", ")", "throws", "InvocationException", "{", "// make sure the target user is online", "BodyObject", "tobj", "=", "_locator", ".", "lookupBody", "(", "target", ")", ";", "if", "(", "tobj", "==", "null", ")", "{", "// if we have a forwarder configured, try forwarding the tell", "if", "(", "_chatForwarder", "!=", "null", "&&", "_chatForwarder", ".", "forwardTell", "(", "message", ",", "target", ",", "listener", ")", ")", "{", "return", ";", "}", "throw", "new", "InvocationException", "(", "ChatCodes", ".", "USER_NOT_ONLINE", ")", ";", "}", "if", "(", "tobj", ".", "status", "==", "OccupantInfo", ".", "DISCONNECTED", ")", "{", "String", "errmsg", "=", "MessageBundle", ".", "compose", "(", "ChatCodes", ".", "USER_DISCONNECTED", ",", "TimeUtil", ".", "getTimeOrderString", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "tobj", ".", "getLocal", "(", "BodyLocal", ".", "class", ")", ".", "statusTime", ",", "TimeUtil", ".", "SECOND", ")", ")", ";", "throw", "new", "InvocationException", "(", "errmsg", ")", ";", "}", "// deliver a tell notification to the target player", "deliverTell", "(", "tobj", ",", "message", ")", ";", "// let the teller know it went ok", "long", "idle", "=", "0L", ";", "if", "(", "tobj", ".", "status", "==", "OccupantInfo", ".", "IDLE", ")", "{", "idle", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "tobj", ".", "getLocal", "(", "BodyLocal", ".", "class", ")", ".", "statusTime", ";", "}", "String", "awayMessage", "=", "null", ";", "if", "(", "!", "StringUtil", ".", "isBlank", "(", "tobj", ".", "awayMessage", ")", ")", "{", "awayMessage", "=", "tobj", ".", "awayMessage", ";", "}", "listener", ".", "tellSucceeded", "(", "idle", ",", "awayMessage", ")", ";", "}" ]
Delivers a tell message to the specified target and notifies the supplied listener of the result. It is assumed that the teller has already been permissions checked.
[ "Delivers", "a", "tell", "message", "to", "the", "specified", "target", "and", "notifies", "the", "supplied", "listener", "of", "the", "result", ".", "It", "is", "assumed", "that", "the", "teller", "has", "already", "been", "permissions", "checked", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatProvider.java#L220-L254
markkent/serial-executor-service
src/main/java/org/logicalshift/concurrent/SerialScheduledExecutorService.java
SerialScheduledExecutorService.elapseTime
public void elapseTime(long quantum, TimeUnit timeUnit) { """ Advance time by the given quantum. <p/> Scheduled tasks due for execution will be executed in the caller's thread. @param quantum the amount of time to advance @param timeUnit the unit of the quantum amount """ Preconditions.checkArgument(quantum > 0, "Time quantum must be a positive number"); Preconditions.checkState(!isShutdown, "Trying to elapse time after shutdown"); elapseTime(toNanos(quantum, timeUnit), ticker); }
java
public void elapseTime(long quantum, TimeUnit timeUnit) { Preconditions.checkArgument(quantum > 0, "Time quantum must be a positive number"); Preconditions.checkState(!isShutdown, "Trying to elapse time after shutdown"); elapseTime(toNanos(quantum, timeUnit), ticker); }
[ "public", "void", "elapseTime", "(", "long", "quantum", ",", "TimeUnit", "timeUnit", ")", "{", "Preconditions", ".", "checkArgument", "(", "quantum", ">", "0", ",", "\"Time quantum must be a positive number\"", ")", ";", "Preconditions", ".", "checkState", "(", "!", "isShutdown", ",", "\"Trying to elapse time after shutdown\"", ")", ";", "elapseTime", "(", "toNanos", "(", "quantum", ",", "timeUnit", ")", ",", "ticker", ")", ";", "}" ]
Advance time by the given quantum. <p/> Scheduled tasks due for execution will be executed in the caller's thread. @param quantum the amount of time to advance @param timeUnit the unit of the quantum amount
[ "Advance", "time", "by", "the", "given", "quantum", ".", "<p", "/", ">", "Scheduled", "tasks", "due", "for", "execution", "will", "be", "executed", "in", "the", "caller", "s", "thread", "." ]
train
https://github.com/markkent/serial-executor-service/blob/64de38c26f0f6f0148b1eb384b69474e3576879c/src/main/java/org/logicalshift/concurrent/SerialScheduledExecutorService.java#L191-L197
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java
ExpressRoutePortsInner.beginDelete
public void beginDelete(String resourceGroupName, String expressRoutePortName) { """ Deletes the specified ExpressRoutePort resource. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ beginDeleteWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().single().body(); }
java
public void beginDelete(String resourceGroupName, String expressRoutePortName) { beginDeleteWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().single().body(); }
[ "public", "void", "beginDelete", "(", "String", "resourceGroupName", ",", "String", "expressRoutePortName", ")", "{", "beginDeleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "expressRoutePortName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Deletes the specified ExpressRoutePort resource. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Deletes", "the", "specified", "ExpressRoutePort", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java#L191-L193
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java
JpaSystemManagement.createInitialTenantMetaData
private TenantMetaData createInitialTenantMetaData(final String tenant) { """ Creating the initial tenant meta-data in a new transaction. Due the {@link MultiTenantJpaTransactionManager} is using the current tenant to set the necessary tenant discriminator to the query. This is not working if we don't have a current tenant set. Due the {@link #getTenantMetadata(String)} is maybe called without having a current tenant we need to re-open a new transaction so the {@link MultiTenantJpaTransactionManager} is called again and set the tenant for this transaction. @param tenant the tenant to be created @return the initial created {@link TenantMetaData} """ return systemSecurityContext.runAsSystemAsTenant( () -> DeploymentHelper.runInNewTransaction(txManager, "initial-tenant-creation", status -> { final DistributionSetType defaultDsType = createStandardSoftwareDataSetup(); return tenantMetaDataRepository.save(new JpaTenantMetaData(defaultDsType, tenant)); }), tenant); }
java
private TenantMetaData createInitialTenantMetaData(final String tenant) { return systemSecurityContext.runAsSystemAsTenant( () -> DeploymentHelper.runInNewTransaction(txManager, "initial-tenant-creation", status -> { final DistributionSetType defaultDsType = createStandardSoftwareDataSetup(); return tenantMetaDataRepository.save(new JpaTenantMetaData(defaultDsType, tenant)); }), tenant); }
[ "private", "TenantMetaData", "createInitialTenantMetaData", "(", "final", "String", "tenant", ")", "{", "return", "systemSecurityContext", ".", "runAsSystemAsTenant", "(", "(", ")", "->", "DeploymentHelper", ".", "runInNewTransaction", "(", "txManager", ",", "\"initial-tenant-creation\"", ",", "status", "->", "{", "final", "DistributionSetType", "defaultDsType", "=", "createStandardSoftwareDataSetup", "(", ")", ";", "return", "tenantMetaDataRepository", ".", "save", "(", "new", "JpaTenantMetaData", "(", "defaultDsType", ",", "tenant", ")", ")", ";", "}", ")", ",", "tenant", ")", ";", "}" ]
Creating the initial tenant meta-data in a new transaction. Due the {@link MultiTenantJpaTransactionManager} is using the current tenant to set the necessary tenant discriminator to the query. This is not working if we don't have a current tenant set. Due the {@link #getTenantMetadata(String)} is maybe called without having a current tenant we need to re-open a new transaction so the {@link MultiTenantJpaTransactionManager} is called again and set the tenant for this transaction. @param tenant the tenant to be created @return the initial created {@link TenantMetaData}
[ "Creating", "the", "initial", "tenant", "meta", "-", "data", "in", "a", "new", "transaction", ".", "Due", "the", "{", "@link", "MultiTenantJpaTransactionManager", "}", "is", "using", "the", "current", "tenant", "to", "set", "the", "necessary", "tenant", "discriminator", "to", "the", "query", ".", "This", "is", "not", "working", "if", "we", "don", "t", "have", "a", "current", "tenant", "set", ".", "Due", "the", "{", "@link", "#getTenantMetadata", "(", "String", ")", "}", "is", "maybe", "called", "without", "having", "a", "current", "tenant", "we", "need", "to", "re", "-", "open", "a", "new", "transaction", "so", "the", "{", "@link", "MultiTenantJpaTransactionManager", "}", "is", "called", "again", "and", "set", "the", "tenant", "for", "this", "transaction", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java#L208-L214
Whiley/WhileyCompiler
src/main/java/wyil/transform/VerificationConditionGenerator.java
VerificationConditionGenerator.translateAssert
private Context translateAssert(WyilFile.Stmt.Assert stmt, Context context) { """ Translate an assert statement. This emits a verification condition which ensures the assert condition holds, given the current context. @param stmt @param wyalFile """ Pair<Expr, Context> p = translateExpressionWithChecks(stmt.getCondition(), null, context); Expr condition = p.first(); context = p.second(); // VerificationCondition verificationCondition = new VerificationCondition("assertion failed", context.assumptions, condition, stmt.getCondition().getParent(WyilFile.Attribute.Span.class)); context.emit(verificationCondition); // return context.assume(condition); }
java
private Context translateAssert(WyilFile.Stmt.Assert stmt, Context context) { Pair<Expr, Context> p = translateExpressionWithChecks(stmt.getCondition(), null, context); Expr condition = p.first(); context = p.second(); // VerificationCondition verificationCondition = new VerificationCondition("assertion failed", context.assumptions, condition, stmt.getCondition().getParent(WyilFile.Attribute.Span.class)); context.emit(verificationCondition); // return context.assume(condition); }
[ "private", "Context", "translateAssert", "(", "WyilFile", ".", "Stmt", ".", "Assert", "stmt", ",", "Context", "context", ")", "{", "Pair", "<", "Expr", ",", "Context", ">", "p", "=", "translateExpressionWithChecks", "(", "stmt", ".", "getCondition", "(", ")", ",", "null", ",", "context", ")", ";", "Expr", "condition", "=", "p", ".", "first", "(", ")", ";", "context", "=", "p", ".", "second", "(", ")", ";", "//", "VerificationCondition", "verificationCondition", "=", "new", "VerificationCondition", "(", "\"assertion failed\"", ",", "context", ".", "assumptions", ",", "condition", ",", "stmt", ".", "getCondition", "(", ")", ".", "getParent", "(", "WyilFile", ".", "Attribute", ".", "Span", ".", "class", ")", ")", ";", "context", ".", "emit", "(", "verificationCondition", ")", ";", "//", "return", "context", ".", "assume", "(", "condition", ")", ";", "}" ]
Translate an assert statement. This emits a verification condition which ensures the assert condition holds, given the current context. @param stmt @param wyalFile
[ "Translate", "an", "assert", "statement", ".", "This", "emits", "a", "verification", "condition", "which", "ensures", "the", "assert", "condition", "holds", "given", "the", "current", "context", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L474-L484
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fs/command/ChgrpCommand.java
ChgrpCommand.chgrp
private void chgrp(AlluxioURI path, String group, boolean recursive) throws AlluxioException, IOException { """ Changes the group for the directory or file with the path specified in args. @param path The {@link AlluxioURI} path as the input of the command @param group The group to be updated to the file or directory @param recursive Whether change the group recursively """ SetAttributePOptions options = SetAttributePOptions.newBuilder().setGroup(group).setRecursive(recursive).build(); mFileSystem.setAttribute(path, options); System.out.println("Changed group of " + path + " to " + group); }
java
private void chgrp(AlluxioURI path, String group, boolean recursive) throws AlluxioException, IOException { SetAttributePOptions options = SetAttributePOptions.newBuilder().setGroup(group).setRecursive(recursive).build(); mFileSystem.setAttribute(path, options); System.out.println("Changed group of " + path + " to " + group); }
[ "private", "void", "chgrp", "(", "AlluxioURI", "path", ",", "String", "group", ",", "boolean", "recursive", ")", "throws", "AlluxioException", ",", "IOException", "{", "SetAttributePOptions", "options", "=", "SetAttributePOptions", ".", "newBuilder", "(", ")", ".", "setGroup", "(", "group", ")", ".", "setRecursive", "(", "recursive", ")", ".", "build", "(", ")", ";", "mFileSystem", ".", "setAttribute", "(", "path", ",", "options", ")", ";", "System", ".", "out", ".", "println", "(", "\"Changed group of \"", "+", "path", "+", "\" to \"", "+", "group", ")", ";", "}" ]
Changes the group for the directory or file with the path specified in args. @param path The {@link AlluxioURI} path as the input of the command @param group The group to be updated to the file or directory @param recursive Whether change the group recursively
[ "Changes", "the", "group", "for", "the", "directory", "or", "file", "with", "the", "path", "specified", "in", "args", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/ChgrpCommand.java#L74-L80
ben-manes/caffeine
jcache/src/main/java/com/github/benmanes/caffeine/jcache/copy/AbstractCopier.java
AbstractCopier.roundtrip
protected <T> T roundtrip(T object, ClassLoader classLoader) { """ Performs the serialization and deserialization, returning the copied object. @param object the object to serialize @param classLoader the classloader to create the instance with @param <T> the type of object being copied @return the deserialized object """ A data = serialize(object); @SuppressWarnings("unchecked") T copy = (T) deserialize(data, classLoader); return copy; }
java
protected <T> T roundtrip(T object, ClassLoader classLoader) { A data = serialize(object); @SuppressWarnings("unchecked") T copy = (T) deserialize(data, classLoader); return copy; }
[ "protected", "<", "T", ">", "T", "roundtrip", "(", "T", "object", ",", "ClassLoader", "classLoader", ")", "{", "A", "data", "=", "serialize", "(", "object", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "T", "copy", "=", "(", "T", ")", "deserialize", "(", "data", ",", "classLoader", ")", ";", "return", "copy", ";", "}" ]
Performs the serialization and deserialization, returning the copied object. @param object the object to serialize @param classLoader the classloader to create the instance with @param <T> the type of object being copied @return the deserialized object
[ "Performs", "the", "serialization", "and", "deserialization", "returning", "the", "copied", "object", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/jcache/src/main/java/com/github/benmanes/caffeine/jcache/copy/AbstractCopier.java#L159-L164
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java
AbstractExecutableMemberWriter.addInheritedSummaryLink
@Override protected void addInheritedSummaryLink(TypeElement te, Element member, Content linksTree) { """ Add the inherited summary link for the member. @param te the type element that we should link to @param member the member being linked to @param linksTree the content tree to which the link will be added """ linksTree.addContent(writer.getDocLink(MEMBER, te, member, name(member), false)); }
java
@Override protected void addInheritedSummaryLink(TypeElement te, Element member, Content linksTree) { linksTree.addContent(writer.getDocLink(MEMBER, te, member, name(member), false)); }
[ "@", "Override", "protected", "void", "addInheritedSummaryLink", "(", "TypeElement", "te", ",", "Element", "member", ",", "Content", "linksTree", ")", "{", "linksTree", ".", "addContent", "(", "writer", ".", "getDocLink", "(", "MEMBER", ",", "te", ",", "member", ",", "name", "(", "member", ")", ",", "false", ")", ")", ";", "}" ]
Add the inherited summary link for the member. @param te the type element that we should link to @param member the member being linked to @param linksTree the content tree to which the link will be added
[ "Add", "the", "inherited", "summary", "link", "for", "the", "member", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java#L139-L142
menacher/java-game-server
jetserver/src/main/java/org/menacheri/jetserver/util/NettyUtils.java
NettyUtils.readString
public static String readString(ChannelBuffer buffer, int length) { """ Read a string from a channel buffer with the specified length. It resets the reader index of the buffer to the end of the string. @param buffer The Netty buffer containing the String. @param length The number of bytes in the String. @return Returns the read string. """ return readString(buffer, length, CharsetUtil.UTF_8); // char[] chars = new char[length]; // for (int i = 0; i < length; i++) // { // chars[i] = buffer.readChar(); // } // return new String(chars); }
java
public static String readString(ChannelBuffer buffer, int length) { return readString(buffer, length, CharsetUtil.UTF_8); // char[] chars = new char[length]; // for (int i = 0; i < length; i++) // { // chars[i] = buffer.readChar(); // } // return new String(chars); }
[ "public", "static", "String", "readString", "(", "ChannelBuffer", "buffer", ",", "int", "length", ")", "{", "return", "readString", "(", "buffer", ",", "length", ",", "CharsetUtil", ".", "UTF_8", ")", ";", "//\t\tchar[] chars = new char[length];", "//\t\tfor (int i = 0; i < length; i++)", "//\t\t{", "//\t\t\tchars[i] = buffer.readChar();", "//\t\t}", "//\t\treturn new String(chars);", "}" ]
Read a string from a channel buffer with the specified length. It resets the reader index of the buffer to the end of the string. @param buffer The Netty buffer containing the String. @param length The number of bytes in the String. @return Returns the read string.
[ "Read", "a", "string", "from", "a", "channel", "buffer", "with", "the", "specified", "length", ".", "It", "resets", "the", "reader", "index", "of", "the", "buffer", "to", "the", "end", "of", "the", "string", "." ]
train
https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetserver/src/main/java/org/menacheri/jetserver/util/NettyUtils.java#L183-L193
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsWidgetUtil.java
CmsWidgetUtil.getStringOption
public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) { """ Returns the value of an option, or the default if the value is null or the key is not part of the map. @param configOptions the map with the config options. @param optionKey the option to get the value of @param defaultValue the default value to return if the option is not set. @return the value of an option, or the default if the value is null or the key is not part of the map. """ String result = configOptions.get(optionKey); return null != result ? result : defaultValue; }
java
public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) { String result = configOptions.get(optionKey); return null != result ? result : defaultValue; }
[ "public", "static", "String", "getStringOption", "(", "Map", "<", "String", ",", "String", ">", "configOptions", ",", "String", "optionKey", ",", "String", "defaultValue", ")", "{", "String", "result", "=", "configOptions", ".", "get", "(", "optionKey", ")", ";", "return", "null", "!=", "result", "?", "result", ":", "defaultValue", ";", "}" ]
Returns the value of an option, or the default if the value is null or the key is not part of the map. @param configOptions the map with the config options. @param optionKey the option to get the value of @param defaultValue the default value to return if the option is not set. @return the value of an option, or the default if the value is null or the key is not part of the map.
[ "Returns", "the", "value", "of", "an", "option", "or", "the", "default", "if", "the", "value", "is", "null", "or", "the", "key", "is", "not", "part", "of", "the", "map", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsWidgetUtil.java#L82-L86
podio/podio-java
src/main/java/com/podio/task/TaskAPI.java
TaskAPI.createTaskWithReference
public int createTaskWithReference(TaskCreate task, Reference reference, boolean silent) { """ Creates a new task with a reference to the given object. @param task The data of the task to be created @param reference The reference to the object the task should be attached to @param silent Disable notifications @return The id of the newly created task """ return createTaskWithReference(task, reference, silent, true); }
java
public int createTaskWithReference(TaskCreate task, Reference reference, boolean silent) { return createTaskWithReference(task, reference, silent, true); }
[ "public", "int", "createTaskWithReference", "(", "TaskCreate", "task", ",", "Reference", "reference", ",", "boolean", "silent", ")", "{", "return", "createTaskWithReference", "(", "task", ",", "reference", ",", "silent", ",", "true", ")", ";", "}" ]
Creates a new task with a reference to the given object. @param task The data of the task to be created @param reference The reference to the object the task should be attached to @param silent Disable notifications @return The id of the newly created task
[ "Creates", "a", "new", "task", "with", "a", "reference", "to", "the", "given", "object", "." ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/task/TaskAPI.java#L196-L199
GoogleCloudPlatform/bigdata-interop
util/src/main/java/com/google/cloud/hadoop/util/ResilientOperation.java
ResilientOperation.nextSleep
private static boolean nextSleep(BackOff backoff, Sleeper sleeper, Exception currentException) throws InterruptedException { """ Determines the amount to sleep for and sleeps if needed. @param backoff BackOff to determine how long to sleep for @param sleeper Used to sleep @param currentException exception that caused the retry and sleep. For logging. @throws InterruptedException if sleep is interrupted """ long backOffTime; try { backOffTime = backoff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException("Failed to to get next back off time", e); } if (backOffTime == BackOff.STOP) { return false; } logger.atInfo().withCause(currentException).log( "Transient exception caught. Sleeping for %d, then retrying.", backOffTime); sleeper.sleep(backOffTime); return true; }
java
private static boolean nextSleep(BackOff backoff, Sleeper sleeper, Exception currentException) throws InterruptedException { long backOffTime; try { backOffTime = backoff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException("Failed to to get next back off time", e); } if (backOffTime == BackOff.STOP) { return false; } logger.atInfo().withCause(currentException).log( "Transient exception caught. Sleeping for %d, then retrying.", backOffTime); sleeper.sleep(backOffTime); return true; }
[ "private", "static", "boolean", "nextSleep", "(", "BackOff", "backoff", ",", "Sleeper", "sleeper", ",", "Exception", "currentException", ")", "throws", "InterruptedException", "{", "long", "backOffTime", ";", "try", "{", "backOffTime", "=", "backoff", ".", "nextBackOffMillis", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to to get next back off time\"", ",", "e", ")", ";", "}", "if", "(", "backOffTime", "==", "BackOff", ".", "STOP", ")", "{", "return", "false", ";", "}", "logger", ".", "atInfo", "(", ")", ".", "withCause", "(", "currentException", ")", ".", "log", "(", "\"Transient exception caught. Sleeping for %d, then retrying.\"", ",", "backOffTime", ")", ";", "sleeper", ".", "sleep", "(", "backOffTime", ")", ";", "return", "true", ";", "}" ]
Determines the amount to sleep for and sleeps if needed. @param backoff BackOff to determine how long to sleep for @param sleeper Used to sleep @param currentException exception that caused the retry and sleep. For logging. @throws InterruptedException if sleep is interrupted
[ "Determines", "the", "amount", "to", "sleep", "for", "and", "sleeps", "if", "needed", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/util/src/main/java/com/google/cloud/hadoop/util/ResilientOperation.java#L117-L132
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.getReader
public static BufferedReader getReader(String path, Charset charset) throws IORuntimeException { """ 获得一个文件读取器 @param path 绝对路径 @param charset 字符集 @return BufferedReader对象 @throws IORuntimeException IO异常 """ return getReader(file(path), charset); }
java
public static BufferedReader getReader(String path, Charset charset) throws IORuntimeException { return getReader(file(path), charset); }
[ "public", "static", "BufferedReader", "getReader", "(", "String", "path", ",", "Charset", "charset", ")", "throws", "IORuntimeException", "{", "return", "getReader", "(", "file", "(", "path", ")", ",", "charset", ")", ";", "}" ]
获得一个文件读取器 @param path 绝对路径 @param charset 字符集 @return BufferedReader对象 @throws IORuntimeException IO异常
[ "获得一个文件读取器" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2029-L2031
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.toInputStream
public static InputStream toInputStream(String str, Charset charset) { """ Turns a {@code String} into an {@code InputStream} containing the string's encoded characters. @param str the string @param charset the {@link Charset} to use when encoding the string. @return an {@link InputStream} containing the string's encoded characters. """ return new ByteArrayInputStream(str.getBytes(charset)); }
java
public static InputStream toInputStream(String str, Charset charset) { return new ByteArrayInputStream(str.getBytes(charset)); }
[ "public", "static", "InputStream", "toInputStream", "(", "String", "str", ",", "Charset", "charset", ")", "{", "return", "new", "ByteArrayInputStream", "(", "str", ".", "getBytes", "(", "charset", ")", ")", ";", "}" ]
Turns a {@code String} into an {@code InputStream} containing the string's encoded characters. @param str the string @param charset the {@link Charset} to use when encoding the string. @return an {@link InputStream} containing the string's encoded characters.
[ "Turns", "a", "{", "@code", "String", "}", "into", "an", "{", "@code", "InputStream", "}", "containing", "the", "string", "s", "encoded", "characters", "." ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L767-L769
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.partValue
public static int partValue(int total, int partCount, boolean isPlusOneWhenHasRem) { """ 把给定的总数平均分成N份,返回每份的个数<br> 如果isPlusOneWhenHasRem为true,则当除以分数有余数时每份+1,否则丢弃余数部分 @param total 总数 @param partCount 份数 @param isPlusOneWhenHasRem 在有余数时是否每份+1 @return 每份的个数 @since 4.0.7 """ int partValue = 0; if (total % partCount == 0) { partValue = total / partCount; } else { partValue = (int) Math.floor(total / partCount); if (isPlusOneWhenHasRem) { partValue += 1; } } return partValue; }
java
public static int partValue(int total, int partCount, boolean isPlusOneWhenHasRem) { int partValue = 0; if (total % partCount == 0) { partValue = total / partCount; } else { partValue = (int) Math.floor(total / partCount); if (isPlusOneWhenHasRem) { partValue += 1; } } return partValue; }
[ "public", "static", "int", "partValue", "(", "int", "total", ",", "int", "partCount", ",", "boolean", "isPlusOneWhenHasRem", ")", "{", "int", "partValue", "=", "0", ";", "if", "(", "total", "%", "partCount", "==", "0", ")", "{", "partValue", "=", "total", "/", "partCount", ";", "}", "else", "{", "partValue", "=", "(", "int", ")", "Math", ".", "floor", "(", "total", "/", "partCount", ")", ";", "if", "(", "isPlusOneWhenHasRem", ")", "{", "partValue", "+=", "1", ";", "}", "}", "return", "partValue", ";", "}" ]
把给定的总数平均分成N份,返回每份的个数<br> 如果isPlusOneWhenHasRem为true,则当除以分数有余数时每份+1,否则丢弃余数部分 @param total 总数 @param partCount 份数 @param isPlusOneWhenHasRem 在有余数时是否每份+1 @return 每份的个数 @since 4.0.7
[ "把给定的总数平均分成N份,返回每份的个数<br", ">", "如果isPlusOneWhenHasRem为true,则当除以分数有余数时每份", "+", "1,否则丢弃余数部分" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L2072-L2083
jeremylong/DependencyCheck
cli/src/main/java/org/owasp/dependencycheck/CliParser.java
CliParser.hasDisableOption
private boolean hasDisableOption(String argument, String setting) { """ Utility method to determine if one of the disable options has been set. If not set, this method will check the currently configured settings for the current value to return. Example given `--disableArchive` on the command line would cause this method to return true for the disable archive setting. @param argument the command line argument @param setting the corresponding settings key @return true if the disable option was set, if not set the currently configured value will be returned """ if (line == null || !line.hasOption(argument)) { try { return !settings.getBoolean(setting); } catch (InvalidSettingException ise) { LOGGER.warn("Invalid property setting '{}' defaulting to false", setting); return false; } } else { return true; } }
java
private boolean hasDisableOption(String argument, String setting) { if (line == null || !line.hasOption(argument)) { try { return !settings.getBoolean(setting); } catch (InvalidSettingException ise) { LOGGER.warn("Invalid property setting '{}' defaulting to false", setting); return false; } } else { return true; } }
[ "private", "boolean", "hasDisableOption", "(", "String", "argument", ",", "String", "setting", ")", "{", "if", "(", "line", "==", "null", "||", "!", "line", ".", "hasOption", "(", "argument", ")", ")", "{", "try", "{", "return", "!", "settings", ".", "getBoolean", "(", "setting", ")", ";", "}", "catch", "(", "InvalidSettingException", "ise", ")", "{", "LOGGER", ".", "warn", "(", "\"Invalid property setting '{}' defaulting to false\"", ",", "setting", ")", ";", "return", "false", ";", "}", "}", "else", "{", "return", "true", ";", "}", "}" ]
Utility method to determine if one of the disable options has been set. If not set, this method will check the currently configured settings for the current value to return. Example given `--disableArchive` on the command line would cause this method to return true for the disable archive setting. @param argument the command line argument @param setting the corresponding settings key @return true if the disable option was set, if not set the currently configured value will be returned
[ "Utility", "method", "to", "determine", "if", "one", "of", "the", "disable", "options", "has", "been", "set", ".", "If", "not", "set", "this", "method", "will", "check", "the", "currently", "configured", "settings", "for", "the", "current", "value", "to", "return", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/cli/src/main/java/org/owasp/dependencycheck/CliParser.java#L589-L600
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/AnycastOutputHandler.java
AnycastOutputHandler.streamIsFlushed
public final void streamIsFlushed(AOStream stream) { """ Callback from a stream, that it has been flushed @param stream """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "streamIsFlushed", stream); // we schedule an asynchronous removal of the persistent data synchronized (streamTable) { String key = SIMPUtils.getRemoteGetKey(stream.getRemoteMEUuid(), stream.getGatheringTargetDestUuid()); StreamInfo sinfo = streamTable.get(key); if ((sinfo != null) && sinfo.streamId.equals(stream.streamId)) { RemovePersistentStream update = null; synchronized (sinfo) { // synchronized since reading sinfo.item update = new RemovePersistentStream(key, sinfo.streamId, sinfo.itemStream, sinfo.item); } doEnqueueWork(update); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "streamIsFlushed"); }
java
public final void streamIsFlushed(AOStream stream) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "streamIsFlushed", stream); // we schedule an asynchronous removal of the persistent data synchronized (streamTable) { String key = SIMPUtils.getRemoteGetKey(stream.getRemoteMEUuid(), stream.getGatheringTargetDestUuid()); StreamInfo sinfo = streamTable.get(key); if ((sinfo != null) && sinfo.streamId.equals(stream.streamId)) { RemovePersistentStream update = null; synchronized (sinfo) { // synchronized since reading sinfo.item update = new RemovePersistentStream(key, sinfo.streamId, sinfo.itemStream, sinfo.item); } doEnqueueWork(update); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "streamIsFlushed"); }
[ "public", "final", "void", "streamIsFlushed", "(", "AOStream", "stream", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"streamIsFlushed\"", ",", "stream", ")", ";", "// we schedule an asynchronous removal of the persistent data", "synchronized", "(", "streamTable", ")", "{", "String", "key", "=", "SIMPUtils", ".", "getRemoteGetKey", "(", "stream", ".", "getRemoteMEUuid", "(", ")", ",", "stream", ".", "getGatheringTargetDestUuid", "(", ")", ")", ";", "StreamInfo", "sinfo", "=", "streamTable", ".", "get", "(", "key", ")", ";", "if", "(", "(", "sinfo", "!=", "null", ")", "&&", "sinfo", ".", "streamId", ".", "equals", "(", "stream", ".", "streamId", ")", ")", "{", "RemovePersistentStream", "update", "=", "null", ";", "synchronized", "(", "sinfo", ")", "{", "// synchronized since reading sinfo.item", "update", "=", "new", "RemovePersistentStream", "(", "key", ",", "sinfo", ".", "streamId", ",", "sinfo", ".", "itemStream", ",", "sinfo", ".", "item", ")", ";", "}", "doEnqueueWork", "(", "update", ")", ";", "}", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"streamIsFlushed\"", ")", ";", "}" ]
Callback from a stream, that it has been flushed @param stream
[ "Callback", "from", "a", "stream", "that", "it", "has", "been", "flushed" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/AnycastOutputHandler.java#L1963-L1986
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/TextBox.java
TextBox.copyTextBox
public TextBox copyTextBox() { """ Create a new box from the same DOM node in the same context @return the new TextBox """ TextBox ret = new TextBox(textNode, g, ctx); ret.copyValues(this); return ret; }
java
public TextBox copyTextBox() { TextBox ret = new TextBox(textNode, g, ctx); ret.copyValues(this); return ret; }
[ "public", "TextBox", "copyTextBox", "(", ")", "{", "TextBox", "ret", "=", "new", "TextBox", "(", "textNode", ",", "g", ",", "ctx", ")", ";", "ret", ".", "copyValues", "(", "this", ")", ";", "return", "ret", ";", "}" ]
Create a new box from the same DOM node in the same context @return the new TextBox
[ "Create", "a", "new", "box", "from", "the", "same", "DOM", "node", "in", "the", "same", "context" ]
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/TextBox.java#L156-L161
apache/spark
common/network-common/src/main/java/org/apache/spark/network/client/TransportClient.java
TransportClient.fetchChunk
public void fetchChunk( long streamId, int chunkIndex, ChunkReceivedCallback callback) { """ Requests a single chunk from the remote side, from the pre-negotiated streamId. Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though some streams may not support this. Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed to be returned in the same order that they were requested, assuming only a single TransportClient is used to fetch the chunks. @param streamId Identifier that refers to a stream in the remote StreamManager. This should be agreed upon by client and server beforehand. @param chunkIndex 0-based index of the chunk to fetch @param callback Callback invoked upon successful receipt of chunk, or upon any failure. """ if (logger.isDebugEnabled()) { logger.debug("Sending fetch chunk request {} to {}", chunkIndex, getRemoteAddress(channel)); } StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex); StdChannelListener listener = new StdChannelListener(streamChunkId) { @Override void handleFailure(String errorMsg, Throwable cause) { handler.removeFetchRequest(streamChunkId); callback.onFailure(chunkIndex, new IOException(errorMsg, cause)); } }; handler.addFetchRequest(streamChunkId, callback); channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(listener); }
java
public void fetchChunk( long streamId, int chunkIndex, ChunkReceivedCallback callback) { if (logger.isDebugEnabled()) { logger.debug("Sending fetch chunk request {} to {}", chunkIndex, getRemoteAddress(channel)); } StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex); StdChannelListener listener = new StdChannelListener(streamChunkId) { @Override void handleFailure(String errorMsg, Throwable cause) { handler.removeFetchRequest(streamChunkId); callback.onFailure(chunkIndex, new IOException(errorMsg, cause)); } }; handler.addFetchRequest(streamChunkId, callback); channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(listener); }
[ "public", "void", "fetchChunk", "(", "long", "streamId", ",", "int", "chunkIndex", ",", "ChunkReceivedCallback", "callback", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Sending fetch chunk request {} to {}\"", ",", "chunkIndex", ",", "getRemoteAddress", "(", "channel", ")", ")", ";", "}", "StreamChunkId", "streamChunkId", "=", "new", "StreamChunkId", "(", "streamId", ",", "chunkIndex", ")", ";", "StdChannelListener", "listener", "=", "new", "StdChannelListener", "(", "streamChunkId", ")", "{", "@", "Override", "void", "handleFailure", "(", "String", "errorMsg", ",", "Throwable", "cause", ")", "{", "handler", ".", "removeFetchRequest", "(", "streamChunkId", ")", ";", "callback", ".", "onFailure", "(", "chunkIndex", ",", "new", "IOException", "(", "errorMsg", ",", "cause", ")", ")", ";", "}", "}", ";", "handler", ".", "addFetchRequest", "(", "streamChunkId", ",", "callback", ")", ";", "channel", ".", "writeAndFlush", "(", "new", "ChunkFetchRequest", "(", "streamChunkId", ")", ")", ".", "addListener", "(", "listener", ")", ";", "}" ]
Requests a single chunk from the remote side, from the pre-negotiated streamId. Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though some streams may not support this. Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed to be returned in the same order that they were requested, assuming only a single TransportClient is used to fetch the chunks. @param streamId Identifier that refers to a stream in the remote StreamManager. This should be agreed upon by client and server beforehand. @param chunkIndex 0-based index of the chunk to fetch @param callback Callback invoked upon successful receipt of chunk, or upon any failure.
[ "Requests", "a", "single", "chunk", "from", "the", "remote", "side", "from", "the", "pre", "-", "negotiated", "streamId", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/client/TransportClient.java#L132-L151
podio/podio-java
src/main/java/com/podio/item/ItemAPI.java
ItemAPI.addItem
public int addItem(int appId, ItemCreate create, boolean silent) { """ Adds a new item to the given app. @param appId The id of the app the item should be added to @param create The data for the new item @param silent True if the create should be silten, false otherwise @return The id of the newly created item """ return getResourceFactory().getApiResource("/item/app/" + appId + "/") .queryParam("silent", silent ? "1" : "0") .entity(create, MediaType.APPLICATION_JSON_TYPE) .post(ItemCreateResponse.class).getId(); }
java
public int addItem(int appId, ItemCreate create, boolean silent) { return getResourceFactory().getApiResource("/item/app/" + appId + "/") .queryParam("silent", silent ? "1" : "0") .entity(create, MediaType.APPLICATION_JSON_TYPE) .post(ItemCreateResponse.class).getId(); }
[ "public", "int", "addItem", "(", "int", "appId", ",", "ItemCreate", "create", ",", "boolean", "silent", ")", "{", "return", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/item/app/\"", "+", "appId", "+", "\"/\"", ")", ".", "queryParam", "(", "\"silent\"", ",", "silent", "?", "\"1\"", ":", "\"0\"", ")", ".", "entity", "(", "create", ",", "MediaType", ".", "APPLICATION_JSON_TYPE", ")", ".", "post", "(", "ItemCreateResponse", ".", "class", ")", ".", "getId", "(", ")", ";", "}" ]
Adds a new item to the given app. @param appId The id of the app the item should be added to @param create The data for the new item @param silent True if the create should be silten, false otherwise @return The id of the newly created item
[ "Adds", "a", "new", "item", "to", "the", "given", "app", "." ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/item/ItemAPI.java#L45-L50
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/TransformerFactoryImpl.java
TransformerFactoryImpl.setFeature
public void setFeature(String name, boolean value) throws TransformerConfigurationException { """ <p>Set a feature for this <code>TransformerFactory</code> and <code>Transformer</code>s or <code>Template</code>s created by this factory.</p> <p> Feature names are fully qualified {@link java.net.URI}s. Implementations may define their own features. An {@link TransformerConfigurationException} is thrown if this <code>TransformerFactory</code> or the <code>Transformer</code>s or <code>Template</code>s it creates cannot support the feature. It is possible for an <code>TransformerFactory</code> to expose a feature value but be unable to change its state. </p> <p>See {@link javax.xml.transform.TransformerFactory} for full documentation of specific features.</p> @param name Feature name. @param value Is feature state <code>true</code> or <code>false</code>. @throws TransformerConfigurationException if this <code>TransformerFactory</code> or the <code>Transformer</code>s or <code>Template</code>s it creates cannot support this feature. @throws NullPointerException If the <code>name</code> parameter is null. """ // feature name cannot be null if (name == null) { throw new NullPointerException( XSLMessages.createMessage( XSLTErrorResources.ER_SET_FEATURE_NULL_NAME, null)); } // secure processing? if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) { m_isSecureProcessing = value; } // This implementation does not support the setting of a feature other than // the secure processing feature. else { throw new TransformerConfigurationException( XSLMessages.createMessage( XSLTErrorResources.ER_UNSUPPORTED_FEATURE, new Object[] {name})); } }
java
public void setFeature(String name, boolean value) throws TransformerConfigurationException { // feature name cannot be null if (name == null) { throw new NullPointerException( XSLMessages.createMessage( XSLTErrorResources.ER_SET_FEATURE_NULL_NAME, null)); } // secure processing? if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) { m_isSecureProcessing = value; } // This implementation does not support the setting of a feature other than // the secure processing feature. else { throw new TransformerConfigurationException( XSLMessages.createMessage( XSLTErrorResources.ER_UNSUPPORTED_FEATURE, new Object[] {name})); } }
[ "public", "void", "setFeature", "(", "String", "name", ",", "boolean", "value", ")", "throws", "TransformerConfigurationException", "{", "// feature name cannot be null", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "XSLMessages", ".", "createMessage", "(", "XSLTErrorResources", ".", "ER_SET_FEATURE_NULL_NAME", ",", "null", ")", ")", ";", "}", "// secure processing?", "if", "(", "name", ".", "equals", "(", "XMLConstants", ".", "FEATURE_SECURE_PROCESSING", ")", ")", "{", "m_isSecureProcessing", "=", "value", ";", "}", "// This implementation does not support the setting of a feature other than", "// the secure processing feature.", "else", "{", "throw", "new", "TransformerConfigurationException", "(", "XSLMessages", ".", "createMessage", "(", "XSLTErrorResources", ".", "ER_UNSUPPORTED_FEATURE", ",", "new", "Object", "[", "]", "{", "name", "}", ")", ")", ";", "}", "}" ]
<p>Set a feature for this <code>TransformerFactory</code> and <code>Transformer</code>s or <code>Template</code>s created by this factory.</p> <p> Feature names are fully qualified {@link java.net.URI}s. Implementations may define their own features. An {@link TransformerConfigurationException} is thrown if this <code>TransformerFactory</code> or the <code>Transformer</code>s or <code>Template</code>s it creates cannot support the feature. It is possible for an <code>TransformerFactory</code> to expose a feature value but be unable to change its state. </p> <p>See {@link javax.xml.transform.TransformerFactory} for full documentation of specific features.</p> @param name Feature name. @param value Is feature state <code>true</code> or <code>false</code>. @throws TransformerConfigurationException if this <code>TransformerFactory</code> or the <code>Transformer</code>s or <code>Template</code>s it creates cannot support this feature. @throws NullPointerException If the <code>name</code> parameter is null.
[ "<p", ">", "Set", "a", "feature", "for", "this", "<code", ">", "TransformerFactory<", "/", "code", ">", "and", "<code", ">", "Transformer<", "/", "code", ">", "s", "or", "<code", ">", "Template<", "/", "code", ">", "s", "created", "by", "this", "factory", ".", "<", "/", "p", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/TransformerFactoryImpl.java#L404-L427
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.binary
public static void binary(Image srcImage, OutputStream out, String imageType) { """ 彩色转为黑白二值化图片<br> 此方法并不关闭流,输出JPG格式 @param srcImage 源图像流 @param out 目标图像流 @param imageType 图片格式(扩展名) @since 4.0.5 """ binary(srcImage, getImageOutputStream(out), imageType); }
java
public static void binary(Image srcImage, OutputStream out, String imageType) { binary(srcImage, getImageOutputStream(out), imageType); }
[ "public", "static", "void", "binary", "(", "Image", "srcImage", ",", "OutputStream", "out", ",", "String", "imageType", ")", "{", "binary", "(", "srcImage", ",", "getImageOutputStream", "(", "out", ")", ",", "imageType", ")", ";", "}" ]
彩色转为黑白二值化图片<br> 此方法并不关闭流,输出JPG格式 @param srcImage 源图像流 @param out 目标图像流 @param imageType 图片格式(扩展名) @since 4.0.5
[ "彩色转为黑白二值化图片<br", ">", "此方法并不关闭流,输出JPG格式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L712-L714
liferay/com-liferay-commerce
commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java
CommerceNotificationTemplatePersistenceImpl.findByG_E
@Override public List<CommerceNotificationTemplate> findByG_E(long groupId, boolean enabled, int start, int end, OrderByComparator<CommerceNotificationTemplate> orderByComparator) { """ Returns an ordered range of all the commerce notification templates where groupId = &#63; and enabled = &#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 CommerceNotificationTemplateModelImpl}. 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 groupId the group ID @param enabled the enabled @param start the lower bound of the range of commerce notification templates @param end the upper bound of the range of commerce notification templates (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching commerce notification templates """ return findByG_E(groupId, enabled, start, end, orderByComparator, true); }
java
@Override public List<CommerceNotificationTemplate> findByG_E(long groupId, boolean enabled, int start, int end, OrderByComparator<CommerceNotificationTemplate> orderByComparator) { return findByG_E(groupId, enabled, start, end, orderByComparator, true); }
[ "@", "Override", "public", "List", "<", "CommerceNotificationTemplate", ">", "findByG_E", "(", "long", "groupId", ",", "boolean", "enabled", ",", "int", "start", ",", "int", "end", ",", "OrderByComparator", "<", "CommerceNotificationTemplate", ">", "orderByComparator", ")", "{", "return", "findByG_E", "(", "groupId", ",", "enabled", ",", "start", ",", "end", ",", "orderByComparator", ",", "true", ")", ";", "}" ]
Returns an ordered range of all the commerce notification templates where groupId = &#63; and enabled = &#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 CommerceNotificationTemplateModelImpl}. 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 groupId the group ID @param enabled the enabled @param start the lower bound of the range of commerce notification templates @param end the upper bound of the range of commerce notification templates (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching commerce notification templates
[ "Returns", "an", "ordered", "range", "of", "all", "the", "commerce", "notification", "templates", "where", "groupId", "=", "&#63", ";", "and", "enabled", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java#L2472-L2477
spotify/helios
helios-services/src/main/java/com/spotify/helios/agent/AgentService.java
AgentService.setupZookeeperClient
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id, final CountDownLatch zkRegistrationSignal) { """ Create a Zookeeper client and create the control and state nodes if needed. @param config The service configuration. @return A zookeeper client. """ ACLProvider aclProvider = null; List<AuthInfo> authorization = null; final String agentUser = config.getZookeeperAclAgentUser(); final String agentPassword = config.getZooKeeperAclAgentPassword(); final String masterUser = config.getZookeeperAclMasterUser(); final String masterDigest = config.getZooKeeperAclMasterDigest(); if (!isNullOrEmpty(agentPassword)) { if (isNullOrEmpty(agentUser)) { throw new HeliosRuntimeException( "Agent username must be set if a password is set"); } authorization = Lists.newArrayList(new AuthInfo( "digest", String.format("%s:%s", agentUser, agentPassword).getBytes())); } if (config.isZooKeeperEnableAcls()) { if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) { throw new HeliosRuntimeException( "ZooKeeper ACLs enabled but agent username and/or password not set"); } if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) { throw new HeliosRuntimeException( "ZooKeeper ACLs enabled but master username and/or digest not set"); } aclProvider = heliosAclProvider( masterUser, masterDigest, agentUser, digest(agentUser, agentPassword)); } final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = new CuratorClientFactoryImpl().newClient( config.getZooKeeperConnectionString(), config.getZooKeeperSessionTimeoutMillis(), config.getZooKeeperConnectionTimeoutMillis(), zooKeeperRetryPolicy, aclProvider, authorization); final ZooKeeperClient client = new DefaultZooKeeperClient(curator, config.getZooKeeperClusterId()); client.start(); // Register the agent final AgentZooKeeperRegistrar agentZooKeeperRegistrar = new AgentZooKeeperRegistrar( config.getName(), id, config.getZooKeeperRegistrationTtlMinutes(), new SystemClock()); zkRegistrar = ZooKeeperRegistrarService.newBuilder() .setZooKeeperClient(client) .setZooKeeperRegistrar(agentZooKeeperRegistrar) .setZkRegistrationSignal(zkRegistrationSignal) .build(); return client; }
java
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id, final CountDownLatch zkRegistrationSignal) { ACLProvider aclProvider = null; List<AuthInfo> authorization = null; final String agentUser = config.getZookeeperAclAgentUser(); final String agentPassword = config.getZooKeeperAclAgentPassword(); final String masterUser = config.getZookeeperAclMasterUser(); final String masterDigest = config.getZooKeeperAclMasterDigest(); if (!isNullOrEmpty(agentPassword)) { if (isNullOrEmpty(agentUser)) { throw new HeliosRuntimeException( "Agent username must be set if a password is set"); } authorization = Lists.newArrayList(new AuthInfo( "digest", String.format("%s:%s", agentUser, agentPassword).getBytes())); } if (config.isZooKeeperEnableAcls()) { if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) { throw new HeliosRuntimeException( "ZooKeeper ACLs enabled but agent username and/or password not set"); } if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) { throw new HeliosRuntimeException( "ZooKeeper ACLs enabled but master username and/or digest not set"); } aclProvider = heliosAclProvider( masterUser, masterDigest, agentUser, digest(agentUser, agentPassword)); } final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = new CuratorClientFactoryImpl().newClient( config.getZooKeeperConnectionString(), config.getZooKeeperSessionTimeoutMillis(), config.getZooKeeperConnectionTimeoutMillis(), zooKeeperRetryPolicy, aclProvider, authorization); final ZooKeeperClient client = new DefaultZooKeeperClient(curator, config.getZooKeeperClusterId()); client.start(); // Register the agent final AgentZooKeeperRegistrar agentZooKeeperRegistrar = new AgentZooKeeperRegistrar( config.getName(), id, config.getZooKeeperRegistrationTtlMinutes(), new SystemClock()); zkRegistrar = ZooKeeperRegistrarService.newBuilder() .setZooKeeperClient(client) .setZooKeeperRegistrar(agentZooKeeperRegistrar) .setZkRegistrationSignal(zkRegistrationSignal) .build(); return client; }
[ "private", "ZooKeeperClient", "setupZookeeperClient", "(", "final", "AgentConfig", "config", ",", "final", "String", "id", ",", "final", "CountDownLatch", "zkRegistrationSignal", ")", "{", "ACLProvider", "aclProvider", "=", "null", ";", "List", "<", "AuthInfo", ">", "authorization", "=", "null", ";", "final", "String", "agentUser", "=", "config", ".", "getZookeeperAclAgentUser", "(", ")", ";", "final", "String", "agentPassword", "=", "config", ".", "getZooKeeperAclAgentPassword", "(", ")", ";", "final", "String", "masterUser", "=", "config", ".", "getZookeeperAclMasterUser", "(", ")", ";", "final", "String", "masterDigest", "=", "config", ".", "getZooKeeperAclMasterDigest", "(", ")", ";", "if", "(", "!", "isNullOrEmpty", "(", "agentPassword", ")", ")", "{", "if", "(", "isNullOrEmpty", "(", "agentUser", ")", ")", "{", "throw", "new", "HeliosRuntimeException", "(", "\"Agent username must be set if a password is set\"", ")", ";", "}", "authorization", "=", "Lists", ".", "newArrayList", "(", "new", "AuthInfo", "(", "\"digest\"", ",", "String", ".", "format", "(", "\"%s:%s\"", ",", "agentUser", ",", "agentPassword", ")", ".", "getBytes", "(", ")", ")", ")", ";", "}", "if", "(", "config", ".", "isZooKeeperEnableAcls", "(", ")", ")", "{", "if", "(", "isNullOrEmpty", "(", "agentUser", ")", "||", "isNullOrEmpty", "(", "agentPassword", ")", ")", "{", "throw", "new", "HeliosRuntimeException", "(", "\"ZooKeeper ACLs enabled but agent username and/or password not set\"", ")", ";", "}", "if", "(", "isNullOrEmpty", "(", "masterUser", ")", "||", "isNullOrEmpty", "(", "masterDigest", ")", ")", "{", "throw", "new", "HeliosRuntimeException", "(", "\"ZooKeeper ACLs enabled but master username and/or digest not set\"", ")", ";", "}", "aclProvider", "=", "heliosAclProvider", "(", "masterUser", ",", "masterDigest", ",", "agentUser", ",", "digest", "(", "agentUser", ",", "agentPassword", ")", ")", ";", "}", "final", "RetryPolicy", "zooKeeperRetryPolicy", "=", "new", "ExponentialBackoffRetry", "(", "1000", ",", "3", ")", ";", "final", "CuratorFramework", "curator", "=", "new", "CuratorClientFactoryImpl", "(", ")", ".", "newClient", "(", "config", ".", "getZooKeeperConnectionString", "(", ")", ",", "config", ".", "getZooKeeperSessionTimeoutMillis", "(", ")", ",", "config", ".", "getZooKeeperConnectionTimeoutMillis", "(", ")", ",", "zooKeeperRetryPolicy", ",", "aclProvider", ",", "authorization", ")", ";", "final", "ZooKeeperClient", "client", "=", "new", "DefaultZooKeeperClient", "(", "curator", ",", "config", ".", "getZooKeeperClusterId", "(", ")", ")", ";", "client", ".", "start", "(", ")", ";", "// Register the agent", "final", "AgentZooKeeperRegistrar", "agentZooKeeperRegistrar", "=", "new", "AgentZooKeeperRegistrar", "(", "config", ".", "getName", "(", ")", ",", "id", ",", "config", ".", "getZooKeeperRegistrationTtlMinutes", "(", ")", ",", "new", "SystemClock", "(", ")", ")", ";", "zkRegistrar", "=", "ZooKeeperRegistrarService", ".", "newBuilder", "(", ")", ".", "setZooKeeperClient", "(", "client", ")", ".", "setZooKeeperRegistrar", "(", "agentZooKeeperRegistrar", ")", ".", "setZkRegistrationSignal", "(", "zkRegistrationSignal", ")", ".", "build", "(", ")", ";", "return", "client", ";", "}" ]
Create a Zookeeper client and create the control and state nodes if needed. @param config The service configuration. @return A zookeeper client.
[ "Create", "a", "Zookeeper", "client", "and", "create", "the", "control", "and", "state", "nodes", "if", "needed", "." ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-services/src/main/java/com/spotify/helios/agent/AgentService.java#L398-L457
tvesalainen/util
util/src/main/java/org/vesalainen/util/CmdArgs.java
CmdArgs.addOption
public final <T> void addOption(Class<T> cls, String name, String description) { """ Add a mandatory option @param <T> Type of option @param cls Option type class @param name Option name Option name without @param description Option description """ addOption(cls, name, description, null); }
java
public final <T> void addOption(Class<T> cls, String name, String description) { addOption(cls, name, description, null); }
[ "public", "final", "<", "T", ">", "void", "addOption", "(", "Class", "<", "T", ">", "cls", ",", "String", "name", ",", "String", "description", ")", "{", "addOption", "(", "cls", ",", "name", ",", "description", ",", "null", ")", ";", "}" ]
Add a mandatory option @param <T> Type of option @param cls Option type class @param name Option name Option name without @param description Option description
[ "Add", "a", "mandatory", "option" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/CmdArgs.java#L331-L334
jurmous/etcd4j
src/main/java/mousio/etcd4j/EtcdClient.java
EtcdClient.getVersion
@Deprecated public String getVersion() { """ Get the version of the Etcd server @return version as String @deprecated use version() when using etcd 2.1+. """ try { return new EtcdOldVersionRequest(this.client, retryHandler).send().get(); } catch (IOException | EtcdException | EtcdAuthenticationException | TimeoutException e) { return null; } }
java
@Deprecated public String getVersion() { try { return new EtcdOldVersionRequest(this.client, retryHandler).send().get(); } catch (IOException | EtcdException | EtcdAuthenticationException | TimeoutException e) { return null; } }
[ "@", "Deprecated", "public", "String", "getVersion", "(", ")", "{", "try", "{", "return", "new", "EtcdOldVersionRequest", "(", "this", ".", "client", ",", "retryHandler", ")", ".", "send", "(", ")", ".", "get", "(", ")", ";", "}", "catch", "(", "IOException", "|", "EtcdException", "|", "EtcdAuthenticationException", "|", "TimeoutException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Get the version of the Etcd server @return version as String @deprecated use version() when using etcd 2.1+.
[ "Get", "the", "version", "of", "the", "Etcd", "server" ]
train
https://github.com/jurmous/etcd4j/blob/ffb1d574cf85bbab025dd566ce250f1860bbcbc7/src/main/java/mousio/etcd4j/EtcdClient.java#L118-L125
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java
IdlToDSMojo.prepWsdlXsl
private void prepWsdlXsl() throws MojoExecutionException { """ Read a wsdl.xsl (stylesheet) from a resource, and write it to a working directory. @return the on-disk wsdl.xsl file """ try { wsdlXsl = new File(getBaseDir(), wsdlXslFile); initOutputDir(wsdlXsl.getParentFile()); writeWsdlStylesheet(wsdlXsl); } catch (Exception e) { throw new MojoExecutionException("Failed to write local copy of WSDL stylesheet: " + e, e); } }
java
private void prepWsdlXsl() throws MojoExecutionException { try { wsdlXsl = new File(getBaseDir(), wsdlXslFile); initOutputDir(wsdlXsl.getParentFile()); writeWsdlStylesheet(wsdlXsl); } catch (Exception e) { throw new MojoExecutionException("Failed to write local copy of WSDL stylesheet: " + e, e); } }
[ "private", "void", "prepWsdlXsl", "(", ")", "throws", "MojoExecutionException", "{", "try", "{", "wsdlXsl", "=", "new", "File", "(", "getBaseDir", "(", ")", ",", "wsdlXslFile", ")", ";", "initOutputDir", "(", "wsdlXsl", ".", "getParentFile", "(", ")", ")", ";", "writeWsdlStylesheet", "(", "wsdlXsl", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Failed to write local copy of WSDL stylesheet: \"", "+", "e", ",", "e", ")", ";", "}", "}" ]
Read a wsdl.xsl (stylesheet) from a resource, and write it to a working directory. @return the on-disk wsdl.xsl file
[ "Read", "a", "wsdl", ".", "xsl", "(", "stylesheet", ")", "from", "a", "resource", "and", "write", "it", "to", "a", "working", "directory", "." ]
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L318-L326
oasp/oasp4j
modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java
RestServiceExceptionFacade.handleValidationException
protected Response handleValidationException(Throwable exception, Throwable catched) { """ Exception handling for validation exception. @param exception the exception to handle @param catched the original exception that was cached. Either same as {@code error} or a (child-) {@link Throwable#getCause() cause} of it. @return the response build from the exception. """ Throwable t = catched; Map<String, List<String>> errorsMap = null; if (exception instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations(); errorsMap = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { Iterator<Node> it = violation.getPropertyPath().iterator(); String fieldName = null; // Getting fieldname from the exception while (it.hasNext()) { fieldName = it.next().toString(); } List<String> errorsList = errorsMap.get(fieldName); if (errorsList == null) { errorsList = new ArrayList<>(); errorsMap.put(fieldName, errorsList); } errorsList.add(violation.getMessage()); } t = new ValidationException(errorsMap.toString(), catched); } ValidationErrorUserException error = new ValidationErrorUserException(t); return createResponse(t, error, errorsMap); }
java
protected Response handleValidationException(Throwable exception, Throwable catched) { Throwable t = catched; Map<String, List<String>> errorsMap = null; if (exception instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations(); errorsMap = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { Iterator<Node> it = violation.getPropertyPath().iterator(); String fieldName = null; // Getting fieldname from the exception while (it.hasNext()) { fieldName = it.next().toString(); } List<String> errorsList = errorsMap.get(fieldName); if (errorsList == null) { errorsList = new ArrayList<>(); errorsMap.put(fieldName, errorsList); } errorsList.add(violation.getMessage()); } t = new ValidationException(errorsMap.toString(), catched); } ValidationErrorUserException error = new ValidationErrorUserException(t); return createResponse(t, error, errorsMap); }
[ "protected", "Response", "handleValidationException", "(", "Throwable", "exception", ",", "Throwable", "catched", ")", "{", "Throwable", "t", "=", "catched", ";", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "errorsMap", "=", "null", ";", "if", "(", "exception", "instanceof", "ConstraintViolationException", ")", "{", "ConstraintViolationException", "constraintViolationException", "=", "(", "ConstraintViolationException", ")", "exception", ";", "Set", "<", "ConstraintViolation", "<", "?", ">", ">", "violations", "=", "constraintViolationException", ".", "getConstraintViolations", "(", ")", ";", "errorsMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "ConstraintViolation", "<", "?", ">", "violation", ":", "violations", ")", "{", "Iterator", "<", "Node", ">", "it", "=", "violation", ".", "getPropertyPath", "(", ")", ".", "iterator", "(", ")", ";", "String", "fieldName", "=", "null", ";", "// Getting fieldname from the exception", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "fieldName", "=", "it", ".", "next", "(", ")", ".", "toString", "(", ")", ";", "}", "List", "<", "String", ">", "errorsList", "=", "errorsMap", ".", "get", "(", "fieldName", ")", ";", "if", "(", "errorsList", "==", "null", ")", "{", "errorsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "errorsMap", ".", "put", "(", "fieldName", ",", "errorsList", ")", ";", "}", "errorsList", ".", "add", "(", "violation", ".", "getMessage", "(", ")", ")", ";", "}", "t", "=", "new", "ValidationException", "(", "errorsMap", ".", "toString", "(", ")", ",", "catched", ")", ";", "}", "ValidationErrorUserException", "error", "=", "new", "ValidationErrorUserException", "(", "t", ")", ";", "return", "createResponse", "(", "t", ",", "error", ",", "errorsMap", ")", ";", "}" ]
Exception handling for validation exception. @param exception the exception to handle @param catched the original exception that was cached. Either same as {@code error} or a (child-) {@link Throwable#getCause() cause} of it. @return the response build from the exception.
[ "Exception", "handling", "for", "validation", "exception", "." ]
train
https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java#L326-L359
netty/netty
codec/src/main/java/io/netty/handler/codec/compression/Snappy.java
Snappy.validateOffset
private static void validateOffset(int offset, int chunkSizeSoFar) { """ Validates that the offset extracted from a compressed reference is within the permissible bounds of an offset (0 < offset < Integer.MAX_VALUE), and does not exceed the length of the chunk currently read so far. @param offset The offset extracted from the compressed reference @param chunkSizeSoFar The number of bytes read so far from this chunk @throws DecompressionException if the offset is invalid """ if (offset == 0) { throw new DecompressionException("Offset is less than minimum permissible value"); } if (offset < 0) { // Due to arithmetic overflow throw new DecompressionException("Offset is greater than maximum value supported by this implementation"); } if (offset > chunkSizeSoFar) { throw new DecompressionException("Offset exceeds size of chunk"); } }
java
private static void validateOffset(int offset, int chunkSizeSoFar) { if (offset == 0) { throw new DecompressionException("Offset is less than minimum permissible value"); } if (offset < 0) { // Due to arithmetic overflow throw new DecompressionException("Offset is greater than maximum value supported by this implementation"); } if (offset > chunkSizeSoFar) { throw new DecompressionException("Offset exceeds size of chunk"); } }
[ "private", "static", "void", "validateOffset", "(", "int", "offset", ",", "int", "chunkSizeSoFar", ")", "{", "if", "(", "offset", "==", "0", ")", "{", "throw", "new", "DecompressionException", "(", "\"Offset is less than minimum permissible value\"", ")", ";", "}", "if", "(", "offset", "<", "0", ")", "{", "// Due to arithmetic overflow", "throw", "new", "DecompressionException", "(", "\"Offset is greater than maximum value supported by this implementation\"", ")", ";", "}", "if", "(", "offset", ">", "chunkSizeSoFar", ")", "{", "throw", "new", "DecompressionException", "(", "\"Offset exceeds size of chunk\"", ")", ";", "}", "}" ]
Validates that the offset extracted from a compressed reference is within the permissible bounds of an offset (0 < offset < Integer.MAX_VALUE), and does not exceed the length of the chunk currently read so far. @param offset The offset extracted from the compressed reference @param chunkSizeSoFar The number of bytes read so far from this chunk @throws DecompressionException if the offset is invalid
[ "Validates", "that", "the", "offset", "extracted", "from", "a", "compressed", "reference", "is", "within", "the", "permissible", "bounds", "of", "an", "offset", "(", "0", "<", "offset", "<", "Integer", ".", "MAX_VALUE", ")", "and", "does", "not", "exceed", "the", "length", "of", "the", "chunk", "currently", "read", "so", "far", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java#L575-L588
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/ZoomSlider.java
ZoomSlider.updateUsableScales
public void updateUsableScales() { """ Update the list of scales to include only the list of usable scales (from all possible scales). """ Bbox bgBounds = backgroundPart.getBounds(); /* * First move background a little bit to right based on difference in width with the sliderUnit. */ int internalHorMargin = (int) (sliderUnit.getBounds().getWidth() - backgroundPart.getBounds().getWidth()) / 2; bgBounds.setX(internalHorMargin); int backgroundPartHeight = (int) bgBounds.getHeight(); int sliderAreaHeight = 0; /* * Needed for aligning the sliderUnit's y with currentScale's y. */ int currentUnitY = sliderAreaHeight; double currentScale = mapWidget.getMapModel().getMapView().getCurrentScale(); List<Bbox> partBounds = new ArrayList<Bbox>(); List<ScaleInfo> zoomLevels = mapWidget.getMapModel().getMapInfo().getScaleConfiguration().getZoomLevels(); int size = zoomLevels.size(); currentScaleList.clear(); boolean scaleFound = false; for (int i = size - 1 ; i >= 0 ; i--) { double scale = zoomLevels.get(i).getPixelPerUnit(); if (mapWidget.getMapModel().getMapView().isResolutionAvailable(1.0 / scale)) { Bbox bounds = (Bbox) bgBounds.clone(); bounds.setY(sliderAreaHeight); partBounds.add(bounds); currentScaleList.add(scale); if (scale <= currentScale && !scaleFound) { scaleFound = true; currentUnitY = sliderAreaHeight; } sliderAreaHeight += backgroundPartHeight; } } /* * Align zoom slider unit with current zoom */ Bbox bounds = sliderUnit.getBounds(); bounds.setY(currentUnitY); /* * Zoom slider area */ sliderArea = new SliderArea(SLIDER_AREA, (int) sliderUnit.getBounds().getWidth(), sliderAreaHeight, sliderUnit, backgroundPart, partBounds, mapWidget, new ZoomSliderController(this)); sliderArea.setHorizontalMargin((int) -bgBounds.getX()); sliderArea.setVerticalMargin((int) backgroundPart.getBounds().getWidth()); /* * Zoom out button internal margin. */ zoomOut.getBackground().getBounds().setY(sliderArea.getVerticalMargin() + sliderAreaHeight); zoomOut.getIcon().getBounds().setY(sliderArea.getVerticalMargin() + sliderAreaHeight); }
java
public void updateUsableScales() { Bbox bgBounds = backgroundPart.getBounds(); /* * First move background a little bit to right based on difference in width with the sliderUnit. */ int internalHorMargin = (int) (sliderUnit.getBounds().getWidth() - backgroundPart.getBounds().getWidth()) / 2; bgBounds.setX(internalHorMargin); int backgroundPartHeight = (int) bgBounds.getHeight(); int sliderAreaHeight = 0; /* * Needed for aligning the sliderUnit's y with currentScale's y. */ int currentUnitY = sliderAreaHeight; double currentScale = mapWidget.getMapModel().getMapView().getCurrentScale(); List<Bbox> partBounds = new ArrayList<Bbox>(); List<ScaleInfo> zoomLevels = mapWidget.getMapModel().getMapInfo().getScaleConfiguration().getZoomLevels(); int size = zoomLevels.size(); currentScaleList.clear(); boolean scaleFound = false; for (int i = size - 1 ; i >= 0 ; i--) { double scale = zoomLevels.get(i).getPixelPerUnit(); if (mapWidget.getMapModel().getMapView().isResolutionAvailable(1.0 / scale)) { Bbox bounds = (Bbox) bgBounds.clone(); bounds.setY(sliderAreaHeight); partBounds.add(bounds); currentScaleList.add(scale); if (scale <= currentScale && !scaleFound) { scaleFound = true; currentUnitY = sliderAreaHeight; } sliderAreaHeight += backgroundPartHeight; } } /* * Align zoom slider unit with current zoom */ Bbox bounds = sliderUnit.getBounds(); bounds.setY(currentUnitY); /* * Zoom slider area */ sliderArea = new SliderArea(SLIDER_AREA, (int) sliderUnit.getBounds().getWidth(), sliderAreaHeight, sliderUnit, backgroundPart, partBounds, mapWidget, new ZoomSliderController(this)); sliderArea.setHorizontalMargin((int) -bgBounds.getX()); sliderArea.setVerticalMargin((int) backgroundPart.getBounds().getWidth()); /* * Zoom out button internal margin. */ zoomOut.getBackground().getBounds().setY(sliderArea.getVerticalMargin() + sliderAreaHeight); zoomOut.getIcon().getBounds().setY(sliderArea.getVerticalMargin() + sliderAreaHeight); }
[ "public", "void", "updateUsableScales", "(", ")", "{", "Bbox", "bgBounds", "=", "backgroundPart", ".", "getBounds", "(", ")", ";", "/*\n\t\t * First move background a little bit to right based on difference in width with the sliderUnit.\n\t\t */", "int", "internalHorMargin", "=", "(", "int", ")", "(", "sliderUnit", ".", "getBounds", "(", ")", ".", "getWidth", "(", ")", "-", "backgroundPart", ".", "getBounds", "(", ")", ".", "getWidth", "(", ")", ")", "/", "2", ";", "bgBounds", ".", "setX", "(", "internalHorMargin", ")", ";", "int", "backgroundPartHeight", "=", "(", "int", ")", "bgBounds", ".", "getHeight", "(", ")", ";", "int", "sliderAreaHeight", "=", "0", ";", "/*\n\t\t * Needed for aligning the sliderUnit's y with currentScale's y.\n\t\t */", "int", "currentUnitY", "=", "sliderAreaHeight", ";", "double", "currentScale", "=", "mapWidget", ".", "getMapModel", "(", ")", ".", "getMapView", "(", ")", ".", "getCurrentScale", "(", ")", ";", "List", "<", "Bbox", ">", "partBounds", "=", "new", "ArrayList", "<", "Bbox", ">", "(", ")", ";", "List", "<", "ScaleInfo", ">", "zoomLevels", "=", "mapWidget", ".", "getMapModel", "(", ")", ".", "getMapInfo", "(", ")", ".", "getScaleConfiguration", "(", ")", ".", "getZoomLevels", "(", ")", ";", "int", "size", "=", "zoomLevels", ".", "size", "(", ")", ";", "currentScaleList", ".", "clear", "(", ")", ";", "boolean", "scaleFound", "=", "false", ";", "for", "(", "int", "i", "=", "size", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "double", "scale", "=", "zoomLevels", ".", "get", "(", "i", ")", ".", "getPixelPerUnit", "(", ")", ";", "if", "(", "mapWidget", ".", "getMapModel", "(", ")", ".", "getMapView", "(", ")", ".", "isResolutionAvailable", "(", "1.0", "/", "scale", ")", ")", "{", "Bbox", "bounds", "=", "(", "Bbox", ")", "bgBounds", ".", "clone", "(", ")", ";", "bounds", ".", "setY", "(", "sliderAreaHeight", ")", ";", "partBounds", ".", "add", "(", "bounds", ")", ";", "currentScaleList", ".", "add", "(", "scale", ")", ";", "if", "(", "scale", "<=", "currentScale", "&&", "!", "scaleFound", ")", "{", "scaleFound", "=", "true", ";", "currentUnitY", "=", "sliderAreaHeight", ";", "}", "sliderAreaHeight", "+=", "backgroundPartHeight", ";", "}", "}", "/*\n\t\t * Align zoom slider unit with current zoom\n\t\t */", "Bbox", "bounds", "=", "sliderUnit", ".", "getBounds", "(", ")", ";", "bounds", ".", "setY", "(", "currentUnitY", ")", ";", "/*\n\t\t * Zoom slider area \n\t\t */", "sliderArea", "=", "new", "SliderArea", "(", "SLIDER_AREA", ",", "(", "int", ")", "sliderUnit", ".", "getBounds", "(", ")", ".", "getWidth", "(", ")", ",", "sliderAreaHeight", ",", "sliderUnit", ",", "backgroundPart", ",", "partBounds", ",", "mapWidget", ",", "new", "ZoomSliderController", "(", "this", ")", ")", ";", "sliderArea", ".", "setHorizontalMargin", "(", "(", "int", ")", "-", "bgBounds", ".", "getX", "(", ")", ")", ";", "sliderArea", ".", "setVerticalMargin", "(", "(", "int", ")", "backgroundPart", ".", "getBounds", "(", ")", ".", "getWidth", "(", ")", ")", ";", "/*\n\t\t * Zoom out button internal margin.\n\t\t */", "zoomOut", ".", "getBackground", "(", ")", ".", "getBounds", "(", ")", ".", "setY", "(", "sliderArea", ".", "getVerticalMargin", "(", ")", "+", "sliderAreaHeight", ")", ";", "zoomOut", ".", "getIcon", "(", ")", ".", "getBounds", "(", ")", ".", "setY", "(", "sliderArea", ".", "getVerticalMargin", "(", ")", "+", "sliderAreaHeight", ")", ";", "}" ]
Update the list of scales to include only the list of usable scales (from all possible scales).
[ "Update", "the", "list", "of", "scales", "to", "include", "only", "the", "list", "of", "usable", "scales", "(", "from", "all", "possible", "scales", ")", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/ZoomSlider.java#L95-L150
haifengl/smile
math/src/main/java/smile/sort/QuickSelect.java
QuickSelect.q1
public static <T extends Comparable<? super T>> T q1(T[] a) { """ Find the first quantile (p = 1/4) of an array of type double. """ int k = a.length / 4; return select(a, k); }
java
public static <T extends Comparable<? super T>> T q1(T[] a) { int k = a.length / 4; return select(a, k); }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", "super", "T", ">", ">", "T", "q1", "(", "T", "[", "]", "a", ")", "{", "int", "k", "=", "a", ".", "length", "/", "4", ";", "return", "select", "(", "a", ",", "k", ")", ";", "}" ]
Find the first quantile (p = 1/4) of an array of type double.
[ "Find", "the", "first", "quantile", "(", "p", "=", "1", "/", "4", ")", "of", "an", "array", "of", "type", "double", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/sort/QuickSelect.java#L331-L334
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/jvm/JvmType.java
JvmType.createFromJavaExecutable
public static JvmType createFromJavaExecutable(final String javaExecutable, boolean forLaunch) { """ Create a {@code JvmType} based on the location of the java executable. @param javaExecutable the location of the java executable. Cannot be {@code null} or empty @param forLaunch {@code true} if the created object will be used for launching servers; {@code false} if it is simply a data holder. A value of {@code true} will disable some validity checks and may disable determining if the JVM is modular @return the {@code JvmType}. Will not return {@code null} """ assert javaExecutable != null; if (javaExecutable.equals(JAVA_WIN_EXECUTABLE) || javaExecutable.equals(JAVA_UNIX_EXECUTABLE)) { return createFromEnvironmentVariable(forLaunch); } else { return new JvmType(forLaunch, isModularJvm(javaExecutable, forLaunch), javaExecutable); } }
java
public static JvmType createFromJavaExecutable(final String javaExecutable, boolean forLaunch) { assert javaExecutable != null; if (javaExecutable.equals(JAVA_WIN_EXECUTABLE) || javaExecutable.equals(JAVA_UNIX_EXECUTABLE)) { return createFromEnvironmentVariable(forLaunch); } else { return new JvmType(forLaunch, isModularJvm(javaExecutable, forLaunch), javaExecutable); } }
[ "public", "static", "JvmType", "createFromJavaExecutable", "(", "final", "String", "javaExecutable", ",", "boolean", "forLaunch", ")", "{", "assert", "javaExecutable", "!=", "null", ";", "if", "(", "javaExecutable", ".", "equals", "(", "JAVA_WIN_EXECUTABLE", ")", "||", "javaExecutable", ".", "equals", "(", "JAVA_UNIX_EXECUTABLE", ")", ")", "{", "return", "createFromEnvironmentVariable", "(", "forLaunch", ")", ";", "}", "else", "{", "return", "new", "JvmType", "(", "forLaunch", ",", "isModularJvm", "(", "javaExecutable", ",", "forLaunch", ")", ",", "javaExecutable", ")", ";", "}", "}" ]
Create a {@code JvmType} based on the location of the java executable. @param javaExecutable the location of the java executable. Cannot be {@code null} or empty @param forLaunch {@code true} if the created object will be used for launching servers; {@code false} if it is simply a data holder. A value of {@code true} will disable some validity checks and may disable determining if the JVM is modular @return the {@code JvmType}. Will not return {@code null}
[ "Create", "a", "{" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/jvm/JvmType.java#L144-L152
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.loadBalancing_serviceName_internalNatIp_GET
public String loadBalancing_serviceName_internalNatIp_GET(String serviceName, OvhLoadBalancingZoneEnum zone) throws IOException { """ Ip subnet used by OVH to nat requests on your ip lb to your backends. You must ensure that your backends are not part of a network that overlap with this one. REST: GET /ip/loadBalancing/{serviceName}/internalNatIp @param zone [required] one of your ip loadbalancing's zone @param serviceName [required] The internal name of your IP load balancing """ String qPath = "/ip/loadBalancing/{serviceName}/internalNatIp"; StringBuilder sb = path(qPath, serviceName); query(sb, "zone", zone); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, String.class); }
java
public String loadBalancing_serviceName_internalNatIp_GET(String serviceName, OvhLoadBalancingZoneEnum zone) throws IOException { String qPath = "/ip/loadBalancing/{serviceName}/internalNatIp"; StringBuilder sb = path(qPath, serviceName); query(sb, "zone", zone); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, String.class); }
[ "public", "String", "loadBalancing_serviceName_internalNatIp_GET", "(", "String", "serviceName", ",", "OvhLoadBalancingZoneEnum", "zone", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/loadBalancing/{serviceName}/internalNatIp\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"zone\"", ",", "zone", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "String", ".", "class", ")", ";", "}" ]
Ip subnet used by OVH to nat requests on your ip lb to your backends. You must ensure that your backends are not part of a network that overlap with this one. REST: GET /ip/loadBalancing/{serviceName}/internalNatIp @param zone [required] one of your ip loadbalancing's zone @param serviceName [required] The internal name of your IP load balancing
[ "Ip", "subnet", "used", "by", "OVH", "to", "nat", "requests", "on", "your", "ip", "lb", "to", "your", "backends", ".", "You", "must", "ensure", "that", "your", "backends", "are", "not", "part", "of", "a", "network", "that", "overlap", "with", "this", "one", "." ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L1347-L1353
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java
SoundStore.getOggStream
public Audio getOggStream(String ref) throws IOException { """ Get the Sound based on a specified OGG file @param ref The reference to the OGG file in the classpath @return The Sound read from the OGG file @throws IOException Indicates a failure to load the OGG """ if (!soundWorks) { return new NullAudio(); } setMOD(null); setStream(null); if (currentMusic != -1) { AL10.alSourceStop(sources.get(0)); } getMusicSource(); currentMusic = sources.get(0); return new StreamSound(new OpenALStreamPlayer(currentMusic, ref)); }
java
public Audio getOggStream(String ref) throws IOException { if (!soundWorks) { return new NullAudio(); } setMOD(null); setStream(null); if (currentMusic != -1) { AL10.alSourceStop(sources.get(0)); } getMusicSource(); currentMusic = sources.get(0); return new StreamSound(new OpenALStreamPlayer(currentMusic, ref)); }
[ "public", "Audio", "getOggStream", "(", "String", "ref", ")", "throws", "IOException", "{", "if", "(", "!", "soundWorks", ")", "{", "return", "new", "NullAudio", "(", ")", ";", "}", "setMOD", "(", "null", ")", ";", "setStream", "(", "null", ")", ";", "if", "(", "currentMusic", "!=", "-", "1", ")", "{", "AL10", ".", "alSourceStop", "(", "sources", ".", "get", "(", "0", ")", ")", ";", "}", "getMusicSource", "(", ")", ";", "currentMusic", "=", "sources", ".", "get", "(", "0", ")", ";", "return", "new", "StreamSound", "(", "new", "OpenALStreamPlayer", "(", "currentMusic", ",", "ref", ")", ")", ";", "}" ]
Get the Sound based on a specified OGG file @param ref The reference to the OGG file in the classpath @return The Sound read from the OGG file @throws IOException Indicates a failure to load the OGG
[ "Get", "the", "Sound", "based", "on", "a", "specified", "OGG", "file" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java#L742-L758
graknlabs/grakn
server/src/server/exception/TransactionException.java
TransactionException.illegalUnhasWithInstance
public static TransactionException illegalUnhasWithInstance(String type, String attributeType, boolean isKey) { """ Thrown when there exists and instance of {@code type} HAS {@code attributeType} upon unlinking the AttributeType from the Type """ return create(ErrorMessage.ILLEGAL_TYPE_UNHAS_ATTRIBUTE_WITH_INSTANCE.getMessage(type, isKey ? "key" : "has", attributeType)); }
java
public static TransactionException illegalUnhasWithInstance(String type, String attributeType, boolean isKey) { return create(ErrorMessage.ILLEGAL_TYPE_UNHAS_ATTRIBUTE_WITH_INSTANCE.getMessage(type, isKey ? "key" : "has", attributeType)); }
[ "public", "static", "TransactionException", "illegalUnhasWithInstance", "(", "String", "type", ",", "String", "attributeType", ",", "boolean", "isKey", ")", "{", "return", "create", "(", "ErrorMessage", ".", "ILLEGAL_TYPE_UNHAS_ATTRIBUTE_WITH_INSTANCE", ".", "getMessage", "(", "type", ",", "isKey", "?", "\"key\"", ":", "\"has\"", ",", "attributeType", ")", ")", ";", "}" ]
Thrown when there exists and instance of {@code type} HAS {@code attributeType} upon unlinking the AttributeType from the Type
[ "Thrown", "when", "there", "exists", "and", "instance", "of", "{" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L122-L124
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java
VirtualNetworkGatewayConnectionsInner.beginUpdateTagsAsync
public Observable<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) { """ Updates a virtual network gateway connection tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkGatewayConnectionInner object """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() { @Override public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() { @Override public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkGatewayConnectionInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayConnectionName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayConnectionName", ",", "tags", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "VirtualNetworkGatewayConnectionInner", ">", ",", "VirtualNetworkGatewayConnectionInner", ">", "(", ")", "{", "@", "Override", "public", "VirtualNetworkGatewayConnectionInner", "call", "(", "ServiceResponse", "<", "VirtualNetworkGatewayConnectionInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a virtual network gateway connection tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkGatewayConnectionInner object
[ "Updates", "a", "virtual", "network", "gateway", "connection", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java#L792-L799
atomix/atomix
storage/src/main/java/io/atomix/storage/statistics/StorageStatistics.java
StorageStatistics.getFreeMemory
public long getFreeMemory() { """ Returns the amount of free memory remaining. @return the amount of free memory remaining if successful, -1 return indicates failure. """ try { return (long) mBeanServer.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "FreePhysicalMemorySize"); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("An exception occurred during memory check", e); } } return -1; }
java
public long getFreeMemory() { try { return (long) mBeanServer.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "FreePhysicalMemorySize"); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("An exception occurred during memory check", e); } } return -1; }
[ "public", "long", "getFreeMemory", "(", ")", "{", "try", "{", "return", "(", "long", ")", "mBeanServer", ".", "getAttribute", "(", "new", "ObjectName", "(", "\"java.lang\"", ",", "\"type\"", ",", "\"OperatingSystem\"", ")", ",", "\"FreePhysicalMemorySize\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "LOGGER", ".", "isDebugEnabled", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"An exception occurred during memory check\"", ",", "e", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Returns the amount of free memory remaining. @return the amount of free memory remaining if successful, -1 return indicates failure.
[ "Returns", "the", "amount", "of", "free", "memory", "remaining", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/statistics/StorageStatistics.java#L73-L82
javagl/CommonUI
src/main/java/de/javagl/common/ui/JTrees.java
JTrees.expandAllRecursively
private static void expandAllRecursively(JTree tree, TreePath treePath) { """ Recursively expand all paths in the given tree, starting with the given path @param tree The tree @param treePath The current tree path """ TreeModel model = tree.getModel(); Object lastPathComponent = treePath.getLastPathComponent(); int childCount = model.getChildCount(lastPathComponent); if (childCount == 0) { return; } tree.expandPath(treePath); for (int i=0; i<childCount; i++) { Object child = model.getChild(lastPathComponent, i); int grandChildCount = model.getChildCount(child); if (grandChildCount > 0) { class LocalTreePath extends TreePath { private static final long serialVersionUID = 0; public LocalTreePath( TreePath parent, Object lastPathComponent) { super(parent, lastPathComponent); } } TreePath nextTreePath = new LocalTreePath(treePath, child); expandAllRecursively(tree, nextTreePath); } } }
java
private static void expandAllRecursively(JTree tree, TreePath treePath) { TreeModel model = tree.getModel(); Object lastPathComponent = treePath.getLastPathComponent(); int childCount = model.getChildCount(lastPathComponent); if (childCount == 0) { return; } tree.expandPath(treePath); for (int i=0; i<childCount; i++) { Object child = model.getChild(lastPathComponent, i); int grandChildCount = model.getChildCount(child); if (grandChildCount > 0) { class LocalTreePath extends TreePath { private static final long serialVersionUID = 0; public LocalTreePath( TreePath parent, Object lastPathComponent) { super(parent, lastPathComponent); } } TreePath nextTreePath = new LocalTreePath(treePath, child); expandAllRecursively(tree, nextTreePath); } } }
[ "private", "static", "void", "expandAllRecursively", "(", "JTree", "tree", ",", "TreePath", "treePath", ")", "{", "TreeModel", "model", "=", "tree", ".", "getModel", "(", ")", ";", "Object", "lastPathComponent", "=", "treePath", ".", "getLastPathComponent", "(", ")", ";", "int", "childCount", "=", "model", ".", "getChildCount", "(", "lastPathComponent", ")", ";", "if", "(", "childCount", "==", "0", ")", "{", "return", ";", "}", "tree", ".", "expandPath", "(", "treePath", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "childCount", ";", "i", "++", ")", "{", "Object", "child", "=", "model", ".", "getChild", "(", "lastPathComponent", ",", "i", ")", ";", "int", "grandChildCount", "=", "model", ".", "getChildCount", "(", "child", ")", ";", "if", "(", "grandChildCount", ">", "0", ")", "{", "class", "LocalTreePath", "extends", "TreePath", "{", "private", "static", "final", "long", "serialVersionUID", "=", "0", ";", "public", "LocalTreePath", "(", "TreePath", "parent", ",", "Object", "lastPathComponent", ")", "{", "super", "(", "parent", ",", "lastPathComponent", ")", ";", "}", "}", "TreePath", "nextTreePath", "=", "new", "LocalTreePath", "(", "treePath", ",", "child", ")", ";", "expandAllRecursively", "(", "tree", ",", "nextTreePath", ")", ";", "}", "}", "}" ]
Recursively expand all paths in the given tree, starting with the given path @param tree The tree @param treePath The current tree path
[ "Recursively", "expand", "all", "paths", "in", "the", "given", "tree", "starting", "with", "the", "given", "path" ]
train
https://github.com/javagl/CommonUI/blob/b2c7a7637d4e288271392ba148dc17e4c9780255/src/main/java/de/javagl/common/ui/JTrees.java#L126-L155
fernandospr/javapns-jdk16
src/main/java/javapns/notification/PushNotificationPayload.java
PushNotificationPayload.getCompatibleProperty
private <T> T getCompatibleProperty(String propertyName, Class<T> expectedClass, String exceptionMessage) throws JSONException { """ Get the value of a given property, but only if it is of the expected class. If the value exists but is of a different class than expected, an exception is thrown. This method simply invokes the other getCompatibleProperty method with the root aps dictionary. @param <T> the property value's class @param propertyName the name of the property to get @param expectedClass the property value's expected (required) class @param exceptionMessage the exception message to throw if the value is not of the expected class @return the property's value @throws JSONException """ return getCompatibleProperty(propertyName, expectedClass, exceptionMessage, this.apsDictionary); }
java
private <T> T getCompatibleProperty(String propertyName, Class<T> expectedClass, String exceptionMessage) throws JSONException { return getCompatibleProperty(propertyName, expectedClass, exceptionMessage, this.apsDictionary); }
[ "private", "<", "T", ">", "T", "getCompatibleProperty", "(", "String", "propertyName", ",", "Class", "<", "T", ">", "expectedClass", ",", "String", "exceptionMessage", ")", "throws", "JSONException", "{", "return", "getCompatibleProperty", "(", "propertyName", ",", "expectedClass", ",", "exceptionMessage", ",", "this", ".", "apsDictionary", ")", ";", "}" ]
Get the value of a given property, but only if it is of the expected class. If the value exists but is of a different class than expected, an exception is thrown. This method simply invokes the other getCompatibleProperty method with the root aps dictionary. @param <T> the property value's class @param propertyName the name of the property to get @param expectedClass the property value's expected (required) class @param exceptionMessage the exception message to throw if the value is not of the expected class @return the property's value @throws JSONException
[ "Get", "the", "value", "of", "a", "given", "property", "but", "only", "if", "it", "is", "of", "the", "expected", "class", ".", "If", "the", "value", "exists", "but", "is", "of", "a", "different", "class", "than", "expected", "an", "exception", "is", "thrown", "." ]
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/PushNotificationPayload.java#L256-L258
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/Transaction.java
Transaction.addSignedInput
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException { """ Same as {@link #addSignedInput(TransactionOutPoint, Script, ECKey, Transaction.SigHash, boolean)} but defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want. """ return addSignedInput(prevOut, scriptPubKey, sigKey, SigHash.ALL, false); }
java
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException { return addSignedInput(prevOut, scriptPubKey, sigKey, SigHash.ALL, false); }
[ "public", "TransactionInput", "addSignedInput", "(", "TransactionOutPoint", "prevOut", ",", "Script", "scriptPubKey", ",", "ECKey", "sigKey", ")", "throws", "ScriptException", "{", "return", "addSignedInput", "(", "prevOut", ",", "scriptPubKey", ",", "sigKey", ",", "SigHash", ".", "ALL", ",", "false", ")", ";", "}" ]
Same as {@link #addSignedInput(TransactionOutPoint, Script, ECKey, Transaction.SigHash, boolean)} but defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want.
[ "Same", "as", "{" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L993-L995
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTree.java
HtmlTree.addAttr
public void addAttr(HtmlAttr attrName, String attrValue) { """ Adds an attribute for the HTML tag. @param attrName name of the attribute @param attrValue value of the attribute """ if (attrs.isEmpty()) attrs = new LinkedHashMap<HtmlAttr,String>(3); attrs.put(nullCheck(attrName), escapeHtmlChars(attrValue)); }
java
public void addAttr(HtmlAttr attrName, String attrValue) { if (attrs.isEmpty()) attrs = new LinkedHashMap<HtmlAttr,String>(3); attrs.put(nullCheck(attrName), escapeHtmlChars(attrValue)); }
[ "public", "void", "addAttr", "(", "HtmlAttr", "attrName", ",", "String", "attrValue", ")", "{", "if", "(", "attrs", ".", "isEmpty", "(", ")", ")", "attrs", "=", "new", "LinkedHashMap", "<", "HtmlAttr", ",", "String", ">", "(", "3", ")", ";", "attrs", ".", "put", "(", "nullCheck", "(", "attrName", ")", ",", "escapeHtmlChars", "(", "attrValue", ")", ")", ";", "}" ]
Adds an attribute for the HTML tag. @param attrName name of the attribute @param attrValue value of the attribute
[ "Adds", "an", "attribute", "for", "the", "HTML", "tag", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTree.java#L80-L84
haifengl/smile
graph/src/main/java/smile/graph/AdjacencyList.java
AdjacencyList.dfsearch
private int dfsearch(int v, int[] pre, int[] ts, int count) { """ Depth-first search of graph. @param v the start vertex. @param pre the array to store the mask if vertex has been visited. @param ts the array to store the reverse topological order. @param count the number of vertices have been visited before this search. @return the number of vertices that have been visited after this search. """ pre[v] = 0; for (Edge edge : graph[v]) { int t = edge.v2; if (pre[t] == -1) { count = dfsearch(t, pre, ts, count); } } ts[count++] = v; return count; }
java
private int dfsearch(int v, int[] pre, int[] ts, int count) { pre[v] = 0; for (Edge edge : graph[v]) { int t = edge.v2; if (pre[t] == -1) { count = dfsearch(t, pre, ts, count); } } ts[count++] = v; return count; }
[ "private", "int", "dfsearch", "(", "int", "v", ",", "int", "[", "]", "pre", ",", "int", "[", "]", "ts", ",", "int", "count", ")", "{", "pre", "[", "v", "]", "=", "0", ";", "for", "(", "Edge", "edge", ":", "graph", "[", "v", "]", ")", "{", "int", "t", "=", "edge", ".", "v2", ";", "if", "(", "pre", "[", "t", "]", "==", "-", "1", ")", "{", "count", "=", "dfsearch", "(", "t", ",", "pre", ",", "ts", ",", "count", ")", ";", "}", "}", "ts", "[", "count", "++", "]", "=", "v", ";", "return", "count", ";", "}" ]
Depth-first search of graph. @param v the start vertex. @param pre the array to store the mask if vertex has been visited. @param ts the array to store the reverse topological order. @param count the number of vertices have been visited before this search. @return the number of vertices that have been visited after this search.
[ "Depth", "-", "first", "search", "of", "graph", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/graph/src/main/java/smile/graph/AdjacencyList.java#L308-L321