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
box/box-java-sdk
src/main/java/com/box/sdk/URLTemplate.java
URLTemplate.buildWithQuery
public URL buildWithQuery(String base, String queryString, Object... values) { """ Build a URL with Query String and URL Parameters. @param base base URL @param queryString query string @param values URL Parameters @return URL """ String urlString = String.format(base + this.template, values) + queryString; URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { assert false : "An invalid URL template indicates a bug in the SDK."; } return url; }
java
public URL buildWithQuery(String base, String queryString, Object... values) { String urlString = String.format(base + this.template, values) + queryString; URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { assert false : "An invalid URL template indicates a bug in the SDK."; } return url; }
[ "public", "URL", "buildWithQuery", "(", "String", "base", ",", "String", "queryString", ",", "Object", "...", "values", ")", "{", "String", "urlString", "=", "String", ".", "format", "(", "base", "+", "this", ".", "template", ",", "values", ")", "+", "queryString", ";", "URL", "url", "=", "null", ";", "try", "{", "url", "=", "new", "URL", "(", "urlString", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "assert", "false", ":", "\"An invalid URL template indicates a bug in the SDK.\"", ";", "}", "return", "url", ";", "}" ]
Build a URL with Query String and URL Parameters. @param base base URL @param queryString query string @param values URL Parameters @return URL
[ "Build", "a", "URL", "with", "Query", "String", "and", "URL", "Parameters", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/URLTemplate.java#L46-L56
kirgor/enklib
rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java
RESTClient.getWithListResult
public <T> EntityResponse<List<T>> getWithListResult(Class<T> entityClass, String path, Map<String, String> params, Map<String, String> headers) throws IOException, RESTException { """ Performs GET request, while expected response entity is a list of specified type. @param entityClass Class, which contains expected response entity fields. @param path Request path. @param params Map of URL query params. @param headers Map of HTTP request headers. @param <T> Type of class, which contains expected response entity fields. @throws IOException If error during HTTP connection or entity parsing occurs. @throws RESTException If HTTP response code is non OK. """ HttpGet httpGet = buildHttpGet(path, params); return parseListEntityResponse(entityClass, getHttpResponse(httpGet, headers)); }
java
public <T> EntityResponse<List<T>> getWithListResult(Class<T> entityClass, String path, Map<String, String> params, Map<String, String> headers) throws IOException, RESTException { HttpGet httpGet = buildHttpGet(path, params); return parseListEntityResponse(entityClass, getHttpResponse(httpGet, headers)); }
[ "public", "<", "T", ">", "EntityResponse", "<", "List", "<", "T", ">", ">", "getWithListResult", "(", "Class", "<", "T", ">", "entityClass", ",", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "params", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "throws", "IOException", ",", "RESTException", "{", "HttpGet", "httpGet", "=", "buildHttpGet", "(", "path", ",", "params", ")", ";", "return", "parseListEntityResponse", "(", "entityClass", ",", "getHttpResponse", "(", "httpGet", ",", "headers", ")", ")", ";", "}" ]
Performs GET request, while expected response entity is a list of specified type. @param entityClass Class, which contains expected response entity fields. @param path Request path. @param params Map of URL query params. @param headers Map of HTTP request headers. @param <T> Type of class, which contains expected response entity fields. @throws IOException If error during HTTP connection or entity parsing occurs. @throws RESTException If HTTP response code is non OK.
[ "Performs", "GET", "request", "while", "expected", "response", "entity", "is", "a", "list", "of", "specified", "type", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java#L106-L109
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContentErrorHandler.java
CmsXmlContentErrorHandler.addWarning
public void addWarning(I_CmsXmlContentValue value, String message) { """ Adds an warning message to the internal list of errors, also raised the "has warning" flag.<p> @param value the value that contians the warning @param message the warning message to add """ m_hasWarnings = true; Locale locale = value.getLocale(); Map<String, String> localeWarnings = getLocalIssueMap(m_warnings, locale); localeWarnings.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_WARN_2, value.getPath(), message)); } }
java
public void addWarning(I_CmsXmlContentValue value, String message) { m_hasWarnings = true; Locale locale = value.getLocale(); Map<String, String> localeWarnings = getLocalIssueMap(m_warnings, locale); localeWarnings.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_WARN_2, value.getPath(), message)); } }
[ "public", "void", "addWarning", "(", "I_CmsXmlContentValue", "value", ",", "String", "message", ")", "{", "m_hasWarnings", "=", "true", ";", "Locale", "locale", "=", "value", ".", "getLocale", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "localeWarnings", "=", "getLocalIssueMap", "(", "m_warnings", ",", "locale", ")", ";", "localeWarnings", ".", "put", "(", "value", ".", "getPath", "(", ")", ",", "message", ")", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_XMLCONTENT_VALIDATION_WARN_2", ",", "value", ".", "getPath", "(", ")", ",", "message", ")", ")", ";", "}", "}" ]
Adds an warning message to the internal list of errors, also raised the "has warning" flag.<p> @param value the value that contians the warning @param message the warning message to add
[ "Adds", "an", "warning", "message", "to", "the", "internal", "list", "of", "errors", "also", "raised", "the", "has", "warning", "flag", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentErrorHandler.java#L98-L109
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java
JimfsFileStore.setInitialAttributes
void setInitialAttributes(File file, FileAttribute<?>... attrs) { """ Sets initial attributes on the given file. Sets default attributes first, then attempts to set the given user-provided attributes. """ state.checkOpen(); attributes.setInitialAttributes(file, attrs); }
java
void setInitialAttributes(File file, FileAttribute<?>... attrs) { state.checkOpen(); attributes.setInitialAttributes(file, attrs); }
[ "void", "setInitialAttributes", "(", "File", "file", ",", "FileAttribute", "<", "?", ">", "...", "attrs", ")", "{", "state", ".", "checkOpen", "(", ")", ";", "attributes", ".", "setInitialAttributes", "(", "file", ",", "attrs", ")", ";", "}" ]
Sets initial attributes on the given file. Sets default attributes first, then attempts to set the given user-provided attributes.
[ "Sets", "initial", "attributes", "on", "the", "given", "file", ".", "Sets", "default", "attributes", "first", "then", "attempts", "to", "set", "the", "given", "user", "-", "provided", "attributes", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java#L164-L167
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java
CommonOps_ZDRM.fill
public static void fill(ZMatrixD1 a, double real, double imaginary) { """ <p> Sets every element in the matrix to the specified value.<br> <br> a<sub>ij</sub> = value <p> @param a A matrix whose elements are about to be set. Modified. @param real The real component @param imaginary The imaginary component """ int N = a.getDataLength(); for (int i = 0; i < N; i += 2) { a.data[i] = real; a.data[i+1] = imaginary; } }
java
public static void fill(ZMatrixD1 a, double real, double imaginary) { int N = a.getDataLength(); for (int i = 0; i < N; i += 2) { a.data[i] = real; a.data[i+1] = imaginary; } }
[ "public", "static", "void", "fill", "(", "ZMatrixD1", "a", ",", "double", "real", ",", "double", "imaginary", ")", "{", "int", "N", "=", "a", ".", "getDataLength", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "N", ";", "i", "+=", "2", ")", "{", "a", ".", "data", "[", "i", "]", "=", "real", ";", "a", ".", "data", "[", "i", "+", "1", "]", "=", "imaginary", ";", "}", "}" ]
<p> Sets every element in the matrix to the specified value.<br> <br> a<sub>ij</sub> = value <p> @param a A matrix whose elements are about to be set. Modified. @param real The real component @param imaginary The imaginary component
[ "<p", ">", "Sets", "every", "element", "in", "the", "matrix", "to", "the", "specified", "value", ".", "<br", ">", "<br", ">", "a<sub", ">", "ij<", "/", "sub", ">", "=", "value", "<p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java#L261-L268
zafarkhaja/jsemver
src/main/java/com/github/zafarkhaja/semver/Version.java
Version.setBuildMetadata
public Version setBuildMetadata(String build) { """ Sets the build metadata. @param build the build metadata to set @return a new instance of the {@code Version} class @throws IllegalArgumentException if the input string is {@code NULL} or empty @throws ParseException when invalid version string is provided @throws UnexpectedCharacterException is a special case of {@code ParseException} """ return new Version(normal, preRelease, VersionParser.parseBuild(build)); }
java
public Version setBuildMetadata(String build) { return new Version(normal, preRelease, VersionParser.parseBuild(build)); }
[ "public", "Version", "setBuildMetadata", "(", "String", "build", ")", "{", "return", "new", "Version", "(", "normal", ",", "preRelease", ",", "VersionParser", ".", "parseBuild", "(", "build", ")", ")", ";", "}" ]
Sets the build metadata. @param build the build metadata to set @return a new instance of the {@code Version} class @throws IllegalArgumentException if the input string is {@code NULL} or empty @throws ParseException when invalid version string is provided @throws UnexpectedCharacterException is a special case of {@code ParseException}
[ "Sets", "the", "build", "metadata", "." ]
train
https://github.com/zafarkhaja/jsemver/blob/1f4996ea3dab06193c378fd66fd4f8fdc8334cc6/src/main/java/com/github/zafarkhaja/semver/Version.java#L457-L459
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.createToken
public CompletableFuture<Revision> createToken(Author author, String appId, String secret, boolean isAdmin) { """ Creates a new {@link Token} with the specified {@code appId}, {@code secret} and {@code isAdmin}. """ requireNonNull(author, "author"); requireNonNull(appId, "appId"); requireNonNull(secret, "secret"); checkArgument(secret.startsWith(SECRET_PREFIX), "secret must start with: " + SECRET_PREFIX); final Token newToken = new Token(appId, secret, isAdmin, UserAndTimestamp.of(author)); final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(newToken.id())); final String newTokenSecret = newToken.secret(); assert newTokenSecret != null; final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(newTokenSecret)); final Change<JsonNode> change = Change.ofJsonPatch(TOKEN_JSON, asJsonArray(new TestAbsenceOperation(appIdPath), new TestAbsenceOperation(secretPath), new AddOperation(appIdPath, Jackson.valueToTree(newToken)), new AddOperation(secretPath, Jackson.valueToTree(newToken.id())))); return tokenRepo.push(INTERNAL_PROJ, Project.REPO_DOGMA, author, "Add a token: '" + newToken.id(), change); }
java
public CompletableFuture<Revision> createToken(Author author, String appId, String secret, boolean isAdmin) { requireNonNull(author, "author"); requireNonNull(appId, "appId"); requireNonNull(secret, "secret"); checkArgument(secret.startsWith(SECRET_PREFIX), "secret must start with: " + SECRET_PREFIX); final Token newToken = new Token(appId, secret, isAdmin, UserAndTimestamp.of(author)); final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(newToken.id())); final String newTokenSecret = newToken.secret(); assert newTokenSecret != null; final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(newTokenSecret)); final Change<JsonNode> change = Change.ofJsonPatch(TOKEN_JSON, asJsonArray(new TestAbsenceOperation(appIdPath), new TestAbsenceOperation(secretPath), new AddOperation(appIdPath, Jackson.valueToTree(newToken)), new AddOperation(secretPath, Jackson.valueToTree(newToken.id())))); return tokenRepo.push(INTERNAL_PROJ, Project.REPO_DOGMA, author, "Add a token: '" + newToken.id(), change); }
[ "public", "CompletableFuture", "<", "Revision", ">", "createToken", "(", "Author", "author", ",", "String", "appId", ",", "String", "secret", ",", "boolean", "isAdmin", ")", "{", "requireNonNull", "(", "author", ",", "\"author\"", ")", ";", "requireNonNull", "(", "appId", ",", "\"appId\"", ")", ";", "requireNonNull", "(", "secret", ",", "\"secret\"", ")", ";", "checkArgument", "(", "secret", ".", "startsWith", "(", "SECRET_PREFIX", ")", ",", "\"secret must start with: \"", "+", "SECRET_PREFIX", ")", ";", "final", "Token", "newToken", "=", "new", "Token", "(", "appId", ",", "secret", ",", "isAdmin", ",", "UserAndTimestamp", ".", "of", "(", "author", ")", ")", ";", "final", "JsonPointer", "appIdPath", "=", "JsonPointer", ".", "compile", "(", "\"/appIds\"", "+", "encodeSegment", "(", "newToken", ".", "id", "(", ")", ")", ")", ";", "final", "String", "newTokenSecret", "=", "newToken", ".", "secret", "(", ")", ";", "assert", "newTokenSecret", "!=", "null", ";", "final", "JsonPointer", "secretPath", "=", "JsonPointer", ".", "compile", "(", "\"/secrets\"", "+", "encodeSegment", "(", "newTokenSecret", ")", ")", ";", "final", "Change", "<", "JsonNode", ">", "change", "=", "Change", ".", "ofJsonPatch", "(", "TOKEN_JSON", ",", "asJsonArray", "(", "new", "TestAbsenceOperation", "(", "appIdPath", ")", ",", "new", "TestAbsenceOperation", "(", "secretPath", ")", ",", "new", "AddOperation", "(", "appIdPath", ",", "Jackson", ".", "valueToTree", "(", "newToken", ")", ")", ",", "new", "AddOperation", "(", "secretPath", ",", "Jackson", ".", "valueToTree", "(", "newToken", ".", "id", "(", ")", ")", ")", ")", ")", ";", "return", "tokenRepo", ".", "push", "(", "INTERNAL_PROJ", ",", "Project", ".", "REPO_DOGMA", ",", "author", ",", "\"Add a token: '\"", "+", "newToken", ".", "id", "(", ")", ",", "change", ")", ";", "}" ]
Creates a new {@link Token} with the specified {@code appId}, {@code secret} and {@code isAdmin}.
[ "Creates", "a", "new", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L718-L740
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optStringArrayList
@Nullable public static ArrayList<String> optStringArrayList(@Nullable Bundle bundle, @Nullable String key) { """ Returns a optional {@link java.lang.String} {@link java.util.ArrayList}. In other words, returns the value mapped by key if it exists and is a {@link java.lang.String} {@link java.util.ArrayList}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link java.lang.String} array value if exists, empty list if bundle is null, null otherwise. @see android.os.Bundle#getStringArrayList(String) """ return optStringArrayList(bundle, key, new ArrayList<String>()); }
java
@Nullable public static ArrayList<String> optStringArrayList(@Nullable Bundle bundle, @Nullable String key) { return optStringArrayList(bundle, key, new ArrayList<String>()); }
[ "@", "Nullable", "public", "static", "ArrayList", "<", "String", ">", "optStringArrayList", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ")", "{", "return", "optStringArrayList", "(", "bundle", ",", "key", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", "}" ]
Returns a optional {@link java.lang.String} {@link java.util.ArrayList}. In other words, returns the value mapped by key if it exists and is a {@link java.lang.String} {@link java.util.ArrayList}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link java.lang.String} array value if exists, empty list if bundle is null, null otherwise. @see android.os.Bundle#getStringArrayList(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L1025-L1028
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/serial/DeserializationGadgetDetector.java
DeserializationGadgetDetector.hasCustomReadObject
private boolean hasCustomReadObject(Method m, ClassContext classContext,List<String> classesToIgnore) throws CFGBuilderException, DataflowAnalysisException { """ Check if the readObject is doing multiple external call beyond the basic readByte, readBoolean, etc.. @param m @param classContext @return @throws CFGBuilderException @throws DataflowAnalysisException """ ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); int count = 0; for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //ByteCode.printOpCode(inst,cpg); if(inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; if (!READ_DESERIALIZATION_METHODS.contains(invoke.getMethodName(cpg)) && !classesToIgnore.contains(invoke.getClassName(cpg))) { count +=1; } } } return count > 3; }
java
private boolean hasCustomReadObject(Method m, ClassContext classContext,List<String> classesToIgnore) throws CFGBuilderException, DataflowAnalysisException { ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); int count = 0; for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //ByteCode.printOpCode(inst,cpg); if(inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; if (!READ_DESERIALIZATION_METHODS.contains(invoke.getMethodName(cpg)) && !classesToIgnore.contains(invoke.getClassName(cpg))) { count +=1; } } } return count > 3; }
[ "private", "boolean", "hasCustomReadObject", "(", "Method", "m", ",", "ClassContext", "classContext", ",", "List", "<", "String", ">", "classesToIgnore", ")", "throws", "CFGBuilderException", ",", "DataflowAnalysisException", "{", "ConstantPoolGen", "cpg", "=", "classContext", ".", "getConstantPoolGen", "(", ")", ";", "CFG", "cfg", "=", "classContext", ".", "getCFG", "(", "m", ")", ";", "int", "count", "=", "0", ";", "for", "(", "Iterator", "<", "Location", ">", "i", "=", "cfg", ".", "locationIterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "Location", "location", "=", "i", ".", "next", "(", ")", ";", "Instruction", "inst", "=", "location", ".", "getHandle", "(", ")", ".", "getInstruction", "(", ")", ";", "//ByteCode.printOpCode(inst,cpg);", "if", "(", "inst", "instanceof", "InvokeInstruction", ")", "{", "InvokeInstruction", "invoke", "=", "(", "InvokeInstruction", ")", "inst", ";", "if", "(", "!", "READ_DESERIALIZATION_METHODS", ".", "contains", "(", "invoke", ".", "getMethodName", "(", "cpg", ")", ")", "&&", "!", "classesToIgnore", ".", "contains", "(", "invoke", ".", "getClassName", "(", "cpg", ")", ")", ")", "{", "count", "+=", "1", ";", "}", "}", "}", "return", "count", ">", "3", ";", "}" ]
Check if the readObject is doing multiple external call beyond the basic readByte, readBoolean, etc.. @param m @param classContext @return @throws CFGBuilderException @throws DataflowAnalysisException
[ "Check", "if", "the", "readObject", "is", "doing", "multiple", "external", "call", "beyond", "the", "basic", "readByte", "readBoolean", "etc", ".." ]
train
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/serial/DeserializationGadgetDetector.java#L129-L147
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WHeadingRenderer.java
WHeadingRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { """ Paints the given WHeading. @param component the WHeading to paint. @param renderContext the RenderContext to paint to. """ WHeading heading = (WHeading) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:heading"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendAttribute("level", heading.getHeadingLevel().getLevel()); xml.appendOptionalAttribute("accessibleText", heading.getAccessibleText()); xml.appendClose(); // Render margin MarginRendererUtil.renderMargin(heading, renderContext); if (heading.getDecoratedLabel() == null) { // Constructed with a String xml.append(heading.getText(), heading.isEncodeText()); } else { heading.getDecoratedLabel().paint(renderContext); } xml.appendEndTag("ui:heading"); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WHeading heading = (WHeading) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:heading"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendAttribute("level", heading.getHeadingLevel().getLevel()); xml.appendOptionalAttribute("accessibleText", heading.getAccessibleText()); xml.appendClose(); // Render margin MarginRendererUtil.renderMargin(heading, renderContext); if (heading.getDecoratedLabel() == null) { // Constructed with a String xml.append(heading.getText(), heading.isEncodeText()); } else { heading.getDecoratedLabel().paint(renderContext); } xml.appendEndTag("ui:heading"); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WHeading", "heading", "=", "(", "WHeading", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "xml", ".", "appendTagOpen", "(", "\"ui:heading\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"id\"", ",", "component", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"class\"", ",", "component", ".", "getHtmlClass", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"track\"", ",", "component", ".", "isTracking", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"level\"", ",", "heading", ".", "getHeadingLevel", "(", ")", ".", "getLevel", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"accessibleText\"", ",", "heading", ".", "getAccessibleText", "(", ")", ")", ";", "xml", ".", "appendClose", "(", ")", ";", "// Render margin", "MarginRendererUtil", ".", "renderMargin", "(", "heading", ",", "renderContext", ")", ";", "if", "(", "heading", ".", "getDecoratedLabel", "(", ")", "==", "null", ")", "{", "// Constructed with a String", "xml", ".", "append", "(", "heading", ".", "getText", "(", ")", ",", "heading", ".", "isEncodeText", "(", ")", ")", ";", "}", "else", "{", "heading", ".", "getDecoratedLabel", "(", ")", ".", "paint", "(", "renderContext", ")", ";", "}", "xml", ".", "appendEndTag", "(", "\"ui:heading\"", ")", ";", "}" ]
Paints the given WHeading. @param component the WHeading to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WHeading", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WHeadingRenderer.java#L23-L47
cdk/cdk
storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java
BeamToCDK.newTetrahedral
private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) { """ Creates a tetrahedral element for the given configuration. Currently only tetrahedral centres with 4 explicit atoms are handled. @param u central atom @param vs neighboring atom indices (in order) @param atoms array of the CDK atoms (pre-converted) @param c the configuration of the neighbors (vs) for the order they are given @return tetrahedral stereo element for addition to an atom container """ // no way to handle tetrahedral configurations with implicit // hydrogen or lone pair at the moment if (vs.length != 4) { // sanity check if (vs.length != 3) return null; // there is an implicit hydrogen (or lone-pair) we insert the // central atom in sorted position vs = insert(u, vs); } // @TH1/@TH2 = anti-clockwise and clockwise respectively Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE; return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]}, stereo); }
java
private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) { // no way to handle tetrahedral configurations with implicit // hydrogen or lone pair at the moment if (vs.length != 4) { // sanity check if (vs.length != 3) return null; // there is an implicit hydrogen (or lone-pair) we insert the // central atom in sorted position vs = insert(u, vs); } // @TH1/@TH2 = anti-clockwise and clockwise respectively Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE; return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]}, stereo); }
[ "private", "IStereoElement", "newTetrahedral", "(", "int", "u", ",", "int", "[", "]", "vs", ",", "IAtom", "[", "]", "atoms", ",", "Configuration", "c", ")", "{", "// no way to handle tetrahedral configurations with implicit", "// hydrogen or lone pair at the moment", "if", "(", "vs", ".", "length", "!=", "4", ")", "{", "// sanity check", "if", "(", "vs", ".", "length", "!=", "3", ")", "return", "null", ";", "// there is an implicit hydrogen (or lone-pair) we insert the", "// central atom in sorted position", "vs", "=", "insert", "(", "u", ",", "vs", ")", ";", "}", "// @TH1/@TH2 = anti-clockwise and clockwise respectively", "Stereo", "stereo", "=", "c", "==", "Configuration", ".", "TH1", "?", "Stereo", ".", "ANTI_CLOCKWISE", ":", "Stereo", ".", "CLOCKWISE", ";", "return", "new", "TetrahedralChirality", "(", "atoms", "[", "u", "]", ",", "new", "IAtom", "[", "]", "{", "atoms", "[", "vs", "[", "0", "]", "]", ",", "atoms", "[", "vs", "[", "1", "]", "]", ",", "atoms", "[", "vs", "[", "2", "]", "]", ",", "atoms", "[", "vs", "[", "3", "]", "]", "}", ",", "stereo", ")", ";", "}" ]
Creates a tetrahedral element for the given configuration. Currently only tetrahedral centres with 4 explicit atoms are handled. @param u central atom @param vs neighboring atom indices (in order) @param atoms array of the CDK atoms (pre-converted) @param c the configuration of the neighbors (vs) for the order they are given @return tetrahedral stereo element for addition to an atom container
[ "Creates", "a", "tetrahedral", "element", "for", "the", "given", "configuration", ".", "Currently", "only", "tetrahedral", "centres", "with", "4", "explicit", "atoms", "are", "handled", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java#L447-L466
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.openReadOnly
public static RocksDbWrapper openReadOnly(String dirPath) throws RocksDbException, IOException { """ Open a {@link RocksDB} with default options in read-only mode. @param dirPath existing {@link RocksDB} data directory @return @throws RocksDbException @throws IOException """ RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(dirPath, true); rocksDbWrapper.init(); return rocksDbWrapper; }
java
public static RocksDbWrapper openReadOnly(String dirPath) throws RocksDbException, IOException { RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(dirPath, true); rocksDbWrapper.init(); return rocksDbWrapper; }
[ "public", "static", "RocksDbWrapper", "openReadOnly", "(", "String", "dirPath", ")", "throws", "RocksDbException", ",", "IOException", "{", "RocksDbWrapper", "rocksDbWrapper", "=", "new", "RocksDbWrapper", "(", "dirPath", ",", "true", ")", ";", "rocksDbWrapper", ".", "init", "(", ")", ";", "return", "rocksDbWrapper", ";", "}" ]
Open a {@link RocksDB} with default options in read-only mode. @param dirPath existing {@link RocksDB} data directory @return @throws RocksDbException @throws IOException
[ "Open", "a", "{", "@link", "RocksDB", "}", "with", "default", "options", "in", "read", "-", "only", "mode", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L68-L72
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java
SDNN.multiHeadDotProductAttention
public SDVariable multiHeadDotProductAttention(String name, SDVariable queries, SDVariable keys, SDVariable values, SDVariable Wq, SDVariable Wk, SDVariable Wv, SDVariable Wo, SDVariable mask, boolean scaled) { """ This performs multi-headed dot product attention on the given timeseries input @see #multiHeadDotProductAttention(String, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, boolean, boolean) """ final SDVariable result = f().multiHeadDotProductAttention(queries, keys, values, Wq, Wk, Wv, Wo, mask, scaled); return updateVariableNameAndReference(result, name); }
java
public SDVariable multiHeadDotProductAttention(String name, SDVariable queries, SDVariable keys, SDVariable values, SDVariable Wq, SDVariable Wk, SDVariable Wv, SDVariable Wo, SDVariable mask, boolean scaled){ final SDVariable result = f().multiHeadDotProductAttention(queries, keys, values, Wq, Wk, Wv, Wo, mask, scaled); return updateVariableNameAndReference(result, name); }
[ "public", "SDVariable", "multiHeadDotProductAttention", "(", "String", "name", ",", "SDVariable", "queries", ",", "SDVariable", "keys", ",", "SDVariable", "values", ",", "SDVariable", "Wq", ",", "SDVariable", "Wk", ",", "SDVariable", "Wv", ",", "SDVariable", "Wo", ",", "SDVariable", "mask", ",", "boolean", "scaled", ")", "{", "final", "SDVariable", "result", "=", "f", "(", ")", ".", "multiHeadDotProductAttention", "(", "queries", ",", "keys", ",", "values", ",", "Wq", ",", "Wk", ",", "Wv", ",", "Wo", ",", "mask", ",", "scaled", ")", ";", "return", "updateVariableNameAndReference", "(", "result", ",", "name", ")", ";", "}" ]
This performs multi-headed dot product attention on the given timeseries input @see #multiHeadDotProductAttention(String, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, boolean, boolean)
[ "This", "performs", "multi", "-", "headed", "dot", "product", "attention", "on", "the", "given", "timeseries", "input" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java#L914-L917
mikepenz/FastAdapter
library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java
SubItemUtil.getAllItems
public static List<IItem> getAllItems(List<IItem> items, boolean countHeaders, IPredicate predicate) { """ retrieves a flat list of the items in the provided list, respecting subitems regardless of there current visibility @param items the list of items to process @param countHeaders if true, headers will be counted as well @return list of items in the adapter """ return getAllItems(items, countHeaders, false, predicate); }
java
public static List<IItem> getAllItems(List<IItem> items, boolean countHeaders, IPredicate predicate) { return getAllItems(items, countHeaders, false, predicate); }
[ "public", "static", "List", "<", "IItem", ">", "getAllItems", "(", "List", "<", "IItem", ">", "items", ",", "boolean", "countHeaders", ",", "IPredicate", "predicate", ")", "{", "return", "getAllItems", "(", "items", ",", "countHeaders", ",", "false", ",", "predicate", ")", ";", "}" ]
retrieves a flat list of the items in the provided list, respecting subitems regardless of there current visibility @param items the list of items to process @param countHeaders if true, headers will be counted as well @return list of items in the adapter
[ "retrieves", "a", "flat", "list", "of", "the", "items", "in", "the", "provided", "list", "respecting", "subitems", "regardless", "of", "there", "current", "visibility" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java#L115-L117
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java
Metric.minimumExistingDatapoints
public void minimumExistingDatapoints(Map<Long, Double> datapoints) { """ If current set already has a value at that timestamp then sets the minimum of the two values for that timestamp at coinciding cutoff boundary, else adds the new data points to the current set. @param datapoints The set of data points to add. If null or empty, no operation is performed. """ if (datapoints != null) { for(Entry<Long, Double> entry : datapoints.entrySet()){ Double existingValue = _datapoints.get(entry.getKey()); if(existingValue == null){ _datapoints.put(entry.getKey(), entry.getValue()); } else if (existingValue > entry.getValue()) { _datapoints.put(entry.getKey(), entry.getValue()); } } } }
java
public void minimumExistingDatapoints(Map<Long, Double> datapoints) { if (datapoints != null) { for(Entry<Long, Double> entry : datapoints.entrySet()){ Double existingValue = _datapoints.get(entry.getKey()); if(existingValue == null){ _datapoints.put(entry.getKey(), entry.getValue()); } else if (existingValue > entry.getValue()) { _datapoints.put(entry.getKey(), entry.getValue()); } } } }
[ "public", "void", "minimumExistingDatapoints", "(", "Map", "<", "Long", ",", "Double", ">", "datapoints", ")", "{", "if", "(", "datapoints", "!=", "null", ")", "{", "for", "(", "Entry", "<", "Long", ",", "Double", ">", "entry", ":", "datapoints", ".", "entrySet", "(", ")", ")", "{", "Double", "existingValue", "=", "_datapoints", ".", "get", "(", "entry", ".", "getKey", "(", ")", ")", ";", "if", "(", "existingValue", "==", "null", ")", "{", "_datapoints", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "else", "if", "(", "existingValue", ">", "entry", ".", "getValue", "(", ")", ")", "{", "_datapoints", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", "}" ]
If current set already has a value at that timestamp then sets the minimum of the two values for that timestamp at coinciding cutoff boundary, else adds the new data points to the current set. @param datapoints The set of data points to add. If null or empty, no operation is performed.
[ "If", "current", "set", "already", "has", "a", "value", "at", "that", "timestamp", "then", "sets", "the", "minimum", "of", "the", "two", "values", "for", "that", "timestamp", "at", "coinciding", "cutoff", "boundary", "else", "adds", "the", "new", "data", "points", "to", "the", "current", "set", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java#L207-L219
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addConstraintsSizeMessage
public FessMessages addConstraintsSizeMessage(String property, String min, String max) { """ Add the created action message for the key 'constraints.Size.message' with parameters. <pre> message: Size of {item} must be between {min} and {max}. </pre> @param property The property name for the message. (NotNull) @param min The parameter min for message. (NotNull) @param max The parameter max for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max)); return this; }
java
public FessMessages addConstraintsSizeMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max)); return this; }
[ "public", "FessMessages", "addConstraintsSizeMessage", "(", "String", "property", ",", "String", "min", ",", "String", "max", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "CONSTRAINTS_Size_MESSAGE", ",", "min", ",", "max", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'constraints.Size.message' with parameters. <pre> message: Size of {item} must be between {min} and {max}. </pre> @param property The property name for the message. (NotNull) @param min The parameter min for message. (NotNull) @param max The parameter max for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "constraints", ".", "Size", ".", "message", "with", "parameters", ".", "<pre", ">", "message", ":", "Size", "of", "{", "item", "}", "must", "be", "between", "{", "min", "}", "and", "{", "max", "}", ".", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L784-L788
wealthfront/magellan
magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java
Navigator.goBackTo
public void goBackTo(final Screen screen, NavigationType navigationType) { """ Navigates from the current screen back to the Screen parameter wherever it is in this Navigator's back stack. Screens in between the current screen and the Screen parameter on the back stack are removed. If the Screen parameter is not present in this Navigator's back stack, this method is equivalent to {@link #goBackToRoot(NavigationType) goBackToRoot(navigationType)} @param screen screen to navigate back to through this Navigator's back stack @param navigationType determines how the navigation event is animated """ navigate(new HistoryRewriter() { @Override public void rewriteHistory(Deque<Screen> history) { checkArgument(history.contains(screen), "Can't go back to a screen that isn't in history."); while (history.size() > 1) { if (history.peek() == screen) { break; } history.pop(); } } }, navigationType, BACKWARD); }
java
public void goBackTo(final Screen screen, NavigationType navigationType) { navigate(new HistoryRewriter() { @Override public void rewriteHistory(Deque<Screen> history) { checkArgument(history.contains(screen), "Can't go back to a screen that isn't in history."); while (history.size() > 1) { if (history.peek() == screen) { break; } history.pop(); } } }, navigationType, BACKWARD); }
[ "public", "void", "goBackTo", "(", "final", "Screen", "screen", ",", "NavigationType", "navigationType", ")", "{", "navigate", "(", "new", "HistoryRewriter", "(", ")", "{", "@", "Override", "public", "void", "rewriteHistory", "(", "Deque", "<", "Screen", ">", "history", ")", "{", "checkArgument", "(", "history", ".", "contains", "(", "screen", ")", ",", "\"Can't go back to a screen that isn't in history.\"", ")", ";", "while", "(", "history", ".", "size", "(", ")", ">", "1", ")", "{", "if", "(", "history", ".", "peek", "(", ")", "==", "screen", ")", "{", "break", ";", "}", "history", ".", "pop", "(", ")", ";", "}", "}", "}", ",", "navigationType", ",", "BACKWARD", ")", ";", "}" ]
Navigates from the current screen back to the Screen parameter wherever it is in this Navigator's back stack. Screens in between the current screen and the Screen parameter on the back stack are removed. If the Screen parameter is not present in this Navigator's back stack, this method is equivalent to {@link #goBackToRoot(NavigationType) goBackToRoot(navigationType)} @param screen screen to navigate back to through this Navigator's back stack @param navigationType determines how the navigation event is animated
[ "Navigates", "from", "the", "current", "screen", "back", "to", "the", "Screen", "parameter", "wherever", "it", "is", "in", "this", "Navigator", "s", "back", "stack", ".", "Screens", "in", "between", "the", "current", "screen", "and", "the", "Screen", "parameter", "on", "the", "back", "stack", "are", "removed", ".", "If", "the", "Screen", "parameter", "is", "not", "present", "in", "this", "Navigator", "s", "back", "stack", "this", "method", "is", "equivalent", "to", "{", "@link", "#goBackToRoot", "(", "NavigationType", ")", "goBackToRoot", "(", "navigationType", ")", "}" ]
train
https://github.com/wealthfront/magellan/blob/f690979161a97e40fb9d11dc9d7e3c8cf85ba312/magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java#L458-L471
Azure/azure-sdk-for-java
signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java
SignalRsInner.checkNameAvailabilityAsync
public Observable<NameAvailabilityInner> checkNameAvailabilityAsync(String location, NameAvailabilityParameters parameters) { """ Checks that the SignalR name is valid and is not already in use. @param location the region @param parameters Parameters supplied to the operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NameAvailabilityInner object """ return checkNameAvailabilityWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<NameAvailabilityInner>, NameAvailabilityInner>() { @Override public NameAvailabilityInner call(ServiceResponse<NameAvailabilityInner> response) { return response.body(); } }); }
java
public Observable<NameAvailabilityInner> checkNameAvailabilityAsync(String location, NameAvailabilityParameters parameters) { return checkNameAvailabilityWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<NameAvailabilityInner>, NameAvailabilityInner>() { @Override public NameAvailabilityInner call(ServiceResponse<NameAvailabilityInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NameAvailabilityInner", ">", "checkNameAvailabilityAsync", "(", "String", "location", ",", "NameAvailabilityParameters", "parameters", ")", "{", "return", "checkNameAvailabilityWithServiceResponseAsync", "(", "location", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "NameAvailabilityInner", ">", ",", "NameAvailabilityInner", ">", "(", ")", "{", "@", "Override", "public", "NameAvailabilityInner", "call", "(", "ServiceResponse", "<", "NameAvailabilityInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Checks that the SignalR name is valid and is not already in use. @param location the region @param parameters Parameters supplied to the operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NameAvailabilityInner object
[ "Checks", "that", "the", "SignalR", "name", "is", "valid", "and", "is", "not", "already", "in", "use", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L241-L248
craterdog/java-general-utilities
src/main/java/craterdog/utils/ByteUtils.java
ByteUtils.bigDecimalToBytes
static public int bigDecimalToBytes(BigDecimal decimal, byte[] buffer, int index) { """ This function converts a big decimal into its corresponding byte format and inserts it into the specified buffer at the specified index. @param decimal The big decimal to be converted. @param buffer The byte array. @param index The index in the array to begin inserting bytes. @return The number of bytes inserted. """ BigInteger intVal = decimal.unscaledValue(); int length = 12 + (intVal.bitLength() + 8) / 8; int scale = decimal.scale(); System.arraycopy(intToBytes(scale), 0, buffer, index, 4); // copy in the scale index += 4; int precision = decimal.precision(); System.arraycopy(intToBytes(precision), 0, buffer, index, 4); // copy in the scale index += 4; System.arraycopy(bigIntegerToBytes(intVal), 0, buffer, index, length - 8); // copy in the big integer return length; }
java
static public int bigDecimalToBytes(BigDecimal decimal, byte[] buffer, int index) { BigInteger intVal = decimal.unscaledValue(); int length = 12 + (intVal.bitLength() + 8) / 8; int scale = decimal.scale(); System.arraycopy(intToBytes(scale), 0, buffer, index, 4); // copy in the scale index += 4; int precision = decimal.precision(); System.arraycopy(intToBytes(precision), 0, buffer, index, 4); // copy in the scale index += 4; System.arraycopy(bigIntegerToBytes(intVal), 0, buffer, index, length - 8); // copy in the big integer return length; }
[ "static", "public", "int", "bigDecimalToBytes", "(", "BigDecimal", "decimal", ",", "byte", "[", "]", "buffer", ",", "int", "index", ")", "{", "BigInteger", "intVal", "=", "decimal", ".", "unscaledValue", "(", ")", ";", "int", "length", "=", "12", "+", "(", "intVal", ".", "bitLength", "(", ")", "+", "8", ")", "/", "8", ";", "int", "scale", "=", "decimal", ".", "scale", "(", ")", ";", "System", ".", "arraycopy", "(", "intToBytes", "(", "scale", ")", ",", "0", ",", "buffer", ",", "index", ",", "4", ")", ";", "// copy in the scale", "index", "+=", "4", ";", "int", "precision", "=", "decimal", ".", "precision", "(", ")", ";", "System", ".", "arraycopy", "(", "intToBytes", "(", "precision", ")", ",", "0", ",", "buffer", ",", "index", ",", "4", ")", ";", "// copy in the scale", "index", "+=", "4", ";", "System", ".", "arraycopy", "(", "bigIntegerToBytes", "(", "intVal", ")", ",", "0", ",", "buffer", ",", "index", ",", "length", "-", "8", ")", ";", "// copy in the big integer", "return", "length", ";", "}" ]
This function converts a big decimal into its corresponding byte format and inserts it into the specified buffer at the specified index. @param decimal The big decimal to be converted. @param buffer The byte array. @param index The index in the array to begin inserting bytes. @return The number of bytes inserted.
[ "This", "function", "converts", "a", "big", "decimal", "into", "its", "corresponding", "byte", "format", "and", "inserts", "it", "into", "the", "specified", "buffer", "at", "the", "specified", "index", "." ]
train
https://github.com/craterdog/java-general-utilities/blob/a3ff45eaa00c2b8ed5c53efe9fe5166065fc1f57/src/main/java/craterdog/utils/ByteUtils.java#L499-L513
phax/ph-commons
ph-graph/src/main/java/com/helger/graph/utils/GraphVizHelper.java
GraphVizHelper.getGraphAsImageWithGraphVizNeato
@Nonnull public static NonBlockingByteArrayOutputStream getGraphAsImageWithGraphVizNeato (@Nonnull @Nonempty final String sFileType, @Nonnull final String sDOT) throws IOException, InterruptedException { """ Invoked the external process "neato" from the GraphViz package. Attention: this spans a sub-process! @param sFileType The file type to be generated. E.g. "png" - see neato help for details. May neither be <code>null</code> nor empty. @param sDOT The DOT file to be converted to an image. May neither be <code>null</code> nor empty. @return The byte buffer that keeps the converted image. Never <code>null</code>. @throws IOException In case some IO error occurs @throws InterruptedException If the sub-process did not terminate correctly! """ ValueEnforcer.notEmpty (sFileType, "FileType"); ValueEnforcer.notEmpty (sDOT, "DOT"); final ProcessBuilder aPB = new ProcessBuilder ("neato", "-T" + sFileType).redirectErrorStream (false); final Process p = aPB.start (); // Set neato stdin p.getOutputStream ().write (sDOT.getBytes (StandardCharsets.UTF_8)); p.getOutputStream ().close (); // Read neato stdout final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (); StreamHelper.copyInputStreamToOutputStream (p.getInputStream (), aBAOS); p.waitFor (); return aBAOS; }
java
@Nonnull public static NonBlockingByteArrayOutputStream getGraphAsImageWithGraphVizNeato (@Nonnull @Nonempty final String sFileType, @Nonnull final String sDOT) throws IOException, InterruptedException { ValueEnforcer.notEmpty (sFileType, "FileType"); ValueEnforcer.notEmpty (sDOT, "DOT"); final ProcessBuilder aPB = new ProcessBuilder ("neato", "-T" + sFileType).redirectErrorStream (false); final Process p = aPB.start (); // Set neato stdin p.getOutputStream ().write (sDOT.getBytes (StandardCharsets.UTF_8)); p.getOutputStream ().close (); // Read neato stdout final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (); StreamHelper.copyInputStreamToOutputStream (p.getInputStream (), aBAOS); p.waitFor (); return aBAOS; }
[ "@", "Nonnull", "public", "static", "NonBlockingByteArrayOutputStream", "getGraphAsImageWithGraphVizNeato", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sFileType", ",", "@", "Nonnull", "final", "String", "sDOT", ")", "throws", "IOException", ",", "InterruptedException", "{", "ValueEnforcer", ".", "notEmpty", "(", "sFileType", ",", "\"FileType\"", ")", ";", "ValueEnforcer", ".", "notEmpty", "(", "sDOT", ",", "\"DOT\"", ")", ";", "final", "ProcessBuilder", "aPB", "=", "new", "ProcessBuilder", "(", "\"neato\"", ",", "\"-T\"", "+", "sFileType", ")", ".", "redirectErrorStream", "(", "false", ")", ";", "final", "Process", "p", "=", "aPB", ".", "start", "(", ")", ";", "// Set neato stdin", "p", ".", "getOutputStream", "(", ")", ".", "write", "(", "sDOT", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "p", ".", "getOutputStream", "(", ")", ".", "close", "(", ")", ";", "// Read neato stdout", "final", "NonBlockingByteArrayOutputStream", "aBAOS", "=", "new", "NonBlockingByteArrayOutputStream", "(", ")", ";", "StreamHelper", ".", "copyInputStreamToOutputStream", "(", "p", ".", "getInputStream", "(", ")", ",", "aBAOS", ")", ";", "p", ".", "waitFor", "(", ")", ";", "return", "aBAOS", ";", "}" ]
Invoked the external process "neato" from the GraphViz package. Attention: this spans a sub-process! @param sFileType The file type to be generated. E.g. "png" - see neato help for details. May neither be <code>null</code> nor empty. @param sDOT The DOT file to be converted to an image. May neither be <code>null</code> nor empty. @return The byte buffer that keeps the converted image. Never <code>null</code>. @throws IOException In case some IO error occurs @throws InterruptedException If the sub-process did not terminate correctly!
[ "Invoked", "the", "external", "process", "neato", "from", "the", "GraphViz", "package", ".", "Attention", ":", "this", "spans", "a", "sub", "-", "process!" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-graph/src/main/java/com/helger/graph/utils/GraphVizHelper.java#L205-L223
UrielCh/ovh-java-sdk
ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java
ApiOvhSms.serviceName_users_login_DELETE
public void serviceName_users_login_DELETE(String serviceName, String login) throws IOException { """ Delete the sms user given REST: DELETE /sms/{serviceName}/users/{login} @param serviceName [required] The internal name of your SMS offer @param login [required] The sms user login """ String qPath = "/sms/{serviceName}/users/{login}"; StringBuilder sb = path(qPath, serviceName, login); exec(qPath, "DELETE", sb.toString(), null); }
java
public void serviceName_users_login_DELETE(String serviceName, String login) throws IOException { String qPath = "/sms/{serviceName}/users/{login}"; StringBuilder sb = path(qPath, serviceName, login); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "serviceName_users_login_DELETE", "(", "String", "serviceName", ",", "String", "login", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/sms/{serviceName}/users/{login}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "login", ")", ";", "exec", "(", "qPath", ",", "\"DELETE\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
Delete the sms user given REST: DELETE /sms/{serviceName}/users/{login} @param serviceName [required] The internal name of your SMS offer @param login [required] The sms user login
[ "Delete", "the", "sms", "user", "given" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L703-L707
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorageDirectoryRetentionManager.java
NNStorageDirectoryRetentionManager.getBackups
static String[] getBackups(File origin) { """ List all directories that match the backup pattern. Sort from oldest to newest. """ File root = origin.getParentFile(); final String originName = origin.getName(); String[] backups = root.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.startsWith(originName + File.pathSeparator) || name.equals(originName)) return false; try { dateForm.get().parse(name.substring(name.indexOf(File.pathSeparator) + 1)); } catch (ParseException pex) { return false; } return true; } }); if (backups == null) return new String[0]; Arrays.sort(backups, new Comparator<String>() { @Override public int compare(String back1, String back2) { try { Date date1 = dateForm.get().parse(back1.substring(back1 .indexOf(File.pathSeparator) + 1)); Date date2 = dateForm.get().parse(back2.substring(back2 .indexOf(File.pathSeparator) + 1)); // Sorting in reverse order, from later dates to earlier return -1 * date2.compareTo(date1); } catch (ParseException pex) { return 0; } } }); return backups; }
java
static String[] getBackups(File origin) { File root = origin.getParentFile(); final String originName = origin.getName(); String[] backups = root.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.startsWith(originName + File.pathSeparator) || name.equals(originName)) return false; try { dateForm.get().parse(name.substring(name.indexOf(File.pathSeparator) + 1)); } catch (ParseException pex) { return false; } return true; } }); if (backups == null) return new String[0]; Arrays.sort(backups, new Comparator<String>() { @Override public int compare(String back1, String back2) { try { Date date1 = dateForm.get().parse(back1.substring(back1 .indexOf(File.pathSeparator) + 1)); Date date2 = dateForm.get().parse(back2.substring(back2 .indexOf(File.pathSeparator) + 1)); // Sorting in reverse order, from later dates to earlier return -1 * date2.compareTo(date1); } catch (ParseException pex) { return 0; } } }); return backups; }
[ "static", "String", "[", "]", "getBackups", "(", "File", "origin", ")", "{", "File", "root", "=", "origin", ".", "getParentFile", "(", ")", ";", "final", "String", "originName", "=", "origin", ".", "getName", "(", ")", ";", "String", "[", "]", "backups", "=", "root", ".", "list", "(", "new", "FilenameFilter", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "File", "dir", ",", "String", "name", ")", "{", "if", "(", "!", "name", ".", "startsWith", "(", "originName", "+", "File", ".", "pathSeparator", ")", "||", "name", ".", "equals", "(", "originName", ")", ")", "return", "false", ";", "try", "{", "dateForm", ".", "get", "(", ")", ".", "parse", "(", "name", ".", "substring", "(", "name", ".", "indexOf", "(", "File", ".", "pathSeparator", ")", "+", "1", ")", ")", ";", "}", "catch", "(", "ParseException", "pex", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "}", ")", ";", "if", "(", "backups", "==", "null", ")", "return", "new", "String", "[", "0", "]", ";", "Arrays", ".", "sort", "(", "backups", ",", "new", "Comparator", "<", "String", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "String", "back1", ",", "String", "back2", ")", "{", "try", "{", "Date", "date1", "=", "dateForm", ".", "get", "(", ")", ".", "parse", "(", "back1", ".", "substring", "(", "back1", ".", "indexOf", "(", "File", ".", "pathSeparator", ")", "+", "1", ")", ")", ";", "Date", "date2", "=", "dateForm", ".", "get", "(", ")", ".", "parse", "(", "back2", ".", "substring", "(", "back2", ".", "indexOf", "(", "File", ".", "pathSeparator", ")", "+", "1", ")", ")", ";", "// Sorting in reverse order, from later dates to earlier", "return", "-", "1", "*", "date2", ".", "compareTo", "(", "date1", ")", ";", "}", "catch", "(", "ParseException", "pex", ")", "{", "return", "0", ";", "}", "}", "}", ")", ";", "return", "backups", ";", "}" ]
List all directories that match the backup pattern. Sort from oldest to newest.
[ "List", "all", "directories", "that", "match", "the", "backup", "pattern", ".", "Sort", "from", "oldest", "to", "newest", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorageDirectoryRetentionManager.java#L203-L241
requery/requery
requery/src/main/java/io/requery/proxy/EntityProxy.java
EntityProxy.getState
public PropertyState getState(Attribute<E, ?> attribute) { """ Gets the current {@link PropertyState} of a given {@link Attribute}. @param attribute to get @return the state of the attribute """ if (stateless) { return null; } PropertyState state = attribute.getPropertyState().get(entity); return state == null ? PropertyState.FETCH : state; }
java
public PropertyState getState(Attribute<E, ?> attribute) { if (stateless) { return null; } PropertyState state = attribute.getPropertyState().get(entity); return state == null ? PropertyState.FETCH : state; }
[ "public", "PropertyState", "getState", "(", "Attribute", "<", "E", ",", "?", ">", "attribute", ")", "{", "if", "(", "stateless", ")", "{", "return", "null", ";", "}", "PropertyState", "state", "=", "attribute", ".", "getPropertyState", "(", ")", ".", "get", "(", "entity", ")", ";", "return", "state", "==", "null", "?", "PropertyState", ".", "FETCH", ":", "state", ";", "}" ]
Gets the current {@link PropertyState} of a given {@link Attribute}. @param attribute to get @return the state of the attribute
[ "Gets", "the", "current", "{", "@link", "PropertyState", "}", "of", "a", "given", "{", "@link", "Attribute", "}", "." ]
train
https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/proxy/EntityProxy.java#L231-L237
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/Interval.java
Interval.checkFlagExclusiveSet
public static boolean checkFlagExclusiveSet(int flags, int flag, int mask) { """ Utility function to check if a particular flag is set exclusively given a particular set of flags and a mask @param flags flags to check @param flag bit for flag of interest (is this flag set or not) @param mask bitmask of bits to check @return true if flag is exclusively set for flags & mask """ int f = flags & flag; if (f != 0) { return ((flags & mask & ~flag) != 0)? false:true; } else { return false; } }
java
public static boolean checkFlagExclusiveSet(int flags, int flag, int mask) { int f = flags & flag; if (f != 0) { return ((flags & mask & ~flag) != 0)? false:true; } else { return false; } }
[ "public", "static", "boolean", "checkFlagExclusiveSet", "(", "int", "flags", ",", "int", "flag", ",", "int", "mask", ")", "{", "int", "f", "=", "flags", "&", "flag", ";", "if", "(", "f", "!=", "0", ")", "{", "return", "(", "(", "flags", "&", "mask", "&", "~", "flag", ")", "!=", "0", ")", "?", "false", ":", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Utility function to check if a particular flag is set exclusively given a particular set of flags and a mask @param flags flags to check @param flag bit for flag of interest (is this flag set or not) @param mask bitmask of bits to check @return true if flag is exclusively set for flags & mask
[ "Utility", "function", "to", "check", "if", "a", "particular", "flag", "is", "set", "exclusively", "given", "a", "particular", "set", "of", "flags", "and", "a", "mask" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Interval.java#L746-L754
davidcarboni/restolino
src/main/java/com/github/davidcarboni/restolino/Configuration.java
Configuration.configureAuthentication
private void configureAuthentication(String username, String password, String realm) { """ Sets up authentication. @param username The HTTP basic authentication username. @param password The HTTP basic authentication password. @param realm Optional. Defaults to "restolino". """ // If the username is set, set up authentication: if (StringUtils.isNotBlank(username)) { this.username = username; this.password = password; this.realm = StringUtils.defaultIfBlank(realm, "restolino"); authenticationEnabled = true; } }
java
private void configureAuthentication(String username, String password, String realm) { // If the username is set, set up authentication: if (StringUtils.isNotBlank(username)) { this.username = username; this.password = password; this.realm = StringUtils.defaultIfBlank(realm, "restolino"); authenticationEnabled = true; } }
[ "private", "void", "configureAuthentication", "(", "String", "username", ",", "String", "password", ",", "String", "realm", ")", "{", "// If the username is set, set up authentication:", "if", "(", "StringUtils", ".", "isNotBlank", "(", "username", ")", ")", "{", "this", ".", "username", "=", "username", ";", "this", ".", "password", "=", "password", ";", "this", ".", "realm", "=", "StringUtils", ".", "defaultIfBlank", "(", "realm", ",", "\"restolino\"", ")", ";", "authenticationEnabled", "=", "true", ";", "}", "}" ]
Sets up authentication. @param username The HTTP basic authentication username. @param password The HTTP basic authentication password. @param realm Optional. Defaults to "restolino".
[ "Sets", "up", "authentication", "." ]
train
https://github.com/davidcarboni/restolino/blob/3f84ece1bd016fbb597c624d46fcca5a2580a33d/src/main/java/com/github/davidcarboni/restolino/Configuration.java#L229-L240
agmip/agmip-common-functions
src/main/java/org/agmip/common/Functions.java
Functions.dateOffset
public static String dateOffset(String initial, String offset) { """ Offset an AgMIP standard date string (YYYYMMDD) by a set number of days. @param initial AgMIP standard date string @param offset number of days to offset (can be positive or negative integer) @return AgMIP standard date string of <code>initial + offset</code> """ Date date = convertFromAgmipDateString(initial); BigInteger iOffset; if (date == null) { // Invalid date return null; } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); try { iOffset = new BigInteger(offset); cal.add(GregorianCalendar.DAY_OF_MONTH, iOffset.intValue()); } catch (Exception ex) { return null; } return convertToAgmipDateString(cal.getTime()); }
java
public static String dateOffset(String initial, String offset) { Date date = convertFromAgmipDateString(initial); BigInteger iOffset; if (date == null) { // Invalid date return null; } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); try { iOffset = new BigInteger(offset); cal.add(GregorianCalendar.DAY_OF_MONTH, iOffset.intValue()); } catch (Exception ex) { return null; } return convertToAgmipDateString(cal.getTime()); }
[ "public", "static", "String", "dateOffset", "(", "String", "initial", ",", "String", "offset", ")", "{", "Date", "date", "=", "convertFromAgmipDateString", "(", "initial", ")", ";", "BigInteger", "iOffset", ";", "if", "(", "date", "==", "null", ")", "{", "// Invalid date", "return", "null", ";", "}", "GregorianCalendar", "cal", "=", "new", "GregorianCalendar", "(", ")", ";", "cal", ".", "setTime", "(", "date", ")", ";", "try", "{", "iOffset", "=", "new", "BigInteger", "(", "offset", ")", ";", "cal", ".", "add", "(", "GregorianCalendar", ".", "DAY_OF_MONTH", ",", "iOffset", ".", "intValue", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "null", ";", "}", "return", "convertToAgmipDateString", "(", "cal", ".", "getTime", "(", ")", ")", ";", "}" ]
Offset an AgMIP standard date string (YYYYMMDD) by a set number of days. @param initial AgMIP standard date string @param offset number of days to offset (can be positive or negative integer) @return AgMIP standard date string of <code>initial + offset</code>
[ "Offset", "an", "AgMIP", "standard", "date", "string", "(", "YYYYMMDD", ")", "by", "a", "set", "number", "of", "days", "." ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/common/Functions.java#L151-L168
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/metrics/metricsets/OperatingSystemMetricSet.java
OperatingSystemMetricSet.getMethod
private static Method getMethod(Object source, String methodName, String name) { """ Returns a method from the given source object. @param source the source object. @param methodName the name of the method to retrieve. @param name the probe name @return the method """ try { Method method = source.getClass().getMethod(methodName); method.setAccessible(true); return method; } catch (Exception e) { if (LOGGER.isFinestEnabled()) { LOGGER.log(Level.FINEST, "Unable to register OperatingSystemMXBean method " + methodName + " used for probe " + name, e); } return null; } }
java
private static Method getMethod(Object source, String methodName, String name) { try { Method method = source.getClass().getMethod(methodName); method.setAccessible(true); return method; } catch (Exception e) { if (LOGGER.isFinestEnabled()) { LOGGER.log(Level.FINEST, "Unable to register OperatingSystemMXBean method " + methodName + " used for probe " + name, e); } return null; } }
[ "private", "static", "Method", "getMethod", "(", "Object", "source", ",", "String", "methodName", ",", "String", "name", ")", "{", "try", "{", "Method", "method", "=", "source", ".", "getClass", "(", ")", ".", "getMethod", "(", "methodName", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "return", "method", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "LOGGER", ".", "isFinestEnabled", "(", ")", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "FINEST", ",", "\"Unable to register OperatingSystemMXBean method \"", "+", "methodName", "+", "\" used for probe \"", "+", "name", ",", "e", ")", ";", "}", "return", "null", ";", "}", "}" ]
Returns a method from the given source object. @param source the source object. @param methodName the name of the method to retrieve. @param name the probe name @return the method
[ "Returns", "a", "method", "from", "the", "given", "source", "object", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/metrics/metricsets/OperatingSystemMetricSet.java#L109-L121
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.postEpisodeRating
public StatusCode postEpisodeRating(int tvID, int seasonNumber, int episodeNumber, int rating, String sessionID, String guestSessionID) throws MovieDbException { """ This method lets users rate a TV episode. A valid session id or guest session id is required. @param tvID tvID @param seasonNumber seasonNumber @param episodeNumber episodeNumber @param rating rating @param sessionID sessionID @param guestSessionID guestSessionID @return @throws MovieDbException exception """ return tmdbEpisodes.postEpisodeRating(tvID, seasonNumber, episodeNumber, rating, sessionID, guestSessionID); }
java
public StatusCode postEpisodeRating(int tvID, int seasonNumber, int episodeNumber, int rating, String sessionID, String guestSessionID) throws MovieDbException { return tmdbEpisodes.postEpisodeRating(tvID, seasonNumber, episodeNumber, rating, sessionID, guestSessionID); }
[ "public", "StatusCode", "postEpisodeRating", "(", "int", "tvID", ",", "int", "seasonNumber", ",", "int", "episodeNumber", ",", "int", "rating", ",", "String", "sessionID", ",", "String", "guestSessionID", ")", "throws", "MovieDbException", "{", "return", "tmdbEpisodes", ".", "postEpisodeRating", "(", "tvID", ",", "seasonNumber", ",", "episodeNumber", ",", "rating", ",", "sessionID", ",", "guestSessionID", ")", ";", "}" ]
This method lets users rate a TV episode. A valid session id or guest session id is required. @param tvID tvID @param seasonNumber seasonNumber @param episodeNumber episodeNumber @param rating rating @param sessionID sessionID @param guestSessionID guestSessionID @return @throws MovieDbException exception
[ "This", "method", "lets", "users", "rate", "a", "TV", "episode", ".", "A", "valid", "session", "id", "or", "guest", "session", "id", "is", "required", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L1861-L1863
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/transaction/TransactionOptions.java
TransactionOptions.setTimeout
public TransactionOptions setTimeout(long timeout, TimeUnit timeUnit) { """ Sets the timeout. <p/> The timeout determines the maximum lifespan of a transaction. So if a transaction is configured with a timeout of 2 minutes, then it will automatically rollback if it hasn't committed yet. @param timeout the timeout. @param timeUnit the TimeUnit of the timeout. @return the updated TransactionOptions @throws IllegalArgumentException if timeout smaller or equal than 0, or timeUnit is null. @see #getTimeoutMillis() """ if (timeout < 0) { throw new IllegalArgumentException("Timeout can not be negative!"); } if (timeUnit == null) { throw new IllegalArgumentException("timeunit can't be null"); } if (timeout == 0) { setDefaultTimeout(); } else { this.timeoutMillis = timeUnit.toMillis(timeout); } return this; }
java
public TransactionOptions setTimeout(long timeout, TimeUnit timeUnit) { if (timeout < 0) { throw new IllegalArgumentException("Timeout can not be negative!"); } if (timeUnit == null) { throw new IllegalArgumentException("timeunit can't be null"); } if (timeout == 0) { setDefaultTimeout(); } else { this.timeoutMillis = timeUnit.toMillis(timeout); } return this; }
[ "public", "TransactionOptions", "setTimeout", "(", "long", "timeout", ",", "TimeUnit", "timeUnit", ")", "{", "if", "(", "timeout", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Timeout can not be negative!\"", ")", ";", "}", "if", "(", "timeUnit", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"timeunit can't be null\"", ")", ";", "}", "if", "(", "timeout", "==", "0", ")", "{", "setDefaultTimeout", "(", ")", ";", "}", "else", "{", "this", ".", "timeoutMillis", "=", "timeUnit", ".", "toMillis", "(", "timeout", ")", ";", "}", "return", "this", ";", "}" ]
Sets the timeout. <p/> The timeout determines the maximum lifespan of a transaction. So if a transaction is configured with a timeout of 2 minutes, then it will automatically rollback if it hasn't committed yet. @param timeout the timeout. @param timeUnit the TimeUnit of the timeout. @return the updated TransactionOptions @throws IllegalArgumentException if timeout smaller or equal than 0, or timeUnit is null. @see #getTimeoutMillis()
[ "Sets", "the", "timeout", ".", "<p", "/", ">", "The", "timeout", "determines", "the", "maximum", "lifespan", "of", "a", "transaction", ".", "So", "if", "a", "transaction", "is", "configured", "with", "a", "timeout", "of", "2", "minutes", "then", "it", "will", "automatically", "rollback", "if", "it", "hasn", "t", "committed", "yet", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/transaction/TransactionOptions.java#L107-L120
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/log/LogHelper.java
LogHelper.isEnabled
public static boolean isEnabled (@Nonnull final Class <?> aLoggingClass, @Nonnull final IErrorLevel aErrorLevel) { """ Check if logging is enabled for the passed class based on the error level provided @param aLoggingClass The class to determine the logger from. May not be <code>null</code> . @param aErrorLevel The error level. May not be <code>null</code>. @return <code>true</code> if the respective log level is allowed, <code>false</code> if not """ return isEnabled (LoggerFactory.getLogger (aLoggingClass), aErrorLevel); }
java
public static boolean isEnabled (@Nonnull final Class <?> aLoggingClass, @Nonnull final IErrorLevel aErrorLevel) { return isEnabled (LoggerFactory.getLogger (aLoggingClass), aErrorLevel); }
[ "public", "static", "boolean", "isEnabled", "(", "@", "Nonnull", "final", "Class", "<", "?", ">", "aLoggingClass", ",", "@", "Nonnull", "final", "IErrorLevel", "aErrorLevel", ")", "{", "return", "isEnabled", "(", "LoggerFactory", ".", "getLogger", "(", "aLoggingClass", ")", ",", "aErrorLevel", ")", ";", "}" ]
Check if logging is enabled for the passed class based on the error level provided @param aLoggingClass The class to determine the logger from. May not be <code>null</code> . @param aErrorLevel The error level. May not be <code>null</code>. @return <code>true</code> if the respective log level is allowed, <code>false</code> if not
[ "Check", "if", "logging", "is", "enabled", "for", "the", "passed", "class", "based", "on", "the", "error", "level", "provided" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/log/LogHelper.java#L152-L155
mijecu25/dsa
src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java
LinearSearch.searchLast
public static <E> int searchLast(E[] array, E value) { """ Search for the value in the array and return the index of the first occurrence from the end of the array @param <E> the type of elements in this array. @param array array that we are searching in. @param value value that is being searched in the array. @return the index where the value is found in the array, else -1. """ return LinearSearch.searchLast(array, value, 1); }
java
public static <E> int searchLast(E[] array, E value) { return LinearSearch.searchLast(array, value, 1); }
[ "public", "static", "<", "E", ">", "int", "searchLast", "(", "E", "[", "]", "array", ",", "E", "value", ")", "{", "return", "LinearSearch", ".", "searchLast", "(", "array", ",", "value", ",", "1", ")", ";", "}" ]
Search for the value in the array and return the index of the first occurrence from the end of the array @param <E> the type of elements in this array. @param array array that we are searching in. @param value value that is being searched in the array. @return the index where the value is found in the array, else -1.
[ "Search", "for", "the", "value", "in", "the", "array", "and", "return", "the", "index", "of", "the", "first", "occurrence", "from", "the", "end", "of", "the", "array" ]
train
https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L160-L162
infinispan/infinispan
cdi/common/src/main/java/org/infinispan/cdi/common/util/BeanManagerProvider.java
BeanManagerProvider.setBeanManager
public void setBeanManager(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { """ It basically doesn't matter which of the system events we use, but basically we use the {@link AfterBeanDiscovery} event since it allows to use the {@link BeanManagerProvider} for all events which occur after the {@link AfterBeanDiscovery} event. @param afterBeanDiscovery event which we don't actually use ;) @param beanManager the BeanManager we store and make available. """ setBeanManagerProvider(this); BeanManagerInfo bmi = getBeanManagerInfo(getClassLoader(null)); bmi.loadTimeBm = beanManager; }
java
public void setBeanManager(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { setBeanManagerProvider(this); BeanManagerInfo bmi = getBeanManagerInfo(getClassLoader(null)); bmi.loadTimeBm = beanManager; }
[ "public", "void", "setBeanManager", "(", "@", "Observes", "AfterBeanDiscovery", "afterBeanDiscovery", ",", "BeanManager", "beanManager", ")", "{", "setBeanManagerProvider", "(", "this", ")", ";", "BeanManagerInfo", "bmi", "=", "getBeanManagerInfo", "(", "getClassLoader", "(", "null", ")", ")", ";", "bmi", ".", "loadTimeBm", "=", "beanManager", ";", "}" ]
It basically doesn't matter which of the system events we use, but basically we use the {@link AfterBeanDiscovery} event since it allows to use the {@link BeanManagerProvider} for all events which occur after the {@link AfterBeanDiscovery} event. @param afterBeanDiscovery event which we don't actually use ;) @param beanManager the BeanManager we store and make available.
[ "It", "basically", "doesn", "t", "matter", "which", "of", "the", "system", "events", "we", "use", "but", "basically", "we", "use", "the", "{", "@link", "AfterBeanDiscovery", "}", "event", "since", "it", "allows", "to", "use", "the", "{", "@link", "BeanManagerProvider", "}", "for", "all", "events", "which", "occur", "after", "the", "{", "@link", "AfterBeanDiscovery", "}", "event", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/cdi/common/src/main/java/org/infinispan/cdi/common/util/BeanManagerProvider.java#L131-L137
logic-ng/LogicNG
src/main/java/org/logicng/bdds/jbuddy/BDDKernel.java
BDDKernel.satOneSet
public int satOneSet(final int r, final int var, final int pol) { """ Returns an arbitrary model for a given BDD or {@code null} which contains at least the given variables. If a variable is a don't care variable, it will be assigned with the given default value. @param r the BDD root node @param var the set of variable which has to be contained in the model as a BDD @param pol the default value for don't care variables as a BDD @return an arbitrary model of this BDD """ if (isZero(r)) return r; if (!isConst(pol)) throw new IllegalArgumentException("polarity for satOneSet must be a constant"); initRef(); return satOneSetRec(r, var, pol); }
java
public int satOneSet(final int r, final int var, final int pol) { if (isZero(r)) return r; if (!isConst(pol)) throw new IllegalArgumentException("polarity for satOneSet must be a constant"); initRef(); return satOneSetRec(r, var, pol); }
[ "public", "int", "satOneSet", "(", "final", "int", "r", ",", "final", "int", "var", ",", "final", "int", "pol", ")", "{", "if", "(", "isZero", "(", "r", ")", ")", "return", "r", ";", "if", "(", "!", "isConst", "(", "pol", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"polarity for satOneSet must be a constant\"", ")", ";", "initRef", "(", ")", ";", "return", "satOneSetRec", "(", "r", ",", "var", ",", "pol", ")", ";", "}" ]
Returns an arbitrary model for a given BDD or {@code null} which contains at least the given variables. If a variable is a don't care variable, it will be assigned with the given default value. @param r the BDD root node @param var the set of variable which has to be contained in the model as a BDD @param pol the default value for don't care variables as a BDD @return an arbitrary model of this BDD
[ "Returns", "an", "arbitrary", "model", "for", "a", "given", "BDD", "or", "{" ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/bdds/jbuddy/BDDKernel.java#L819-L826
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updateEntityRoleAsync
public Observable<OperationStatus> updateEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateEntityRoleOptionalParameter updateEntityRoleOptionalParameter) { """ Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updateEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object """ return updateEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> updateEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateEntityRoleOptionalParameter updateEntityRoleOptionalParameter) { return updateEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "updateEntityRoleAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ",", "UpdateEntityRoleOptionalParameter", "updateEntityRoleOptionalParameter", ")", "{", "return", "updateEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "roleId", ",", "updateEntityRoleOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatus", ">", ",", "OperationStatus", ">", "(", ")", "{", "@", "Override", "public", "OperationStatus", "call", "(", "ServiceResponse", "<", "OperationStatus", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updateEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Update", "an", "entity", "role", "for", "a", "given", "entity", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L10873-L10880
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/WebJBossASClient.java
WebJBossASClient.addConnector
public void addConnector(String name, ConnectorConfiguration connectorConfig) throws Exception { """ Add a new web connector, which may be a secure SSL connector (HTTPS) or not (HTTP). @param name name of new connector to add @param connectorConfig the connector's configuration @throws Exception any error """ ModelNode fullRequest; final Address connectorAddress = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, name); final ModelNode connectorRequest = createRequest(ADD, connectorAddress); setPossibleExpression(connectorRequest, "executor", connectorConfig.getExecutor()); setPossibleExpression(connectorRequest, "max-connections", connectorConfig.getMaxConnections()); setPossibleExpression(connectorRequest, "max-post-size", connectorConfig.getMaxPostSize()); setPossibleExpression(connectorRequest, "max-save-post-size", connectorConfig.getMaxSavePostSize()); setPossibleExpression(connectorRequest, "protocol", connectorConfig.getProtocol()); setPossibleExpression(connectorRequest, "proxy-name", connectorConfig.getProxyName()); setPossibleExpression(connectorRequest, "proxy-port", connectorConfig.getProxyPort()); setPossibleExpression(connectorRequest, "scheme", connectorConfig.getScheme()); setPossibleExpression(connectorRequest, "socket-binding", connectorConfig.getSocketBinding()); setPossibleExpression(connectorRequest, "redirect-port", connectorConfig.getRedirectPort()); setPossibleExpression(connectorRequest, "enabled", String.valueOf(connectorConfig.isEnabled())); setPossibleExpression(connectorRequest, "enable-lookups", String.valueOf(connectorConfig.isEnableLookups())); setPossibleExpression(connectorRequest, "secure", String.valueOf(connectorConfig.isSecure())); SSLConfiguration sslConfig = connectorConfig.getSslConfiguration(); if (sslConfig != null) { final Address sslAddress = connectorAddress.clone().add(SSL, "configuration"); // MUST be "configuration" final ModelNode sslRequest = createRequest(ADD, sslAddress); setPossibleExpression(sslRequest, "ca-certificate-file", sslConfig.getCaCertificateFile()); setPossibleExpression(sslRequest, "ca-certificate-password", sslConfig.getCaCertificatePassword()); setPossibleExpression(sslRequest, "ca-revocation-url", sslConfig.getCaRevocationUrl()); setPossibleExpression(sslRequest, "certificate-file", sslConfig.getCertificateFile()); setPossibleExpression(sslRequest, "certificate-key-file", sslConfig.getCertificateKeyFile()); setPossibleExpression(sslRequest, "cipher-suite", sslConfig.getCipherSuite()); setPossibleExpression(sslRequest, "key-alias", sslConfig.getKeyAlias()); setPossibleExpression(sslRequest, "keystore-type", sslConfig.getKeystoreType()); setPossibleExpression(sslRequest, "name", sslConfig.getName()); setPossibleExpression(sslRequest, "password", sslConfig.getPassword()); setPossibleExpression(sslRequest, "protocol", sslConfig.getProtocol()); setPossibleExpression(sslRequest, "session-cache-size", sslConfig.getSessionCacheSize()); setPossibleExpression(sslRequest, "session-timeout", sslConfig.getSessionTimeout()); setPossibleExpression(sslRequest, "truststore-type", sslConfig.getTruststoreType()); setPossibleExpression(sslRequest, "verify-client", sslConfig.getVerifyClient()); setPossibleExpression(sslRequest, "verify-depth", sslConfig.getVerifyDepth()); fullRequest = createBatchRequest(connectorRequest, sslRequest); } else { fullRequest = connectorRequest; } final ModelNode response = execute(fullRequest); if (!isSuccess(response)) { throw new FailureException(response, "Failed to add new connector [" + name + "]"); } return; }
java
public void addConnector(String name, ConnectorConfiguration connectorConfig) throws Exception { ModelNode fullRequest; final Address connectorAddress = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, name); final ModelNode connectorRequest = createRequest(ADD, connectorAddress); setPossibleExpression(connectorRequest, "executor", connectorConfig.getExecutor()); setPossibleExpression(connectorRequest, "max-connections", connectorConfig.getMaxConnections()); setPossibleExpression(connectorRequest, "max-post-size", connectorConfig.getMaxPostSize()); setPossibleExpression(connectorRequest, "max-save-post-size", connectorConfig.getMaxSavePostSize()); setPossibleExpression(connectorRequest, "protocol", connectorConfig.getProtocol()); setPossibleExpression(connectorRequest, "proxy-name", connectorConfig.getProxyName()); setPossibleExpression(connectorRequest, "proxy-port", connectorConfig.getProxyPort()); setPossibleExpression(connectorRequest, "scheme", connectorConfig.getScheme()); setPossibleExpression(connectorRequest, "socket-binding", connectorConfig.getSocketBinding()); setPossibleExpression(connectorRequest, "redirect-port", connectorConfig.getRedirectPort()); setPossibleExpression(connectorRequest, "enabled", String.valueOf(connectorConfig.isEnabled())); setPossibleExpression(connectorRequest, "enable-lookups", String.valueOf(connectorConfig.isEnableLookups())); setPossibleExpression(connectorRequest, "secure", String.valueOf(connectorConfig.isSecure())); SSLConfiguration sslConfig = connectorConfig.getSslConfiguration(); if (sslConfig != null) { final Address sslAddress = connectorAddress.clone().add(SSL, "configuration"); // MUST be "configuration" final ModelNode sslRequest = createRequest(ADD, sslAddress); setPossibleExpression(sslRequest, "ca-certificate-file", sslConfig.getCaCertificateFile()); setPossibleExpression(sslRequest, "ca-certificate-password", sslConfig.getCaCertificatePassword()); setPossibleExpression(sslRequest, "ca-revocation-url", sslConfig.getCaRevocationUrl()); setPossibleExpression(sslRequest, "certificate-file", sslConfig.getCertificateFile()); setPossibleExpression(sslRequest, "certificate-key-file", sslConfig.getCertificateKeyFile()); setPossibleExpression(sslRequest, "cipher-suite", sslConfig.getCipherSuite()); setPossibleExpression(sslRequest, "key-alias", sslConfig.getKeyAlias()); setPossibleExpression(sslRequest, "keystore-type", sslConfig.getKeystoreType()); setPossibleExpression(sslRequest, "name", sslConfig.getName()); setPossibleExpression(sslRequest, "password", sslConfig.getPassword()); setPossibleExpression(sslRequest, "protocol", sslConfig.getProtocol()); setPossibleExpression(sslRequest, "session-cache-size", sslConfig.getSessionCacheSize()); setPossibleExpression(sslRequest, "session-timeout", sslConfig.getSessionTimeout()); setPossibleExpression(sslRequest, "truststore-type", sslConfig.getTruststoreType()); setPossibleExpression(sslRequest, "verify-client", sslConfig.getVerifyClient()); setPossibleExpression(sslRequest, "verify-depth", sslConfig.getVerifyDepth()); fullRequest = createBatchRequest(connectorRequest, sslRequest); } else { fullRequest = connectorRequest; } final ModelNode response = execute(fullRequest); if (!isSuccess(response)) { throw new FailureException(response, "Failed to add new connector [" + name + "]"); } return; }
[ "public", "void", "addConnector", "(", "String", "name", ",", "ConnectorConfiguration", "connectorConfig", ")", "throws", "Exception", "{", "ModelNode", "fullRequest", ";", "final", "Address", "connectorAddress", "=", "Address", ".", "root", "(", ")", ".", "add", "(", "SUBSYSTEM", ",", "SUBSYSTEM_WEB", ",", "CONNECTOR", ",", "name", ")", ";", "final", "ModelNode", "connectorRequest", "=", "createRequest", "(", "ADD", ",", "connectorAddress", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"executor\"", ",", "connectorConfig", ".", "getExecutor", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"max-connections\"", ",", "connectorConfig", ".", "getMaxConnections", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"max-post-size\"", ",", "connectorConfig", ".", "getMaxPostSize", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"max-save-post-size\"", ",", "connectorConfig", ".", "getMaxSavePostSize", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"protocol\"", ",", "connectorConfig", ".", "getProtocol", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"proxy-name\"", ",", "connectorConfig", ".", "getProxyName", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"proxy-port\"", ",", "connectorConfig", ".", "getProxyPort", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"scheme\"", ",", "connectorConfig", ".", "getScheme", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"socket-binding\"", ",", "connectorConfig", ".", "getSocketBinding", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"redirect-port\"", ",", "connectorConfig", ".", "getRedirectPort", "(", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"enabled\"", ",", "String", ".", "valueOf", "(", "connectorConfig", ".", "isEnabled", "(", ")", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"enable-lookups\"", ",", "String", ".", "valueOf", "(", "connectorConfig", ".", "isEnableLookups", "(", ")", ")", ")", ";", "setPossibleExpression", "(", "connectorRequest", ",", "\"secure\"", ",", "String", ".", "valueOf", "(", "connectorConfig", ".", "isSecure", "(", ")", ")", ")", ";", "SSLConfiguration", "sslConfig", "=", "connectorConfig", ".", "getSslConfiguration", "(", ")", ";", "if", "(", "sslConfig", "!=", "null", ")", "{", "final", "Address", "sslAddress", "=", "connectorAddress", ".", "clone", "(", ")", ".", "add", "(", "SSL", ",", "\"configuration\"", ")", ";", "// MUST be \"configuration\"", "final", "ModelNode", "sslRequest", "=", "createRequest", "(", "ADD", ",", "sslAddress", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"ca-certificate-file\"", ",", "sslConfig", ".", "getCaCertificateFile", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"ca-certificate-password\"", ",", "sslConfig", ".", "getCaCertificatePassword", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"ca-revocation-url\"", ",", "sslConfig", ".", "getCaRevocationUrl", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"certificate-file\"", ",", "sslConfig", ".", "getCertificateFile", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"certificate-key-file\"", ",", "sslConfig", ".", "getCertificateKeyFile", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"cipher-suite\"", ",", "sslConfig", ".", "getCipherSuite", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"key-alias\"", ",", "sslConfig", ".", "getKeyAlias", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"keystore-type\"", ",", "sslConfig", ".", "getKeystoreType", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"name\"", ",", "sslConfig", ".", "getName", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"password\"", ",", "sslConfig", ".", "getPassword", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"protocol\"", ",", "sslConfig", ".", "getProtocol", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"session-cache-size\"", ",", "sslConfig", ".", "getSessionCacheSize", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"session-timeout\"", ",", "sslConfig", ".", "getSessionTimeout", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"truststore-type\"", ",", "sslConfig", ".", "getTruststoreType", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"verify-client\"", ",", "sslConfig", ".", "getVerifyClient", "(", ")", ")", ";", "setPossibleExpression", "(", "sslRequest", ",", "\"verify-depth\"", ",", "sslConfig", ".", "getVerifyDepth", "(", ")", ")", ";", "fullRequest", "=", "createBatchRequest", "(", "connectorRequest", ",", "sslRequest", ")", ";", "}", "else", "{", "fullRequest", "=", "connectorRequest", ";", "}", "final", "ModelNode", "response", "=", "execute", "(", "fullRequest", ")", ";", "if", "(", "!", "isSuccess", "(", "response", ")", ")", "{", "throw", "new", "FailureException", "(", "response", ",", "\"Failed to add new connector [\"", "+", "name", "+", "\"]\"", ")", ";", "}", "return", ";", "}" ]
Add a new web connector, which may be a secure SSL connector (HTTPS) or not (HTTP). @param name name of new connector to add @param connectorConfig the connector's configuration @throws Exception any error
[ "Add", "a", "new", "web", "connector", "which", "may", "be", "a", "secure", "SSL", "connector", "(", "HTTPS", ")", "or", "not", "(", "HTTP", ")", "." ]
train
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/WebJBossASClient.java#L133-L182
stephenc/redmine-java-api
src/main/java/org/redmine/ta/internal/RedmineJSONBuilder.java
RedmineJSONBuilder.writeTracker
static void writeTracker(JSONWriter writer, Tracker tracker) throws JSONException { """ Writes a tracker. @param writer used writer. @param tracker tracker to writer. @throws JSONException if error occurs. """ writer.key("id"); writer.value(tracker.getId()); writer.key("name"); writer.value(tracker.getName()); }
java
static void writeTracker(JSONWriter writer, Tracker tracker) throws JSONException { writer.key("id"); writer.value(tracker.getId()); writer.key("name"); writer.value(tracker.getName()); }
[ "static", "void", "writeTracker", "(", "JSONWriter", "writer", ",", "Tracker", "tracker", ")", "throws", "JSONException", "{", "writer", ".", "key", "(", "\"id\"", ")", ";", "writer", ".", "value", "(", "tracker", ".", "getId", "(", ")", ")", ";", "writer", ".", "key", "(", "\"name\"", ")", ";", "writer", ".", "value", "(", "tracker", ".", "getName", "(", ")", ")", ";", "}" ]
Writes a tracker. @param writer used writer. @param tracker tracker to writer. @throws JSONException if error occurs.
[ "Writes", "a", "tracker", "." ]
train
https://github.com/stephenc/redmine-java-api/blob/7e5270c84aba32d74a506260ec47ff86ab6c9d84/src/main/java/org/redmine/ta/internal/RedmineJSONBuilder.java#L161-L167
anotheria/configureme
src/main/java/org/configureme/sources/ConfigurationSourceKey.java
ConfigurationSourceKey.xmlFile
public static final ConfigurationSourceKey xmlFile(final String name) { """ Creates a new configuration source key for xml files. @param name name of the xml file. @return a new configuration source key instance for xml files """ return new ConfigurationSourceKey(Type.FILE, Format.XML, name); }
java
public static final ConfigurationSourceKey xmlFile(final String name){ return new ConfigurationSourceKey(Type.FILE, Format.XML, name); }
[ "public", "static", "final", "ConfigurationSourceKey", "xmlFile", "(", "final", "String", "name", ")", "{", "return", "new", "ConfigurationSourceKey", "(", "Type", ".", "FILE", ",", "Format", ".", "XML", ",", "name", ")", ";", "}" ]
Creates a new configuration source key for xml files. @param name name of the xml file. @return a new configuration source key instance for xml files
[ "Creates", "a", "new", "configuration", "source", "key", "for", "xml", "files", "." ]
train
https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/sources/ConfigurationSourceKey.java#L211-L213
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java
JsonModelCoder.getList
public List<T> getList(JsonPullParser parser) throws IOException, JsonFormatException { """ Attempts to parse the given data as {@link List} of objects. @param parser {@link JsonPullParser} with some JSON-formatted data @return {@link List} of objects @throws IOException @throws JsonFormatException The given data is malformed, or its type is unexpected """ return getList(parser, null); }
java
public List<T> getList(JsonPullParser parser) throws IOException, JsonFormatException { return getList(parser, null); }
[ "public", "List", "<", "T", ">", "getList", "(", "JsonPullParser", "parser", ")", "throws", "IOException", ",", "JsonFormatException", "{", "return", "getList", "(", "parser", ",", "null", ")", ";", "}" ]
Attempts to parse the given data as {@link List} of objects. @param parser {@link JsonPullParser} with some JSON-formatted data @return {@link List} of objects @throws IOException @throws JsonFormatException The given data is malformed, or its type is unexpected
[ "Attempts", "to", "parse", "the", "given", "data", "as", "{", "@link", "List", "}", "of", "objects", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java#L112-L114
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog2/utilities/ConfigurationMapConverter.java
ConfigurationMapConverter.convertValues
public static Map<String, Object> convertValues(final Map<String, Object> data, final ConfigurationRequest configurationRequest) throws ValidationException { """ Converts the values in the map to the requested types. This has been copied from the Graylog web interface and should be removed once we have better configuration objects. """ final Map<String, Object> configuration = Maps.newHashMapWithExpectedSize(data.size()); final Map<String, Map<String, Object>> configurationFields = configurationRequest.asList(); for (final Map.Entry<String, Object> entry : data.entrySet()) { final String field = entry.getKey(); final Map<String, Object> fieldDescription = configurationFields.get(field); if (fieldDescription == null || fieldDescription.isEmpty()) { throw new ValidationException(field, "Unknown configuration field description for field \"" + field + "\""); } final String type = (String) fieldDescription.get("type"); // Decide what to cast to. (string, bool, number) Object value; switch (type) { case "text": case "dropdown": value = entry.getValue() == null ? "" : String.valueOf(entry.getValue()); break; case "number": try { value = Integer.parseInt(String.valueOf(entry.getValue())); } catch (NumberFormatException e) { // If a numeric field is optional and not provided, use null as value if ("true".equals(String.valueOf(fieldDescription.get("is_optional")))) { value = null; } else { throw new ValidationException(field, e.getMessage()); } } break; case "boolean": value = "true".equalsIgnoreCase(String.valueOf(entry.getValue())); break; case "list": final List<?> valueList = entry.getValue() == null ? Collections.emptyList() : (List<?>) entry.getValue(); value = valueList.stream() .filter(o -> o != null && o instanceof String) .map(String::valueOf) .collect(Collectors.toList()); break; default: throw new ValidationException(field, "Unknown configuration field type \"" + type + "\""); } configuration.put(field, value); } return configuration; }
java
public static Map<String, Object> convertValues(final Map<String, Object> data, final ConfigurationRequest configurationRequest) throws ValidationException { final Map<String, Object> configuration = Maps.newHashMapWithExpectedSize(data.size()); final Map<String, Map<String, Object>> configurationFields = configurationRequest.asList(); for (final Map.Entry<String, Object> entry : data.entrySet()) { final String field = entry.getKey(); final Map<String, Object> fieldDescription = configurationFields.get(field); if (fieldDescription == null || fieldDescription.isEmpty()) { throw new ValidationException(field, "Unknown configuration field description for field \"" + field + "\""); } final String type = (String) fieldDescription.get("type"); // Decide what to cast to. (string, bool, number) Object value; switch (type) { case "text": case "dropdown": value = entry.getValue() == null ? "" : String.valueOf(entry.getValue()); break; case "number": try { value = Integer.parseInt(String.valueOf(entry.getValue())); } catch (NumberFormatException e) { // If a numeric field is optional and not provided, use null as value if ("true".equals(String.valueOf(fieldDescription.get("is_optional")))) { value = null; } else { throw new ValidationException(field, e.getMessage()); } } break; case "boolean": value = "true".equalsIgnoreCase(String.valueOf(entry.getValue())); break; case "list": final List<?> valueList = entry.getValue() == null ? Collections.emptyList() : (List<?>) entry.getValue(); value = valueList.stream() .filter(o -> o != null && o instanceof String) .map(String::valueOf) .collect(Collectors.toList()); break; default: throw new ValidationException(field, "Unknown configuration field type \"" + type + "\""); } configuration.put(field, value); } return configuration; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "convertValues", "(", "final", "Map", "<", "String", ",", "Object", ">", "data", ",", "final", "ConfigurationRequest", "configurationRequest", ")", "throws", "ValidationException", "{", "final", "Map", "<", "String", ",", "Object", ">", "configuration", "=", "Maps", ".", "newHashMapWithExpectedSize", "(", "data", ".", "size", "(", ")", ")", ";", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "configurationFields", "=", "configurationRequest", ".", "asList", "(", ")", ";", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "data", ".", "entrySet", "(", ")", ")", "{", "final", "String", "field", "=", "entry", ".", "getKey", "(", ")", ";", "final", "Map", "<", "String", ",", "Object", ">", "fieldDescription", "=", "configurationFields", ".", "get", "(", "field", ")", ";", "if", "(", "fieldDescription", "==", "null", "||", "fieldDescription", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "ValidationException", "(", "field", ",", "\"Unknown configuration field description for field \\\"\"", "+", "field", "+", "\"\\\"\"", ")", ";", "}", "final", "String", "type", "=", "(", "String", ")", "fieldDescription", ".", "get", "(", "\"type\"", ")", ";", "// Decide what to cast to. (string, bool, number)", "Object", "value", ";", "switch", "(", "type", ")", "{", "case", "\"text\"", ":", "case", "\"dropdown\"", ":", "value", "=", "entry", ".", "getValue", "(", ")", "==", "null", "?", "\"\"", ":", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ";", "break", ";", "case", "\"number\"", ":", "try", "{", "value", "=", "Integer", ".", "parseInt", "(", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "// If a numeric field is optional and not provided, use null as value", "if", "(", "\"true\"", ".", "equals", "(", "String", ".", "valueOf", "(", "fieldDescription", ".", "get", "(", "\"is_optional\"", ")", ")", ")", ")", "{", "value", "=", "null", ";", "}", "else", "{", "throw", "new", "ValidationException", "(", "field", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "break", ";", "case", "\"boolean\"", ":", "value", "=", "\"true\"", ".", "equalsIgnoreCase", "(", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "break", ";", "case", "\"list\"", ":", "final", "List", "<", "?", ">", "valueList", "=", "entry", ".", "getValue", "(", ")", "==", "null", "?", "Collections", ".", "emptyList", "(", ")", ":", "(", "List", "<", "?", ">", ")", "entry", ".", "getValue", "(", ")", ";", "value", "=", "valueList", ".", "stream", "(", ")", ".", "filter", "(", "o", "->", "o", "!=", "null", "&&", "o", "instanceof", "String", ")", ".", "map", "(", "String", "::", "valueOf", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "ValidationException", "(", "field", ",", "\"Unknown configuration field type \\\"\"", "+", "type", "+", "\"\\\"\"", ")", ";", "}", "configuration", ".", "put", "(", "field", ",", "value", ")", ";", "}", "return", "configuration", ";", "}" ]
Converts the values in the map to the requested types. This has been copied from the Graylog web interface and should be removed once we have better configuration objects.
[ "Converts", "the", "values", "in", "the", "map", "to", "the", "requested", "types", ".", "This", "has", "been", "copied", "from", "the", "Graylog", "web", "interface", "and", "should", "be", "removed", "once", "we", "have", "better", "configuration", "objects", "." ]
train
https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/utilities/ConfigurationMapConverter.java#L33-L83
Cornutum/tcases
tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java
TupleGenerator.makeComplete
private boolean makeComplete( TestCaseDef testCase, VarTupleSet tuples, List<VarDef> vars) { """ Using selections from the given set of tuples, completes binding for all remaining variables. Returns true if all variables have been bound. """ boolean complete; // Test case still missing a required property? if( testCase.isSatisfied()) { // No, complete bindings for remaining variables complete = completeSatisfied( testCase, tuples, vars); } else { // Yes, find tuples that contain satisfying bindings. int prevBindings = testCase.getBindingCount(); Iterator<Tuple> satisfyingTuples = getSatisfyingTuples( testCase, tuples); for( complete = false; satisfyingTuples.hasNext() && !( // Does this tuple lead to satisfaction of all current test case conditions? makeSatisfied( testCase, tuples, satisfyingTuples.next()) // Can we complete bindings for remaining variables? && (complete = completeSatisfied( testCase, tuples, vars))); // No, try next tuple testCase.revertBindings( prevBindings)); } return complete; }
java
private boolean makeComplete( TestCaseDef testCase, VarTupleSet tuples, List<VarDef> vars) { boolean complete; // Test case still missing a required property? if( testCase.isSatisfied()) { // No, complete bindings for remaining variables complete = completeSatisfied( testCase, tuples, vars); } else { // Yes, find tuples that contain satisfying bindings. int prevBindings = testCase.getBindingCount(); Iterator<Tuple> satisfyingTuples = getSatisfyingTuples( testCase, tuples); for( complete = false; satisfyingTuples.hasNext() && !( // Does this tuple lead to satisfaction of all current test case conditions? makeSatisfied( testCase, tuples, satisfyingTuples.next()) // Can we complete bindings for remaining variables? && (complete = completeSatisfied( testCase, tuples, vars))); // No, try next tuple testCase.revertBindings( prevBindings)); } return complete; }
[ "private", "boolean", "makeComplete", "(", "TestCaseDef", "testCase", ",", "VarTupleSet", "tuples", ",", "List", "<", "VarDef", ">", "vars", ")", "{", "boolean", "complete", ";", "// Test case still missing a required property?", "if", "(", "testCase", ".", "isSatisfied", "(", ")", ")", "{", "// No, complete bindings for remaining variables", "complete", "=", "completeSatisfied", "(", "testCase", ",", "tuples", ",", "vars", ")", ";", "}", "else", "{", "// Yes, find tuples that contain satisfying bindings.", "int", "prevBindings", "=", "testCase", ".", "getBindingCount", "(", ")", ";", "Iterator", "<", "Tuple", ">", "satisfyingTuples", "=", "getSatisfyingTuples", "(", "testCase", ",", "tuples", ")", ";", "for", "(", "complete", "=", "false", ";", "satisfyingTuples", ".", "hasNext", "(", ")", "&&", "!", "(", "// Does this tuple lead to satisfaction of all current test case conditions?", "makeSatisfied", "(", "testCase", ",", "tuples", ",", "satisfyingTuples", ".", "next", "(", ")", ")", "// Can we complete bindings for remaining variables?", "&&", "(", "complete", "=", "completeSatisfied", "(", "testCase", ",", "tuples", ",", "vars", ")", ")", ")", ";", "// No, try next tuple", "testCase", ".", "revertBindings", "(", "prevBindings", ")", ")", ";", "}", "return", "complete", ";", "}" ]
Using selections from the given set of tuples, completes binding for all remaining variables. Returns true if all variables have been bound.
[ "Using", "selections", "from", "the", "given", "set", "of", "tuples", "completes", "binding", "for", "all", "remaining", "variables", ".", "Returns", "true", "if", "all", "variables", "have", "been", "bound", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java#L395-L425
Azure/azure-sdk-for-java
hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java
ClustersInner.rotateDiskEncryptionKey
public void rotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { """ Rotate disk encryption key of the specified HDInsight cluster. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param parameters The parameters for the disk encryption operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
java
public void rotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
[ "public", "void", "rotateDiskEncryptionKey", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "ClusterDiskEncryptionParameters", "parameters", ")", "{", "rotateDiskEncryptionKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Rotate disk encryption key of the specified HDInsight cluster. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param parameters The parameters for the disk encryption operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Rotate", "disk", "encryption", "key", "of", "the", "specified", "HDInsight", "cluster", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java#L1293-L1295
OpenLiberty/open-liberty
dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/BoundedBuffer.java
BoundedBuffer.poll
@Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { """ Removes an object from the buffer. If the buffer is empty, the call blocks for up to a specified amount of time before it gives up. @param timeout - the amount of time, that the caller is willing to wait in the event of an empty buffer. @param unit - the unit of time """ T old = poll(); long endTimeMillis = System.currentTimeMillis() + unit.toMillis(timeout); long timeLeftMillis = endTimeMillis - System.currentTimeMillis(); int spinctr = SPINS_TAKE_; while (old == null && timeLeftMillis > 0) { while (size() <= 0 && timeLeftMillis > 0) { if (spinctr > 0) { // busy wait if (YIELD_TAKE_) Thread.yield(); spinctr--; } else { // block on lock waitGet_(timeLeftMillis); } timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } old = poll(); timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } return old; }
java
@Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { T old = poll(); long endTimeMillis = System.currentTimeMillis() + unit.toMillis(timeout); long timeLeftMillis = endTimeMillis - System.currentTimeMillis(); int spinctr = SPINS_TAKE_; while (old == null && timeLeftMillis > 0) { while (size() <= 0 && timeLeftMillis > 0) { if (spinctr > 0) { // busy wait if (YIELD_TAKE_) Thread.yield(); spinctr--; } else { // block on lock waitGet_(timeLeftMillis); } timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } old = poll(); timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } return old; }
[ "@", "Override", "public", "T", "poll", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "T", "old", "=", "poll", "(", ")", ";", "long", "endTimeMillis", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "unit", ".", "toMillis", "(", "timeout", ")", ";", "long", "timeLeftMillis", "=", "endTimeMillis", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "int", "spinctr", "=", "SPINS_TAKE_", ";", "while", "(", "old", "==", "null", "&&", "timeLeftMillis", ">", "0", ")", "{", "while", "(", "size", "(", ")", "<=", "0", "&&", "timeLeftMillis", ">", "0", ")", "{", "if", "(", "spinctr", ">", "0", ")", "{", "// busy wait", "if", "(", "YIELD_TAKE_", ")", "Thread", ".", "yield", "(", ")", ";", "spinctr", "--", ";", "}", "else", "{", "// block on lock", "waitGet_", "(", "timeLeftMillis", ")", ";", "}", "timeLeftMillis", "=", "endTimeMillis", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "old", "=", "poll", "(", ")", ";", "timeLeftMillis", "=", "endTimeMillis", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "return", "old", ";", "}" ]
Removes an object from the buffer. If the buffer is empty, the call blocks for up to a specified amount of time before it gives up. @param timeout - the amount of time, that the caller is willing to wait in the event of an empty buffer. @param unit - the unit of time
[ "Removes", "an", "object", "from", "the", "buffer", ".", "If", "the", "buffer", "is", "empty", "the", "call", "blocks", "for", "up", "to", "a", "specified", "amount", "of", "time", "before", "it", "gives", "up", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/BoundedBuffer.java#L664-L690
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/DocBookUtilities.java
DocBookUtilities.validateTableRow
public static boolean validateTableRow(final Node row, final int numColumns) { """ Check to ensure that a docbook row has the required number of columns for a table. @param row The DOM row element to be checked. @param numColumns The number of entry elements that should exist in the row. @return True if the row has the required number of entries, otherwise false. """ assert row != null; assert row.getNodeName().equals("row") || row.getNodeName().equals("tr"); if (row.getNodeName().equals("row")) { final List<Node> entries = XMLUtilities.getDirectChildNodes(row, "entry"); final List<Node> entryTbls = XMLUtilities.getDirectChildNodes(row, "entrytbl"); if ((entries.size() + entryTbls.size()) <= numColumns) { for (final Node entryTbl : entryTbls) { if (!validateEntryTbl((Element) entryTbl)) return false; } return true; } else { return false; } } else { final List<Node> nodes = XMLUtilities.getDirectChildNodes(row, "td", "th"); return nodes.size() <= numColumns; } }
java
public static boolean validateTableRow(final Node row, final int numColumns) { assert row != null; assert row.getNodeName().equals("row") || row.getNodeName().equals("tr"); if (row.getNodeName().equals("row")) { final List<Node> entries = XMLUtilities.getDirectChildNodes(row, "entry"); final List<Node> entryTbls = XMLUtilities.getDirectChildNodes(row, "entrytbl"); if ((entries.size() + entryTbls.size()) <= numColumns) { for (final Node entryTbl : entryTbls) { if (!validateEntryTbl((Element) entryTbl)) return false; } return true; } else { return false; } } else { final List<Node> nodes = XMLUtilities.getDirectChildNodes(row, "td", "th"); return nodes.size() <= numColumns; } }
[ "public", "static", "boolean", "validateTableRow", "(", "final", "Node", "row", ",", "final", "int", "numColumns", ")", "{", "assert", "row", "!=", "null", ";", "assert", "row", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"row\"", ")", "||", "row", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"tr\"", ")", ";", "if", "(", "row", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"row\"", ")", ")", "{", "final", "List", "<", "Node", ">", "entries", "=", "XMLUtilities", ".", "getDirectChildNodes", "(", "row", ",", "\"entry\"", ")", ";", "final", "List", "<", "Node", ">", "entryTbls", "=", "XMLUtilities", ".", "getDirectChildNodes", "(", "row", ",", "\"entrytbl\"", ")", ";", "if", "(", "(", "entries", ".", "size", "(", ")", "+", "entryTbls", ".", "size", "(", ")", ")", "<=", "numColumns", ")", "{", "for", "(", "final", "Node", "entryTbl", ":", "entryTbls", ")", "{", "if", "(", "!", "validateEntryTbl", "(", "(", "Element", ")", "entryTbl", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "final", "List", "<", "Node", ">", "nodes", "=", "XMLUtilities", ".", "getDirectChildNodes", "(", "row", ",", "\"td\"", ",", "\"th\"", ")", ";", "return", "nodes", ".", "size", "(", ")", "<=", "numColumns", ";", "}", "}" ]
Check to ensure that a docbook row has the required number of columns for a table. @param row The DOM row element to be checked. @param numColumns The number of entry elements that should exist in the row. @return True if the row has the required number of entries, otherwise false.
[ "Check", "to", "ensure", "that", "a", "docbook", "row", "has", "the", "required", "number", "of", "columns", "for", "a", "table", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/DocBookUtilities.java#L3122-L3143
jbake-org/jbake
jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java
JBakeConfigurationFactory.createDefaultJbakeConfiguration
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache) throws ConfigurationException { """ Creates a {@link DefaultJBakeConfiguration} @param sourceFolder The source folder of the project @param destination The destination folder to render and copy files to @param isClearCache Whether to clear database cache or not @return A configuration by given parameters @throws ConfigurationException if loading the configuration fails """ DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
java
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache) throws ConfigurationException { DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
[ "public", "DefaultJBakeConfiguration", "createDefaultJbakeConfiguration", "(", "File", "sourceFolder", ",", "File", "destination", ",", "boolean", "isClearCache", ")", "throws", "ConfigurationException", "{", "DefaultJBakeConfiguration", "configuration", "=", "(", "DefaultJBakeConfiguration", ")", "getConfigUtil", "(", ")", ".", "loadConfig", "(", "sourceFolder", ")", ";", "configuration", ".", "setDestinationFolder", "(", "destination", ")", ";", "configuration", ".", "setClearCache", "(", "isClearCache", ")", ";", "return", "configuration", ";", "}" ]
Creates a {@link DefaultJBakeConfiguration} @param sourceFolder The source folder of the project @param destination The destination folder to render and copy files to @param isClearCache Whether to clear database cache or not @return A configuration by given parameters @throws ConfigurationException if loading the configuration fails
[ "Creates", "a", "{" ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java#L27-L34
akberc/ceylon-maven-plugin
src/main/java/com/dgwave/car/common/CeylonUtil.java
CeylonUtil.mkdirs
public static void mkdirs(final File outdir, final String path) { """ Creates directories from an existing file to an additional path. @param outdir Existing directory @param path Additional path """ File d = new File(outdir, path); if (!d.exists()) { d.mkdirs(); } }
java
public static void mkdirs(final File outdir, final String path) { File d = new File(outdir, path); if (!d.exists()) { d.mkdirs(); } }
[ "public", "static", "void", "mkdirs", "(", "final", "File", "outdir", ",", "final", "String", "path", ")", "{", "File", "d", "=", "new", "File", "(", "outdir", ",", "path", ")", ";", "if", "(", "!", "d", ".", "exists", "(", ")", ")", "{", "d", ".", "mkdirs", "(", ")", ";", "}", "}" ]
Creates directories from an existing file to an additional path. @param outdir Existing directory @param path Additional path
[ "Creates", "directories", "from", "an", "existing", "file", "to", "an", "additional", "path", "." ]
train
https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/common/CeylonUtil.java#L238-L243
buschmais/jqa-maven3-plugin
src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java
MavenModelScannerPlugin._addProfileDependencies
private void _addProfileDependencies(MavenProfileDescriptor profileDescriptor, List<Dependency> dependencies, ScannerContext scannerContext) { """ Adds information about profile dependencies. @param profileDescriptor The descriptor for the current profile. @param dependencies The dependencies information. @param scannerContext The scanner context. """ for (Dependency dependency : dependencies) { MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor(dependency, scannerContext); Store store = scannerContext.getStore(); ProfileDeclaresDependencyDescriptor profileDependsOnDescriptor = store.create(profileDescriptor, ProfileDeclaresDependencyDescriptor.class, dependencyArtifactDescriptor); profileDependsOnDescriptor.setOptional(dependency.isOptional()); profileDependsOnDescriptor.setScope(dependency.getScope()); } }
java
private void _addProfileDependencies(MavenProfileDescriptor profileDescriptor, List<Dependency> dependencies, ScannerContext scannerContext) { for (Dependency dependency : dependencies) { MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor(dependency, scannerContext); Store store = scannerContext.getStore(); ProfileDeclaresDependencyDescriptor profileDependsOnDescriptor = store.create(profileDescriptor, ProfileDeclaresDependencyDescriptor.class, dependencyArtifactDescriptor); profileDependsOnDescriptor.setOptional(dependency.isOptional()); profileDependsOnDescriptor.setScope(dependency.getScope()); } }
[ "private", "void", "_addProfileDependencies", "(", "MavenProfileDescriptor", "profileDescriptor", ",", "List", "<", "Dependency", ">", "dependencies", ",", "ScannerContext", "scannerContext", ")", "{", "for", "(", "Dependency", "dependency", ":", "dependencies", ")", "{", "MavenArtifactDescriptor", "dependencyArtifactDescriptor", "=", "getMavenArtifactDescriptor", "(", "dependency", ",", "scannerContext", ")", ";", "Store", "store", "=", "scannerContext", ".", "getStore", "(", ")", ";", "ProfileDeclaresDependencyDescriptor", "profileDependsOnDescriptor", "=", "store", ".", "create", "(", "profileDescriptor", ",", "ProfileDeclaresDependencyDescriptor", ".", "class", ",", "dependencyArtifactDescriptor", ")", ";", "profileDependsOnDescriptor", ".", "setOptional", "(", "dependency", ".", "isOptional", "(", ")", ")", ";", "profileDependsOnDescriptor", ".", "setScope", "(", "dependency", ".", "getScope", "(", ")", ")", ";", "}", "}" ]
Adds information about profile dependencies. @param profileDescriptor The descriptor for the current profile. @param dependencies The dependencies information. @param scannerContext The scanner context.
[ "Adds", "information", "about", "profile", "dependencies", "." ]
train
https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L543-L552
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java
JARVerifier.create
public static JARVerifier create(String keystore, String alias, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { """ @return Construct a JARVerifier with a keystore and alias and password. @param keystore filepath to the keystore @param alias alias name of the cert chain to verify with @param passwd password to use to verify the keystore, or null @throws IOException on io error @throws KeyStoreException key store error @throws NoSuchAlgorithmException algorithm missing @throws CertificateException cert error """ KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fileIn=null; try { fileIn = new FileInputStream(keystore); keyStore.load(fileIn, passwd); } finally { if(null!= fileIn){ fileIn.close(); } } Certificate[] chain = keyStore.getCertificateChain(alias); if (chain == null) { Certificate cert = keyStore.getCertificate(alias); if (cert == null) { throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias); } chain = new Certificate[]{cert}; } X509Certificate certChain[] = new X509Certificate[chain.length]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int count = 0; count < chain.length; count++) { ByteArrayInputStream certIn = new ByteArrayInputStream(chain[count].getEncoded()); X509Certificate cert = (X509Certificate) cf.generateCertificate(certIn); certChain[count] = cert; } JARVerifier jarVerifier = new JARVerifier(certChain); return jarVerifier; }
java
public static JARVerifier create(String keystore, String alias, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fileIn=null; try { fileIn = new FileInputStream(keystore); keyStore.load(fileIn, passwd); } finally { if(null!= fileIn){ fileIn.close(); } } Certificate[] chain = keyStore.getCertificateChain(alias); if (chain == null) { Certificate cert = keyStore.getCertificate(alias); if (cert == null) { throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias); } chain = new Certificate[]{cert}; } X509Certificate certChain[] = new X509Certificate[chain.length]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int count = 0; count < chain.length; count++) { ByteArrayInputStream certIn = new ByteArrayInputStream(chain[count].getEncoded()); X509Certificate cert = (X509Certificate) cf.generateCertificate(certIn); certChain[count] = cert; } JARVerifier jarVerifier = new JARVerifier(certChain); return jarVerifier; }
[ "public", "static", "JARVerifier", "create", "(", "String", "keystore", ",", "String", "alias", ",", "char", "[", "]", "passwd", ")", "throws", "IOException", ",", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", "{", "KeyStore", "keyStore", "=", "KeyStore", ".", "getInstance", "(", "\"JKS\"", ")", ";", "FileInputStream", "fileIn", "=", "null", ";", "try", "{", "fileIn", "=", "new", "FileInputStream", "(", "keystore", ")", ";", "keyStore", ".", "load", "(", "fileIn", ",", "passwd", ")", ";", "}", "finally", "{", "if", "(", "null", "!=", "fileIn", ")", "{", "fileIn", ".", "close", "(", ")", ";", "}", "}", "Certificate", "[", "]", "chain", "=", "keyStore", ".", "getCertificateChain", "(", "alias", ")", ";", "if", "(", "chain", "==", "null", ")", "{", "Certificate", "cert", "=", "keyStore", ".", "getCertificate", "(", "alias", ")", ";", "if", "(", "cert", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No trusted certificate or chain found for alias: \"", "+", "alias", ")", ";", "}", "chain", "=", "new", "Certificate", "[", "]", "{", "cert", "}", ";", "}", "X509Certificate", "certChain", "[", "]", "=", "new", "X509Certificate", "[", "chain", ".", "length", "]", ";", "CertificateFactory", "cf", "=", "CertificateFactory", ".", "getInstance", "(", "\"X.509\"", ")", ";", "for", "(", "int", "count", "=", "0", ";", "count", "<", "chain", ".", "length", ";", "count", "++", ")", "{", "ByteArrayInputStream", "certIn", "=", "new", "ByteArrayInputStream", "(", "chain", "[", "count", "]", ".", "getEncoded", "(", ")", ")", ";", "X509Certificate", "cert", "=", "(", "X509Certificate", ")", "cf", ".", "generateCertificate", "(", "certIn", ")", ";", "certChain", "[", "count", "]", "=", "cert", ";", "}", "JARVerifier", "jarVerifier", "=", "new", "JARVerifier", "(", "certChain", ")", ";", "return", "jarVerifier", ";", "}" ]
@return Construct a JARVerifier with a keystore and alias and password. @param keystore filepath to the keystore @param alias alias name of the cert chain to verify with @param passwd password to use to verify the keystore, or null @throws IOException on io error @throws KeyStoreException key store error @throws NoSuchAlgorithmException algorithm missing @throws CertificateException cert error
[ "@return", "Construct", "a", "JARVerifier", "with", "a", "keystore", "and", "alias", "and", "password", "." ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java#L76-L110
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Normalizer.java
Normalizer.quickCheck
@Deprecated public static QuickCheckResult quickCheck(String source, Mode mode) { """ Convenience method. @param source string for determining if it is in a normalized format @param mode normalization format (Normalizer.NFC,Normalizer.NFD, Normalizer.NFKC,Normalizer.NFKD) @return Return code to specify if the text is normalized or not (Normalizer.YES, Normalizer.NO or Normalizer.MAYBE) @deprecated ICU 56 Use {@link Normalizer2} instead. @hide original deprecated declaration """ return quickCheck(source, mode, 0); }
java
@Deprecated public static QuickCheckResult quickCheck(String source, Mode mode) { return quickCheck(source, mode, 0); }
[ "@", "Deprecated", "public", "static", "QuickCheckResult", "quickCheck", "(", "String", "source", ",", "Mode", "mode", ")", "{", "return", "quickCheck", "(", "source", ",", "mode", ",", "0", ")", ";", "}" ]
Convenience method. @param source string for determining if it is in a normalized format @param mode normalization format (Normalizer.NFC,Normalizer.NFD, Normalizer.NFKC,Normalizer.NFKD) @return Return code to specify if the text is normalized or not (Normalizer.YES, Normalizer.NO or Normalizer.MAYBE) @deprecated ICU 56 Use {@link Normalizer2} instead. @hide original deprecated declaration
[ "Convenience", "method", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Normalizer.java#L982-L985
neokree/MaterialNavigationDrawer
MaterialNavigationDrawerModule/src/main/java/it/neokree/materialnavigationdrawer/MaterialNavigationDrawer.java
MaterialNavigationDrawer.setFragment
public void setFragment(Fragment fragment,String title) { """ Set the fragment to the activity content.<br /> N.B. If you want to support the master/child flow, please consider to use setFragmentChild instead @param fragment to replace into the main content @param title to set into Toolbar """ setFragment(fragment,title,null); if(!isCurrentFragmentChild) {// remove the last child from the stack childFragmentStack.remove(childFragmentStack.size() - 1); childTitleStack.remove(childTitleStack.size() - 1); } else for(int i = childFragmentStack.size()-1; i >= 0;i--) { // if a section is clicked when user is into a child remove all childs from stack childFragmentStack.remove(i); childTitleStack.remove(i); } // add to the childStack the Fragment and title childFragmentStack.add(fragment); childTitleStack.add(title); isCurrentFragmentChild = false; }
java
public void setFragment(Fragment fragment,String title) { setFragment(fragment,title,null); if(!isCurrentFragmentChild) {// remove the last child from the stack childFragmentStack.remove(childFragmentStack.size() - 1); childTitleStack.remove(childTitleStack.size() - 1); } else for(int i = childFragmentStack.size()-1; i >= 0;i--) { // if a section is clicked when user is into a child remove all childs from stack childFragmentStack.remove(i); childTitleStack.remove(i); } // add to the childStack the Fragment and title childFragmentStack.add(fragment); childTitleStack.add(title); isCurrentFragmentChild = false; }
[ "public", "void", "setFragment", "(", "Fragment", "fragment", ",", "String", "title", ")", "{", "setFragment", "(", "fragment", ",", "title", ",", "null", ")", ";", "if", "(", "!", "isCurrentFragmentChild", ")", "{", "// remove the last child from the stack", "childFragmentStack", ".", "remove", "(", "childFragmentStack", ".", "size", "(", ")", "-", "1", ")", ";", "childTitleStack", ".", "remove", "(", "childTitleStack", ".", "size", "(", ")", "-", "1", ")", ";", "}", "else", "for", "(", "int", "i", "=", "childFragmentStack", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "// if a section is clicked when user is into a child remove all childs from stack", "childFragmentStack", ".", "remove", "(", "i", ")", ";", "childTitleStack", ".", "remove", "(", "i", ")", ";", "}", "// add to the childStack the Fragment and title", "childFragmentStack", ".", "add", "(", "fragment", ")", ";", "childTitleStack", ".", "add", "(", "title", ")", ";", "isCurrentFragmentChild", "=", "false", ";", "}" ]
Set the fragment to the activity content.<br /> N.B. If you want to support the master/child flow, please consider to use setFragmentChild instead @param fragment to replace into the main content @param title to set into Toolbar
[ "Set", "the", "fragment", "to", "the", "activity", "content", ".", "<br", "/", ">", "N", ".", "B", ".", "If", "you", "want", "to", "support", "the", "master", "/", "child", "flow", "please", "consider", "to", "use", "setFragmentChild", "instead" ]
train
https://github.com/neokree/MaterialNavigationDrawer/blob/86e355f6190dcb7255c6b9c28c1e54cf96f46358/MaterialNavigationDrawerModule/src/main/java/it/neokree/materialnavigationdrawer/MaterialNavigationDrawer.java#L1026-L1043
apache/flink
flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/network/messages/MessageSerializer.java
MessageSerializer.deserializeRequestFailure
public static RequestFailure deserializeRequestFailure(final ByteBuf buf) throws IOException, ClassNotFoundException { """ De-serializes the {@link RequestFailure} sent to the {@link org.apache.flink.queryablestate.network.Client} in case of protocol related errors. <pre> <b>The buffer is expected to be at the correct position.</b> </pre> @param buf The {@link ByteBuf} containing the serialized failure message. @return The failure message. """ long requestId = buf.readLong(); Throwable cause; try (ByteBufInputStream bis = new ByteBufInputStream(buf); ObjectInputStream in = new ObjectInputStream(bis)) { cause = (Throwable) in.readObject(); } return new RequestFailure(requestId, cause); }
java
public static RequestFailure deserializeRequestFailure(final ByteBuf buf) throws IOException, ClassNotFoundException { long requestId = buf.readLong(); Throwable cause; try (ByteBufInputStream bis = new ByteBufInputStream(buf); ObjectInputStream in = new ObjectInputStream(bis)) { cause = (Throwable) in.readObject(); } return new RequestFailure(requestId, cause); }
[ "public", "static", "RequestFailure", "deserializeRequestFailure", "(", "final", "ByteBuf", "buf", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "long", "requestId", "=", "buf", ".", "readLong", "(", ")", ";", "Throwable", "cause", ";", "try", "(", "ByteBufInputStream", "bis", "=", "new", "ByteBufInputStream", "(", "buf", ")", ";", "ObjectInputStream", "in", "=", "new", "ObjectInputStream", "(", "bis", ")", ")", "{", "cause", "=", "(", "Throwable", ")", "in", ".", "readObject", "(", ")", ";", "}", "return", "new", "RequestFailure", "(", "requestId", ",", "cause", ")", ";", "}" ]
De-serializes the {@link RequestFailure} sent to the {@link org.apache.flink.queryablestate.network.Client} in case of protocol related errors. <pre> <b>The buffer is expected to be at the correct position.</b> </pre> @param buf The {@link ByteBuf} containing the serialized failure message. @return The failure message.
[ "De", "-", "serializes", "the", "{" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/network/messages/MessageSerializer.java#L293-L302
EdwardRaff/JSAT
JSAT/src/jsat/utils/concurrent/AtomicDoubleArray.java
AtomicDoubleArray.getAndSet
public double getAndSet(int i, double newValue) { """ Atomically sets the element at position {@code i} to the given value and returns the old value. @param i the index @param newValue the new value @return the previous value """ long oldL = larray.getAndSet(i, Double.doubleToRawLongBits(newValue)); return Double.longBitsToDouble(oldL); }
java
public double getAndSet(int i, double newValue) { long oldL = larray.getAndSet(i, Double.doubleToRawLongBits(newValue)); return Double.longBitsToDouble(oldL); }
[ "public", "double", "getAndSet", "(", "int", "i", ",", "double", "newValue", ")", "{", "long", "oldL", "=", "larray", ".", "getAndSet", "(", "i", ",", "Double", ".", "doubleToRawLongBits", "(", "newValue", ")", ")", ";", "return", "Double", ".", "longBitsToDouble", "(", "oldL", ")", ";", "}" ]
Atomically sets the element at position {@code i} to the given value and returns the old value. @param i the index @param newValue the new value @return the previous value
[ "Atomically", "sets", "the", "element", "at", "position", "{", "@code", "i", "}", "to", "the", "given", "value", "and", "returns", "the", "old", "value", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/concurrent/AtomicDoubleArray.java#L113-L117
googleapis/google-cloud-java
google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java
KeyManagementServiceClient.updateCryptoKey
public final CryptoKey updateCryptoKey(CryptoKey cryptoKey, FieldMask updateMask) { """ Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. <p>Sample code: <pre><code> try (KeyManagementServiceClient keyManagementServiceClient = KeyManagementServiceClient.create()) { CryptoKey cryptoKey = CryptoKey.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); CryptoKey response = keyManagementServiceClient.updateCryptoKey(cryptoKey, updateMask); } </code></pre> @param cryptoKey [CryptoKey][google.cloud.kms.v1.CryptoKey] with updated values. @param updateMask Required list of fields to be updated in this request. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ UpdateCryptoKeyRequest request = UpdateCryptoKeyRequest.newBuilder() .setCryptoKey(cryptoKey) .setUpdateMask(updateMask) .build(); return updateCryptoKey(request); }
java
public final CryptoKey updateCryptoKey(CryptoKey cryptoKey, FieldMask updateMask) { UpdateCryptoKeyRequest request = UpdateCryptoKeyRequest.newBuilder() .setCryptoKey(cryptoKey) .setUpdateMask(updateMask) .build(); return updateCryptoKey(request); }
[ "public", "final", "CryptoKey", "updateCryptoKey", "(", "CryptoKey", "cryptoKey", ",", "FieldMask", "updateMask", ")", "{", "UpdateCryptoKeyRequest", "request", "=", "UpdateCryptoKeyRequest", ".", "newBuilder", "(", ")", ".", "setCryptoKey", "(", "cryptoKey", ")", ".", "setUpdateMask", "(", "updateMask", ")", ".", "build", "(", ")", ";", "return", "updateCryptoKey", "(", "request", ")", ";", "}" ]
Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. <p>Sample code: <pre><code> try (KeyManagementServiceClient keyManagementServiceClient = KeyManagementServiceClient.create()) { CryptoKey cryptoKey = CryptoKey.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); CryptoKey response = keyManagementServiceClient.updateCryptoKey(cryptoKey, updateMask); } </code></pre> @param cryptoKey [CryptoKey][google.cloud.kms.v1.CryptoKey] with updated values. @param updateMask Required list of fields to be updated in this request. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Update", "a", "[", "CryptoKey", "]", "[", "google", ".", "cloud", ".", "kms", ".", "v1", ".", "CryptoKey", "]", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java#L1324-L1332
santhosh-tekuri/jlibs
core/src/main/java/jlibs/core/lang/Ansi.java
Ansi.println
public void println(PrintStream ps, String message) { """ Prints colorized {@code message} to specified {@code ps} followed by newline. <p> if {@link #SUPPORTED} is false, it prints raw {@code message} to {@code ps} followed by newline. @param ps stream to print @param message message to be colorized """ print(ps, message); ps.println(); }
java
public void println(PrintStream ps, String message){ print(ps, message); ps.println(); }
[ "public", "void", "println", "(", "PrintStream", "ps", ",", "String", "message", ")", "{", "print", "(", "ps", ",", "message", ")", ";", "ps", ".", "println", "(", ")", ";", "}" ]
Prints colorized {@code message} to specified {@code ps} followed by newline. <p> if {@link #SUPPORTED} is false, it prints raw {@code message} to {@code ps} followed by newline. @param ps stream to print @param message message to be colorized
[ "Prints", "colorized", "{", "@code", "message", "}", "to", "specified", "{", "@code", "ps", "}", "followed", "by", "newline", ".", "<p", ">", "if", "{", "@link", "#SUPPORTED", "}", "is", "false", "it", "prints", "raw", "{", "@code", "message", "}", "to", "{", "@code", "ps", "}", "followed", "by", "newline", "." ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/lang/Ansi.java#L258-L261
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java
ClassUtil.findEnumConstant
public static Object findEnumConstant(Class<?> type, String constantName) { """ Finds an instance of an Enum constant on a class. Useful for safely getting the value of an enum constant without an exception being thrown like the Enum.valueOf() method causes. Searches for enum constant where case is sensitive. """ return findEnumConstant(type, constantName, true); }
java
public static Object findEnumConstant(Class<?> type, String constantName) { return findEnumConstant(type, constantName, true); }
[ "public", "static", "Object", "findEnumConstant", "(", "Class", "<", "?", ">", "type", ",", "String", "constantName", ")", "{", "return", "findEnumConstant", "(", "type", ",", "constantName", ",", "true", ")", ";", "}" ]
Finds an instance of an Enum constant on a class. Useful for safely getting the value of an enum constant without an exception being thrown like the Enum.valueOf() method causes. Searches for enum constant where case is sensitive.
[ "Finds", "an", "instance", "of", "an", "Enum", "constant", "on", "a", "class", ".", "Useful", "for", "safely", "getting", "the", "value", "of", "an", "enum", "constant", "without", "an", "exception", "being", "thrown", "like", "the", "Enum", ".", "valueOf", "()", "method", "causes", ".", "Searches", "for", "enum", "constant", "where", "case", "is", "sensitive", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java#L41-L43
stripe/stripe-android
example/src/main/java/com/stripe/example/adapter/RedirectAdapter.java
RedirectAdapter.onBindViewHolder
@Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { """ Replace the contents of a view (invoked by the layout manager) """ // - get element from your dataset at this position // - replace the contents of the view with that element final ViewModel model = mDataset.get(position); holder.setFinalStatus(model.mFinalStatus); holder.setRedirectStatus(model.mRedirectStatus); holder.setSourceId(model.mSourceId); holder.setSourceType(model.mSourceType); }
java
@Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element final ViewModel model = mDataset.get(position); holder.setFinalStatus(model.mFinalStatus); holder.setRedirectStatus(model.mRedirectStatus); holder.setSourceId(model.mSourceId); holder.setSourceType(model.mSourceType); }
[ "@", "Override", "public", "void", "onBindViewHolder", "(", "@", "NonNull", "ViewHolder", "holder", ",", "int", "position", ")", "{", "// - get element from your dataset at this position", "// - replace the contents of the view with that element", "final", "ViewModel", "model", "=", "mDataset", ".", "get", "(", "position", ")", ";", "holder", ".", "setFinalStatus", "(", "model", ".", "mFinalStatus", ")", ";", "holder", ".", "setRedirectStatus", "(", "model", ".", "mRedirectStatus", ")", ";", "holder", ".", "setSourceId", "(", "model", ".", "mSourceId", ")", ";", "holder", ".", "setSourceType", "(", "model", ".", "mSourceType", ")", ";", "}" ]
Replace the contents of a view (invoked by the layout manager)
[ "Replace", "the", "contents", "of", "a", "view", "(", "invoked", "by", "the", "layout", "manager", ")" ]
train
https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/example/src/main/java/com/stripe/example/adapter/RedirectAdapter.java#L97-L106
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.escapeUriFragmentId
public static void escapeUriFragmentId(final char[] text, final int offset, final int len, final Writer writer) throws IOException { """ <p> Perform am URI fragment identifier <strong>escape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> The following are the only allowed chars in an URI fragment identifier (will not be escaped): </p> <ul> <li><tt>A-Z a-z 0-9</tt></li> <li><tt>- . _ ~</tt></li> <li><tt>! $ &amp; ' ( ) * + , ; =</tt></li> <li><tt>: @</tt></li> <li><tt>/ ?</tt></li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the <tt>UTF-8</tt> and then representing each byte in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs """ escapeUriFragmentId(text, offset, len, writer, DEFAULT_ENCODING); }
java
public static void escapeUriFragmentId(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeUriFragmentId(text, offset, len, writer, DEFAULT_ENCODING); }
[ "public", "static", "void", "escapeUriFragmentId", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeUriFragmentId", "(", "text", ",", "offset", ",", "len", ",", "writer", ",", "DEFAULT_ENCODING", ")", ";", "}" ]
<p> Perform am URI fragment identifier <strong>escape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> The following are the only allowed chars in an URI fragment identifier (will not be escaped): </p> <ul> <li><tt>A-Z a-z 0-9</tt></li> <li><tt>- . _ ~</tt></li> <li><tt>! $ &amp; ' ( ) * + , ; =</tt></li> <li><tt>: @</tt></li> <li><tt>/ ?</tt></li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the <tt>UTF-8</tt> and then representing each byte in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "am", "URI", "fragment", "identifier", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", "using", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "as", "encoding", ".", "<", "/", "p", ">", "<p", ">", "The", "following", "are", "the", "only", "allowed", "chars", "in", "an", "URI", "fragment", "identifier", "(", "will", "not", "be", "escaped", ")", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<tt", ">", "A", "-", "Z", "a", "-", "z", "0", "-", "9<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "-", ".", "_", "~<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "!", "$", "&amp", ";", "(", ")", "*", "+", ";", "=", "<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", ":", "@<", "/", "tt", ">", "<", "/", "li", ">", "<li", ">", "<tt", ">", "/", "?<", "/", "tt", ">", "<", "/", "li", ">", "<", "/", "ul", ">", "<p", ">", "All", "other", "chars", "will", "be", "escaped", "by", "converting", "them", "to", "the", "sequence", "of", "bytes", "that", "represents", "them", "in", "the", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "and", "then", "representing", "each", "byte", "in", "<tt", ">", "%HH<", "/", "tt", ">", "syntax", "being", "<tt", ">", "HH<", "/", "tt", ">", "the", "hexadecimal", "representation", "of", "the", "byte", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1434-L1437
netplex/json-smart-v2
json-smart/src/main/java/net/minidev/json/parser/JSONParser.java
JSONParser.parse
public <T> T parse(String in, JsonReaderI<T> mapper) throws ParseException { """ use to return Primitive Type, or String, Or JsonObject or JsonArray generated by a ContainerFactory """ return getPString().parse(in, mapper); }
java
public <T> T parse(String in, JsonReaderI<T> mapper) throws ParseException { return getPString().parse(in, mapper); }
[ "public", "<", "T", ">", "T", "parse", "(", "String", "in", ",", "JsonReaderI", "<", "T", ">", "mapper", ")", "throws", "ParseException", "{", "return", "getPString", "(", ")", ".", "parse", "(", "in", ",", "mapper", ")", ";", "}" ]
use to return Primitive Type, or String, Or JsonObject or JsonArray generated by a ContainerFactory
[ "use", "to", "return", "Primitive", "Type", "or", "String", "Or", "JsonObject", "or", "JsonArray", "generated", "by", "a", "ContainerFactory" ]
train
https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java#L270-L272
rhuss/jolokia
agent/jvm/src/main/java/org/jolokia/jvmagent/client/util/OptionsAndArgs.java
OptionsAndArgs.getNextListIndexSuffix
private String getNextListIndexSuffix(Map<String, String> options, String key) { """ check for the next key with a suffix like ".1" which is not already set """ if (!options.containsKey(key)) { return ""; } else { int i = 1; while (options.containsKey(key + "." + i)) { i++; } return "." + i; } }
java
private String getNextListIndexSuffix(Map<String, String> options, String key) { if (!options.containsKey(key)) { return ""; } else { int i = 1; while (options.containsKey(key + "." + i)) { i++; } return "." + i; } }
[ "private", "String", "getNextListIndexSuffix", "(", "Map", "<", "String", ",", "String", ">", "options", ",", "String", "key", ")", "{", "if", "(", "!", "options", ".", "containsKey", "(", "key", ")", ")", "{", "return", "\"\"", ";", "}", "else", "{", "int", "i", "=", "1", ";", "while", "(", "options", ".", "containsKey", "(", "key", "+", "\".\"", "+", "i", ")", ")", "{", "i", "++", ";", "}", "return", "\".\"", "+", "i", ";", "}", "}" ]
check for the next key with a suffix like ".1" which is not already set
[ "check", "for", "the", "next", "key", "with", "a", "suffix", "like", ".", "1", "which", "is", "not", "already", "set" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/client/util/OptionsAndArgs.java#L314-L324
seedstack/i18n-addon
rest/src/main/java/org/seedstack/i18n/rest/internal/key/KeysResource.java
KeysResource.getKeys
@GET @Produces(MediaType.APPLICATION_JSON) @RequiresPermissions(I18nPermissions.KEY_READ) public Response getKeys(@QueryParam(PAGE_INDEX) @DefaultValue("0") long pageIndex, @QueryParam(PAGE_SIZE) @DefaultValue("10") int pageSize, @QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox, @QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) { """ Returns a list of filtered keys without their translations. @param pageIndex page index @param pageSize page size @param isMissing filter on missing default translation @param isApprox filter on approximate default translation @param isOutdated filter on outdated key @param searchName filter on key name @return 200 - keys without translations """ WebAssertions.assertIf(pageSize > 0, "Page size should be greater than zero."); KeySearchCriteria keySearchCriteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName); Page page = new Page(pageIndex, pageSize); return Response.ok(keyFinder.findKeysWithTheirDefaultTranslation(page, keySearchCriteria)).build(); }
java
@GET @Produces(MediaType.APPLICATION_JSON) @RequiresPermissions(I18nPermissions.KEY_READ) public Response getKeys(@QueryParam(PAGE_INDEX) @DefaultValue("0") long pageIndex, @QueryParam(PAGE_SIZE) @DefaultValue("10") int pageSize, @QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox, @QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) { WebAssertions.assertIf(pageSize > 0, "Page size should be greater than zero."); KeySearchCriteria keySearchCriteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName); Page page = new Page(pageIndex, pageSize); return Response.ok(keyFinder.findKeysWithTheirDefaultTranslation(page, keySearchCriteria)).build(); }
[ "@", "GET", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "RequiresPermissions", "(", "I18nPermissions", ".", "KEY_READ", ")", "public", "Response", "getKeys", "(", "@", "QueryParam", "(", "PAGE_INDEX", ")", "@", "DefaultValue", "(", "\"0\"", ")", "long", "pageIndex", ",", "@", "QueryParam", "(", "PAGE_SIZE", ")", "@", "DefaultValue", "(", "\"10\"", ")", "int", "pageSize", ",", "@", "QueryParam", "(", "IS_MISSING", ")", "Boolean", "isMissing", ",", "@", "QueryParam", "(", "IS_APPROX", ")", "Boolean", "isApprox", ",", "@", "QueryParam", "(", "IS_OUTDATED", ")", "Boolean", "isOutdated", ",", "@", "QueryParam", "(", "SEARCH_NAME", ")", "String", "searchName", ")", "{", "WebAssertions", ".", "assertIf", "(", "pageSize", ">", "0", ",", "\"Page size should be greater than zero.\"", ")", ";", "KeySearchCriteria", "keySearchCriteria", "=", "new", "KeySearchCriteria", "(", "isMissing", ",", "isApprox", ",", "isOutdated", ",", "searchName", ")", ";", "Page", "page", "=", "new", "Page", "(", "pageIndex", ",", "pageSize", ")", ";", "return", "Response", ".", "ok", "(", "keyFinder", ".", "findKeysWithTheirDefaultTranslation", "(", "page", ",", "keySearchCriteria", ")", ")", ".", "build", "(", ")", ";", "}" ]
Returns a list of filtered keys without their translations. @param pageIndex page index @param pageSize page size @param isMissing filter on missing default translation @param isApprox filter on approximate default translation @param isOutdated filter on outdated key @param searchName filter on key name @return 200 - keys without translations
[ "Returns", "a", "list", "of", "filtered", "keys", "without", "their", "translations", "." ]
train
https://github.com/seedstack/i18n-addon/blob/1e65101d8554623f09bda2497b0151fd10a16615/rest/src/main/java/org/seedstack/i18n/rest/internal/key/KeysResource.java#L86-L99
j256/ormlite-core
src/main/java/com/j256/ormlite/dao/DaoManager.java
DaoManager.lookupDao
public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) { """ Helper method to lookup a DAO if it has already been associated with the table-config. Otherwise this returns null. """ if (connectionSource == null) { throw new IllegalArgumentException("connectionSource argument cannot be null"); } TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig); Dao<?, ?> dao = lookupDao(key); if (dao == null) { return null; } else { @SuppressWarnings("unchecked") D castDao = (D) dao; return castDao; } }
java
public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) { if (connectionSource == null) { throw new IllegalArgumentException("connectionSource argument cannot be null"); } TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig); Dao<?, ?> dao = lookupDao(key); if (dao == null) { return null; } else { @SuppressWarnings("unchecked") D castDao = (D) dao; return castDao; } }
[ "public", "synchronized", "static", "<", "D", "extends", "Dao", "<", "T", ",", "?", ">", ",", "T", ">", "D", "lookupDao", "(", "ConnectionSource", "connectionSource", ",", "DatabaseTableConfig", "<", "T", ">", "tableConfig", ")", "{", "if", "(", "connectionSource", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"connectionSource argument cannot be null\"", ")", ";", "}", "TableConfigConnectionSource", "key", "=", "new", "TableConfigConnectionSource", "(", "connectionSource", ",", "tableConfig", ")", ";", "Dao", "<", "?", ",", "?", ">", "dao", "=", "lookupDao", "(", "key", ")", ";", "if", "(", "dao", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "D", "castDao", "=", "(", "D", ")", "dao", ";", "return", "castDao", ";", "}", "}" ]
Helper method to lookup a DAO if it has already been associated with the table-config. Otherwise this returns null.
[ "Helper", "method", "to", "lookup", "a", "DAO", "if", "it", "has", "already", "been", "associated", "with", "the", "table", "-", "config", ".", "Otherwise", "this", "returns", "null", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/dao/DaoManager.java#L137-L151
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java
ComputeNodesImpl.addUser
public void addUser(String poolId, String nodeId, ComputeNodeUser user) { """ Adds a user account to the specified compute node. You can add a user account to a node only when it is in the idle or running state. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the machine on which you want to create a user account. @param user The user account to be created. @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ addUserWithServiceResponseAsync(poolId, nodeId, user).toBlocking().single().body(); }
java
public void addUser(String poolId, String nodeId, ComputeNodeUser user) { addUserWithServiceResponseAsync(poolId, nodeId, user).toBlocking().single().body(); }
[ "public", "void", "addUser", "(", "String", "poolId", ",", "String", "nodeId", ",", "ComputeNodeUser", "user", ")", "{", "addUserWithServiceResponseAsync", "(", "poolId", ",", "nodeId", ",", "user", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Adds a user account to the specified compute node. You can add a user account to a node only when it is in the idle or running state. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the machine on which you want to create a user account. @param user The user account to be created. @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Adds", "a", "user", "account", "to", "the", "specified", "compute", "node", ".", "You", "can", "add", "a", "user", "account", "to", "a", "node", "only", "when", "it", "is", "in", "the", "idle", "or", "running", "state", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java#L178-L180
alkacon/opencms-core
src/org/opencms/xml/containerpage/CmsDynamicFunctionParser.java
CmsDynamicFunctionParser.getStringValue
protected String getStringValue(CmsObject cms, I_CmsXmlContentValueLocation location, String defaultValue) { """ Converts a (possibly null) content value location to a string.<p> @param cms the current CMS context @param location the content value location @param defaultValue the value to return if the location is null @return the string value of the content value location """ if (location == null) { return defaultValue; } return location.asString(cms); }
java
protected String getStringValue(CmsObject cms, I_CmsXmlContentValueLocation location, String defaultValue) { if (location == null) { return defaultValue; } return location.asString(cms); }
[ "protected", "String", "getStringValue", "(", "CmsObject", "cms", ",", "I_CmsXmlContentValueLocation", "location", ",", "String", "defaultValue", ")", "{", "if", "(", "location", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "return", "location", ".", "asString", "(", "cms", ")", ";", "}" ]
Converts a (possibly null) content value location to a string.<p> @param cms the current CMS context @param location the content value location @param defaultValue the value to return if the location is null @return the string value of the content value location
[ "Converts", "a", "(", "possibly", "null", ")", "content", "value", "location", "to", "a", "string", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsDynamicFunctionParser.java#L227-L233
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/JobClient.java
JobClient.listEvents
private void listEvents(JobID jobId, int fromEventId, int numEvents) throws IOException { """ List the events for the given job @param jobId the job id for the job's events to list @throws IOException """ TaskCompletionEvent[] events = jobSubmitClient.getTaskCompletionEvents(jobId, fromEventId, numEvents); System.out.println("Task completion events for " + jobId); System.out.println("Number of events (from " + fromEventId + ") are: " + events.length); for(TaskCompletionEvent event: events) { System.out.println(event.getTaskStatus() + " " + event.getTaskAttemptId() + " " + getTaskLogURL(event.getTaskAttemptId(), event.getTaskTrackerHttp())); } }
java
private void listEvents(JobID jobId, int fromEventId, int numEvents) throws IOException { TaskCompletionEvent[] events = jobSubmitClient.getTaskCompletionEvents(jobId, fromEventId, numEvents); System.out.println("Task completion events for " + jobId); System.out.println("Number of events (from " + fromEventId + ") are: " + events.length); for(TaskCompletionEvent event: events) { System.out.println(event.getTaskStatus() + " " + event.getTaskAttemptId() + " " + getTaskLogURL(event.getTaskAttemptId(), event.getTaskTrackerHttp())); } }
[ "private", "void", "listEvents", "(", "JobID", "jobId", ",", "int", "fromEventId", ",", "int", "numEvents", ")", "throws", "IOException", "{", "TaskCompletionEvent", "[", "]", "events", "=", "jobSubmitClient", ".", "getTaskCompletionEvents", "(", "jobId", ",", "fromEventId", ",", "numEvents", ")", ";", "System", ".", "out", ".", "println", "(", "\"Task completion events for \"", "+", "jobId", ")", ";", "System", ".", "out", ".", "println", "(", "\"Number of events (from \"", "+", "fromEventId", "+", "\") are: \"", "+", "events", ".", "length", ")", ";", "for", "(", "TaskCompletionEvent", "event", ":", "events", ")", "{", "System", ".", "out", ".", "println", "(", "event", ".", "getTaskStatus", "(", ")", "+", "\" \"", "+", "event", ".", "getTaskAttemptId", "(", ")", "+", "\" \"", "+", "getTaskLogURL", "(", "event", ".", "getTaskAttemptId", "(", ")", ",", "event", ".", "getTaskTrackerHttp", "(", ")", ")", ")", ";", "}", "}" ]
List the events for the given job @param jobId the job id for the job's events to list @throws IOException
[ "List", "the", "events", "for", "the", "given", "job" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/JobClient.java#L2335-L2347
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.createExternalStorageTileCache
public static TileCache createExternalStorageTileCache(File cacheDir, String id, int firstLevelSize, int tileSize, boolean persistent) { """ Utility function to create a two-level tile cache along with its backends. @param cacheDir the cache directory @param id name for the directory, which will be created as a subdirectory of the cache directory @param firstLevelSize size of the first level cache (tiles number) @param tileSize tile size @param persistent whether the second level tile cache should be persistent @return a new cache created on the external storage """ LOGGER.info("TILECACHE INMEMORY SIZE: " + Integer.toString(firstLevelSize)); TileCache firstLevelTileCache = new InMemoryTileCache(firstLevelSize); if (cacheDir != null) { String cacheDirectoryName = cacheDir.getAbsolutePath() + File.separator + id; File cacheDirectory = new File(cacheDirectoryName); if (cacheDirectory.exists() || cacheDirectory.mkdirs()) { int tileCacheFiles = estimateSizeOfFileSystemCache(cacheDirectoryName, firstLevelSize, tileSize); if (cacheDirectory.canWrite() && tileCacheFiles > 0) { try { LOGGER.info("TILECACHE FILE SIZE: " + Integer.toString(tileCacheFiles)); TileCache secondLevelTileCache = new FileSystemTileCache(tileCacheFiles, cacheDirectory, org.mapsforge.map.android.graphics.AndroidGraphicFactory.INSTANCE, persistent); return new TwoLevelTileCache(firstLevelTileCache, secondLevelTileCache); } catch (IllegalArgumentException e) { LOGGER.warning(e.getMessage()); } } } } return firstLevelTileCache; }
java
public static TileCache createExternalStorageTileCache(File cacheDir, String id, int firstLevelSize, int tileSize, boolean persistent) { LOGGER.info("TILECACHE INMEMORY SIZE: " + Integer.toString(firstLevelSize)); TileCache firstLevelTileCache = new InMemoryTileCache(firstLevelSize); if (cacheDir != null) { String cacheDirectoryName = cacheDir.getAbsolutePath() + File.separator + id; File cacheDirectory = new File(cacheDirectoryName); if (cacheDirectory.exists() || cacheDirectory.mkdirs()) { int tileCacheFiles = estimateSizeOfFileSystemCache(cacheDirectoryName, firstLevelSize, tileSize); if (cacheDirectory.canWrite() && tileCacheFiles > 0) { try { LOGGER.info("TILECACHE FILE SIZE: " + Integer.toString(tileCacheFiles)); TileCache secondLevelTileCache = new FileSystemTileCache(tileCacheFiles, cacheDirectory, org.mapsforge.map.android.graphics.AndroidGraphicFactory.INSTANCE, persistent); return new TwoLevelTileCache(firstLevelTileCache, secondLevelTileCache); } catch (IllegalArgumentException e) { LOGGER.warning(e.getMessage()); } } } } return firstLevelTileCache; }
[ "public", "static", "TileCache", "createExternalStorageTileCache", "(", "File", "cacheDir", ",", "String", "id", ",", "int", "firstLevelSize", ",", "int", "tileSize", ",", "boolean", "persistent", ")", "{", "LOGGER", ".", "info", "(", "\"TILECACHE INMEMORY SIZE: \"", "+", "Integer", ".", "toString", "(", "firstLevelSize", ")", ")", ";", "TileCache", "firstLevelTileCache", "=", "new", "InMemoryTileCache", "(", "firstLevelSize", ")", ";", "if", "(", "cacheDir", "!=", "null", ")", "{", "String", "cacheDirectoryName", "=", "cacheDir", ".", "getAbsolutePath", "(", ")", "+", "File", ".", "separator", "+", "id", ";", "File", "cacheDirectory", "=", "new", "File", "(", "cacheDirectoryName", ")", ";", "if", "(", "cacheDirectory", ".", "exists", "(", ")", "||", "cacheDirectory", ".", "mkdirs", "(", ")", ")", "{", "int", "tileCacheFiles", "=", "estimateSizeOfFileSystemCache", "(", "cacheDirectoryName", ",", "firstLevelSize", ",", "tileSize", ")", ";", "if", "(", "cacheDirectory", ".", "canWrite", "(", ")", "&&", "tileCacheFiles", ">", "0", ")", "{", "try", "{", "LOGGER", ".", "info", "(", "\"TILECACHE FILE SIZE: \"", "+", "Integer", ".", "toString", "(", "tileCacheFiles", ")", ")", ";", "TileCache", "secondLevelTileCache", "=", "new", "FileSystemTileCache", "(", "tileCacheFiles", ",", "cacheDirectory", ",", "org", ".", "mapsforge", ".", "map", ".", "android", ".", "graphics", ".", "AndroidGraphicFactory", ".", "INSTANCE", ",", "persistent", ")", ";", "return", "new", "TwoLevelTileCache", "(", "firstLevelTileCache", ",", "secondLevelTileCache", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "LOGGER", ".", "warning", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}", "}", "return", "firstLevelTileCache", ";", "}" ]
Utility function to create a two-level tile cache along with its backends. @param cacheDir the cache directory @param id name for the directory, which will be created as a subdirectory of the cache directory @param firstLevelSize size of the first level cache (tiles number) @param tileSize tile size @param persistent whether the second level tile cache should be persistent @return a new cache created on the external storage
[ "Utility", "function", "to", "create", "a", "two", "-", "level", "tile", "cache", "along", "with", "its", "backends", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L96-L119
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoader.java
DataLoader.newMappedDataLoader
public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoaderWithContext<K, V> batchLoadFunction) { """ Creates new DataLoader with the specified mapped batch loader function and default options (batching, caching and unlimited batch size). @param batchLoadFunction the batch load function to use @param <K> the key type @param <V> the value type @return a new DataLoader """ return newMappedDataLoader(batchLoadFunction, null); }
java
public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoaderWithContext<K, V> batchLoadFunction) { return newMappedDataLoader(batchLoadFunction, null); }
[ "public", "static", "<", "K", ",", "V", ">", "DataLoader", "<", "K", ",", "V", ">", "newMappedDataLoader", "(", "MappedBatchLoaderWithContext", "<", "K", ",", "V", ">", "batchLoadFunction", ")", "{", "return", "newMappedDataLoader", "(", "batchLoadFunction", ",", "null", ")", ";", "}" ]
Creates new DataLoader with the specified mapped batch loader function and default options (batching, caching and unlimited batch size). @param batchLoadFunction the batch load function to use @param <K> the key type @param <V> the value type @return a new DataLoader
[ "Creates", "new", "DataLoader", "with", "the", "specified", "mapped", "batch", "loader", "function", "and", "default", "options", "(", "batching", "caching", "and", "unlimited", "batch", "size", ")", "." ]
train
https://github.com/graphql-java/java-dataloader/blob/dfdc8133ead10aa723f896b4a1fa4a1cec9a6fbc/src/main/java/org/dataloader/DataLoader.java#L278-L280
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java
PersistenceBrokerImpl.getPlainDBObject
private Object getPlainDBObject(ClassDescriptor cld, Identity oid) throws ClassNotPersistenceCapableException { """ Retrieve an plain object (without populated references) by it's identity from the database @param cld the real {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the object to refresh @param oid the {@link org.apache.ojb.broker.Identity} of the object @return A new plain object read from the database or <em>null</em> if not found @throws ClassNotPersistenceCapableException """ Object newObj = null; // Class is NOT an Interface: it has a directly mapped table and we lookup this table first: if (!cld.isInterface()) { // 1. try to retrieve skalar fields from directly mapped table columns newObj = dbAccess.materializeObject(cld, oid); } // if we did not find the object yet AND if the cld represents an Extent, // we can lookup all tables of the extent classes: if (newObj == null && cld.isExtent()) { Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator(); while (extents.hasNext()) { ClassDescriptor extCld = (ClassDescriptor) extents.next(); newObj = dbAccess.materializeObject(extCld, oid); if (newObj != null) { break; } } } return newObj; }
java
private Object getPlainDBObject(ClassDescriptor cld, Identity oid) throws ClassNotPersistenceCapableException { Object newObj = null; // Class is NOT an Interface: it has a directly mapped table and we lookup this table first: if (!cld.isInterface()) { // 1. try to retrieve skalar fields from directly mapped table columns newObj = dbAccess.materializeObject(cld, oid); } // if we did not find the object yet AND if the cld represents an Extent, // we can lookup all tables of the extent classes: if (newObj == null && cld.isExtent()) { Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator(); while (extents.hasNext()) { ClassDescriptor extCld = (ClassDescriptor) extents.next(); newObj = dbAccess.materializeObject(extCld, oid); if (newObj != null) { break; } } } return newObj; }
[ "private", "Object", "getPlainDBObject", "(", "ClassDescriptor", "cld", ",", "Identity", "oid", ")", "throws", "ClassNotPersistenceCapableException", "{", "Object", "newObj", "=", "null", ";", "// Class is NOT an Interface: it has a directly mapped table and we lookup this table first:", "if", "(", "!", "cld", ".", "isInterface", "(", ")", ")", "{", "// 1. try to retrieve skalar fields from directly mapped table columns", "newObj", "=", "dbAccess", ".", "materializeObject", "(", "cld", ",", "oid", ")", ";", "}", "// if we did not find the object yet AND if the cld represents an Extent,", "// we can lookup all tables of the extent classes:", "if", "(", "newObj", "==", "null", "&&", "cld", ".", "isExtent", "(", ")", ")", "{", "Iterator", "extents", "=", "getDescriptorRepository", "(", ")", ".", "getAllConcreteSubclassDescriptors", "(", "cld", ")", ".", "iterator", "(", ")", ";", "while", "(", "extents", ".", "hasNext", "(", ")", ")", "{", "ClassDescriptor", "extCld", "=", "(", "ClassDescriptor", ")", "extents", ".", "next", "(", ")", ";", "newObj", "=", "dbAccess", ".", "materializeObject", "(", "extCld", ",", "oid", ")", ";", "if", "(", "newObj", "!=", "null", ")", "{", "break", ";", "}", "}", "}", "return", "newObj", ";", "}" ]
Retrieve an plain object (without populated references) by it's identity from the database @param cld the real {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the object to refresh @param oid the {@link org.apache.ojb.broker.Identity} of the object @return A new plain object read from the database or <em>null</em> if not found @throws ClassNotPersistenceCapableException
[ "Retrieve", "an", "plain", "object", "(", "without", "populated", "references", ")", "by", "it", "s", "identity", "from", "the", "database" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1536-L1565
geomajas/geomajas-project-server
impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java
StringContentTilePainter.createLabelDocument
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo) throws RenderException { """ Create a document that parses the tile's labelFragment, using GraphicsWriter classes. @param writer writer @param labelStyleInfo label style info @return graphics document @throws RenderException cannot render """ if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo, geoService, textService)); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight, getTransformer(), labelStyleInfo, geoService, textService)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
java
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo, geoService, textService)); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight, getTransformer(), labelStyleInfo, geoService, textService)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
[ "private", "GraphicsDocument", "createLabelDocument", "(", "StringWriter", "writer", ",", "LabelStyleInfo", "labelStyleInfo", ")", "throws", "RenderException", "{", "if", "(", "TileMetadata", ".", "PARAM_SVG_RENDERER", ".", "equalsIgnoreCase", "(", "renderer", ")", ")", "{", "DefaultSvgDocument", "document", "=", "new", "DefaultSvgDocument", "(", "writer", ",", "false", ")", ";", "document", ".", "setMaximumFractionDigits", "(", "MAXIMUM_FRACTION_DIGITS", ")", ";", "document", ".", "registerWriter", "(", "InternalTileImpl", ".", "class", ",", "new", "SvgLabelTileWriter", "(", "getTransformer", "(", ")", ",", "labelStyleInfo", ",", "geoService", ",", "textService", ")", ")", ";", "return", "document", ";", "}", "else", "if", "(", "TileMetadata", ".", "PARAM_VML_RENDERER", ".", "equalsIgnoreCase", "(", "renderer", ")", ")", "{", "DefaultVmlDocument", "document", "=", "new", "DefaultVmlDocument", "(", "writer", ")", ";", "int", "coordWidth", "=", "tile", ".", "getScreenWidth", "(", ")", ";", "int", "coordHeight", "=", "tile", ".", "getScreenHeight", "(", ")", ";", "document", ".", "registerWriter", "(", "InternalFeatureImpl", ".", "class", ",", "new", "VmlFeatureWriter", "(", "getTransformer", "(", ")", ",", "coordWidth", ",", "coordHeight", ")", ")", ";", "document", ".", "registerWriter", "(", "InternalTileImpl", ".", "class", ",", "new", "VmlLabelTileWriter", "(", "coordWidth", ",", "coordHeight", ",", "getTransformer", "(", ")", ",", "labelStyleInfo", ",", "geoService", ",", "textService", ")", ")", ";", "document", ".", "setMaximumFractionDigits", "(", "MAXIMUM_FRACTION_DIGITS", ")", ";", "return", "document", ";", "}", "else", "{", "throw", "new", "RenderException", "(", "ExceptionCode", ".", "RENDERER_TYPE_NOT_SUPPORTED", ",", "renderer", ")", ";", "}", "}" ]
Create a document that parses the tile's labelFragment, using GraphicsWriter classes. @param writer writer @param labelStyleInfo label style info @return graphics document @throws RenderException cannot render
[ "Create", "a", "document", "that", "parses", "the", "tile", "s", "labelFragment", "using", "GraphicsWriter", "classes", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java#L282-L304
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.startsWithAny
public static boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) { """ <p>Check if a CharSequence starts with any of the provided case-sensitive prefixes.</p> <pre> StringUtils.startsWithAny(null, null) = false StringUtils.startsWithAny(null, new String[] {"abc"}) = false StringUtils.startsWithAny("abcxyz", null) = false StringUtils.startsWithAny("abcxyz", new String[] {""}) = true StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX") = false StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc") = false </pre> @param sequence the CharSequence to check, may be null @param searchStrings the case-sensitive CharSequence prefixes, may be empty or contain {@code null} @see StringUtils#startsWith(CharSequence, CharSequence) @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or the input {@code sequence} begins with any of the provided case-sensitive {@code searchStrings}. @since 2.5 @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...) """ if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) { return false; } for (final CharSequence searchString : searchStrings) { if (startsWith(sequence, searchString)) { return true; } } return false; }
java
public static boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) { if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) { return false; } for (final CharSequence searchString : searchStrings) { if (startsWith(sequence, searchString)) { return true; } } return false; }
[ "public", "static", "boolean", "startsWithAny", "(", "final", "CharSequence", "sequence", ",", "final", "CharSequence", "...", "searchStrings", ")", "{", "if", "(", "isEmpty", "(", "sequence", ")", "||", "ArrayUtils", ".", "isEmpty", "(", "searchStrings", ")", ")", "{", "return", "false", ";", "}", "for", "(", "final", "CharSequence", "searchString", ":", "searchStrings", ")", "{", "if", "(", "startsWith", "(", "sequence", ",", "searchString", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
<p>Check if a CharSequence starts with any of the provided case-sensitive prefixes.</p> <pre> StringUtils.startsWithAny(null, null) = false StringUtils.startsWithAny(null, new String[] {"abc"}) = false StringUtils.startsWithAny("abcxyz", null) = false StringUtils.startsWithAny("abcxyz", new String[] {""}) = true StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX") = false StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc") = false </pre> @param sequence the CharSequence to check, may be null @param searchStrings the case-sensitive CharSequence prefixes, may be empty or contain {@code null} @see StringUtils#startsWith(CharSequence, CharSequence) @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or the input {@code sequence} begins with any of the provided case-sensitive {@code searchStrings}. @since 2.5 @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
[ "<p", ">", "Check", "if", "a", "CharSequence", "starts", "with", "any", "of", "the", "provided", "case", "-", "sensitive", "prefixes", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8558-L8568
cesarferreira/AndroidQuickUtils
library/src/main/java/com/google/common/base/internal/Finalizer.java
Finalizer.startFinalizer
public static ReferenceQueue<Object> startFinalizer( Class<?> finalizableReferenceClass, Object frq) { """ Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively. @param finalizableReferenceClass FinalizableReference.class @param frq reference to instance of FinalizableReferenceQueue that started this thread @return ReferenceQueue which Finalizer will poll """ /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage * collected, at which point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException( "Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, frq); finalizer.start(); return finalizer.queue; }
java
public static ReferenceQueue<Object> startFinalizer( Class<?> finalizableReferenceClass, Object frq) { /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage * collected, at which point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException( "Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, frq); finalizer.start(); return finalizer.queue; }
[ "public", "static", "ReferenceQueue", "<", "Object", ">", "startFinalizer", "(", "Class", "<", "?", ">", "finalizableReferenceClass", ",", "Object", "frq", ")", "{", "/*\n * We use FinalizableReference.class for two things:\n *\n * 1) To invoke FinalizableReference.finalizeReferent()\n *\n * 2) To detect when FinalizableReference's class loader has to be garbage\n * collected, at which point, Finalizer can stop running\n */", "if", "(", "!", "finalizableReferenceClass", ".", "getName", "(", ")", ".", "equals", "(", "FINALIZABLE_REFERENCE", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Expected \"", "+", "FINALIZABLE_REFERENCE", "+", "\".\"", ")", ";", "}", "Finalizer", "finalizer", "=", "new", "Finalizer", "(", "finalizableReferenceClass", ",", "frq", ")", ";", "finalizer", ".", "start", "(", ")", ";", "return", "finalizer", ".", "queue", ";", "}" ]
Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively. @param finalizableReferenceClass FinalizableReference.class @param frq reference to instance of FinalizableReferenceQueue that started this thread @return ReferenceQueue which Finalizer will poll
[ "Starts", "the", "Finalizer", "thread", ".", "FinalizableReferenceQueue", "calls", "this", "method", "reflectively", "." ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/com/google/common/base/internal/Finalizer.java#L67-L85
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java
ModelSerializer.getObjectFromFile
public static <T> T getObjectFromFile(@NonNull File f, @NonNull String key) { """ Get an object with the specified key from the model file, that was previously added to the file using {@link #addObjectToFile(File, String, Object)} @param f model file to add the object to @param key Key for the object @param <T> Type of the object @return The serialized object @see #listObjectsInFile(File) """ Preconditions.checkState(f.exists(), "File must exist: %s", f); Preconditions.checkArgument(!(UPDATER_BIN.equalsIgnoreCase(key) || NORMALIZER_BIN.equalsIgnoreCase(key) || CONFIGURATION_JSON.equalsIgnoreCase(key) || COEFFICIENTS_BIN.equalsIgnoreCase(key) || NO_PARAMS_MARKER.equalsIgnoreCase(key) || PREPROCESSOR_BIN.equalsIgnoreCase(key)), "Invalid key: Key is reserved for internal use: \"%s\"", key); try (ZipFile zipFile = new ZipFile(f)) { ZipEntry entry = zipFile.getEntry("objects/" + key); if(entry == null){ throw new IllegalStateException("No object with key \"" + key + "\" found"); } Object o; try(ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(zipFile.getInputStream(entry)))){ o = ois.readObject(); } zipFile.close(); return (T)o; } catch (IOException | ClassNotFoundException e){ throw new RuntimeException("Error reading object (key = " + key + ") from file " + f, e); } }
java
public static <T> T getObjectFromFile(@NonNull File f, @NonNull String key){ Preconditions.checkState(f.exists(), "File must exist: %s", f); Preconditions.checkArgument(!(UPDATER_BIN.equalsIgnoreCase(key) || NORMALIZER_BIN.equalsIgnoreCase(key) || CONFIGURATION_JSON.equalsIgnoreCase(key) || COEFFICIENTS_BIN.equalsIgnoreCase(key) || NO_PARAMS_MARKER.equalsIgnoreCase(key) || PREPROCESSOR_BIN.equalsIgnoreCase(key)), "Invalid key: Key is reserved for internal use: \"%s\"", key); try (ZipFile zipFile = new ZipFile(f)) { ZipEntry entry = zipFile.getEntry("objects/" + key); if(entry == null){ throw new IllegalStateException("No object with key \"" + key + "\" found"); } Object o; try(ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(zipFile.getInputStream(entry)))){ o = ois.readObject(); } zipFile.close(); return (T)o; } catch (IOException | ClassNotFoundException e){ throw new RuntimeException("Error reading object (key = " + key + ") from file " + f, e); } }
[ "public", "static", "<", "T", ">", "T", "getObjectFromFile", "(", "@", "NonNull", "File", "f", ",", "@", "NonNull", "String", "key", ")", "{", "Preconditions", ".", "checkState", "(", "f", ".", "exists", "(", ")", ",", "\"File must exist: %s\"", ",", "f", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "(", "UPDATER_BIN", ".", "equalsIgnoreCase", "(", "key", ")", "||", "NORMALIZER_BIN", ".", "equalsIgnoreCase", "(", "key", ")", "||", "CONFIGURATION_JSON", ".", "equalsIgnoreCase", "(", "key", ")", "||", "COEFFICIENTS_BIN", ".", "equalsIgnoreCase", "(", "key", ")", "||", "NO_PARAMS_MARKER", ".", "equalsIgnoreCase", "(", "key", ")", "||", "PREPROCESSOR_BIN", ".", "equalsIgnoreCase", "(", "key", ")", ")", ",", "\"Invalid key: Key is reserved for internal use: \\\"%s\\\"\"", ",", "key", ")", ";", "try", "(", "ZipFile", "zipFile", "=", "new", "ZipFile", "(", "f", ")", ")", "{", "ZipEntry", "entry", "=", "zipFile", ".", "getEntry", "(", "\"objects/\"", "+", "key", ")", ";", "if", "(", "entry", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"No object with key \\\"\"", "+", "key", "+", "\"\\\" found\"", ")", ";", "}", "Object", "o", ";", "try", "(", "ObjectInputStream", "ois", "=", "new", "ObjectInputStream", "(", "new", "BufferedInputStream", "(", "zipFile", ".", "getInputStream", "(", "entry", ")", ")", ")", ")", "{", "o", "=", "ois", ".", "readObject", "(", ")", ";", "}", "zipFile", ".", "close", "(", ")", ";", "return", "(", "T", ")", "o", ";", "}", "catch", "(", "IOException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error reading object (key = \"", "+", "key", "+", "\") from file \"", "+", "f", ",", "e", ")", ";", "}", "}" ]
Get an object with the specified key from the model file, that was previously added to the file using {@link #addObjectToFile(File, String, Object)} @param f model file to add the object to @param key Key for the object @param <T> Type of the object @return The serialized object @see #listObjectsInFile(File)
[ "Get", "an", "object", "with", "the", "specified", "key", "from", "the", "model", "file", "that", "was", "previously", "added", "to", "the", "file", "using", "{", "@link", "#addObjectToFile", "(", "File", "String", "Object", ")", "}" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java#L847-L869
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/util/SecretDetector.java
SecretDetector.maskText
private static String maskText(String text, int begPos, int endPos) { """ Masks given text between begin position and end position. @param text text to mask @param begPos begin position (inclusive) @param endPos end position (exclusive) @return masked text """ // Convert the SQL statement to a char array to obe able to modify it. char[] chars = text.toCharArray(); // Mask the value in the SQL statement using *. for (int curPos = begPos; curPos < endPos; curPos++) { chars[curPos] = '☺'; } // Convert it back to a string return String.valueOf(chars); }
java
private static String maskText(String text, int begPos, int endPos) { // Convert the SQL statement to a char array to obe able to modify it. char[] chars = text.toCharArray(); // Mask the value in the SQL statement using *. for (int curPos = begPos; curPos < endPos; curPos++) { chars[curPos] = '☺'; } // Convert it back to a string return String.valueOf(chars); }
[ "private", "static", "String", "maskText", "(", "String", "text", ",", "int", "begPos", ",", "int", "endPos", ")", "{", "// Convert the SQL statement to a char array to obe able to modify it.", "char", "[", "]", "chars", "=", "text", ".", "toCharArray", "(", ")", ";", "// Mask the value in the SQL statement using *.", "for", "(", "int", "curPos", "=", "begPos", ";", "curPos", "<", "endPos", ";", "curPos", "++", ")", "{", "chars", "[", "curPos", "]", "=", "'", "", "", "}", "// Convert it back to a string", "return", "String", ".", "valueOf", "(", "chars", ")", ";", "}" ]
Masks given text between begin position and end position. @param text text to mask @param begPos begin position (inclusive) @param endPos end position (exclusive) @return masked text
[ "Masks", "given", "text", "between", "begin", "position", "and", "end", "position", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/util/SecretDetector.java#L155-L168
jbossws/jbossws-common
src/main/java/org/jboss/ws/common/injection/resolvers/ResourceReferenceResolver.java
ResourceReferenceResolver.getName
private static String getName(final String resourceName, final String fallBackName) { """ Returns JNDI resource name. @param resourceName to use if specified @param fallBackName fall back bean name otherwise @return JNDI resource name """ return resourceName.length() > 0 ? resourceName : fallBackName; }
java
private static String getName(final String resourceName, final String fallBackName) { return resourceName.length() > 0 ? resourceName : fallBackName; }
[ "private", "static", "String", "getName", "(", "final", "String", "resourceName", ",", "final", "String", "fallBackName", ")", "{", "return", "resourceName", ".", "length", "(", ")", ">", "0", "?", "resourceName", ":", "fallBackName", ";", "}" ]
Returns JNDI resource name. @param resourceName to use if specified @param fallBackName fall back bean name otherwise @return JNDI resource name
[ "Returns", "JNDI", "resource", "name", "." ]
train
https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/injection/resolvers/ResourceReferenceResolver.java#L77-L80
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java
ModelSerializer.restoreComputationGraphAndNormalizer
public static Pair<ComputationGraph, Normalizer> restoreComputationGraphAndNormalizer( @NonNull InputStream is, boolean loadUpdater) throws IOException { """ Restore a ComputationGraph and Normalizer (if present - null if not) from the InputStream. Note: the input stream is read fully and closed by this method. Consequently, the input stream cannot be re-used. @param is Input stream to read from @param loadUpdater Whether to load the updater from the model or not @return Model and normalizer, if present @throws IOException If an error occurs when reading from the stream """ checkInputStream(is); File tmpFile = null; try { tmpFile = tempFileFromStream(is); return restoreComputationGraphAndNormalizer(tmpFile, loadUpdater); } finally { if (tmpFile != null) { tmpFile.delete(); } } }
java
public static Pair<ComputationGraph, Normalizer> restoreComputationGraphAndNormalizer( @NonNull InputStream is, boolean loadUpdater) throws IOException { checkInputStream(is); File tmpFile = null; try { tmpFile = tempFileFromStream(is); return restoreComputationGraphAndNormalizer(tmpFile, loadUpdater); } finally { if (tmpFile != null) { tmpFile.delete(); } } }
[ "public", "static", "Pair", "<", "ComputationGraph", ",", "Normalizer", ">", "restoreComputationGraphAndNormalizer", "(", "@", "NonNull", "InputStream", "is", ",", "boolean", "loadUpdater", ")", "throws", "IOException", "{", "checkInputStream", "(", "is", ")", ";", "File", "tmpFile", "=", "null", ";", "try", "{", "tmpFile", "=", "tempFileFromStream", "(", "is", ")", ";", "return", "restoreComputationGraphAndNormalizer", "(", "tmpFile", ",", "loadUpdater", ")", ";", "}", "finally", "{", "if", "(", "tmpFile", "!=", "null", ")", "{", "tmpFile", ".", "delete", "(", ")", ";", "}", "}", "}" ]
Restore a ComputationGraph and Normalizer (if present - null if not) from the InputStream. Note: the input stream is read fully and closed by this method. Consequently, the input stream cannot be re-used. @param is Input stream to read from @param loadUpdater Whether to load the updater from the model or not @return Model and normalizer, if present @throws IOException If an error occurs when reading from the stream
[ "Restore", "a", "ComputationGraph", "and", "Normalizer", "(", "if", "present", "-", "null", "if", "not", ")", "from", "the", "InputStream", ".", "Note", ":", "the", "input", "stream", "is", "read", "fully", "and", "closed", "by", "this", "method", ".", "Consequently", "the", "input", "stream", "cannot", "be", "re", "-", "used", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java#L510-L523
aws/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/OpenXJsonSerDe.java
OpenXJsonSerDe.withColumnToJsonKeyMappings
public OpenXJsonSerDe withColumnToJsonKeyMappings(java.util.Map<String, String> columnToJsonKeyMappings) { """ <p> Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. </p> @param columnToJsonKeyMappings Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. @return Returns a reference to this object so that method calls can be chained together. """ setColumnToJsonKeyMappings(columnToJsonKeyMappings); return this; }
java
public OpenXJsonSerDe withColumnToJsonKeyMappings(java.util.Map<String, String> columnToJsonKeyMappings) { setColumnToJsonKeyMappings(columnToJsonKeyMappings); return this; }
[ "public", "OpenXJsonSerDe", "withColumnToJsonKeyMappings", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "columnToJsonKeyMappings", ")", "{", "setColumnToJsonKeyMappings", "(", "columnToJsonKeyMappings", ")", ";", "return", "this", ";", "}" ]
<p> Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. </p> @param columnToJsonKeyMappings Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Maps", "column", "names", "to", "JSON", "keys", "that", "aren", "t", "identical", "to", "the", "column", "names", ".", "This", "is", "useful", "when", "the", "JSON", "contains", "keys", "that", "are", "Hive", "keywords", ".", "For", "example", "<code", ">", "timestamp<", "/", "code", ">", "is", "a", "Hive", "keyword", ".", "If", "you", "have", "a", "JSON", "key", "named", "<code", ">", "timestamp<", "/", "code", ">", "set", "this", "parameter", "to", "<code", ">", "{", "ts", ":", "timestamp", "}", "<", "/", "code", ">", "to", "map", "this", "key", "to", "a", "column", "named", "<code", ">", "ts<", "/", "code", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/OpenXJsonSerDe.java#L271-L274
michael-rapp/AndroidMaterialValidation
library/src/main/java/de/mrapp/android/validation/Validators.java
Validators.maxLength
public static Validator<CharSequence> maxLength(@NonNull final Context context, @StringRes final int resourceId, final int maxLength) { """ Creates and returns a validator, which allows to validate texts to ensure, that they are not longer than a specific length. @param context The context, which should be used to retrieve the error message, as an instance of the class {@link Context}. The context may not be null @param resourceId The resource ID of the string resource, which contains the error message, which should be set, as an {@link Integer} value. The resource ID must correspond to a valid string resource @param maxLength The maximum length a text may have as an {@link Integer} value. The maximum length must be at least 1 @return The validator, which has been created, as an instance of the type {@link Validator} """ return new MaxLengthValidator(context, resourceId, maxLength); }
java
public static Validator<CharSequence> maxLength(@NonNull final Context context, @StringRes final int resourceId, final int maxLength) { return new MaxLengthValidator(context, resourceId, maxLength); }
[ "public", "static", "Validator", "<", "CharSequence", ">", "maxLength", "(", "@", "NonNull", "final", "Context", "context", ",", "@", "StringRes", "final", "int", "resourceId", ",", "final", "int", "maxLength", ")", "{", "return", "new", "MaxLengthValidator", "(", "context", ",", "resourceId", ",", "maxLength", ")", ";", "}" ]
Creates and returns a validator, which allows to validate texts to ensure, that they are not longer than a specific length. @param context The context, which should be used to retrieve the error message, as an instance of the class {@link Context}. The context may not be null @param resourceId The resource ID of the string resource, which contains the error message, which should be set, as an {@link Integer} value. The resource ID must correspond to a valid string resource @param maxLength The maximum length a text may have as an {@link Integer} value. The maximum length must be at least 1 @return The validator, which has been created, as an instance of the type {@link Validator}
[ "Creates", "and", "returns", "a", "validator", "which", "allows", "to", "validate", "texts", "to", "ensure", "that", "they", "are", "not", "longer", "than", "a", "specific", "length", "." ]
train
https://github.com/michael-rapp/AndroidMaterialValidation/blob/ac8693baeac7abddf2e38a47da4c1849d4661a8b/library/src/main/java/de/mrapp/android/validation/Validators.java#L482-L486
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java
Integer.parseUnsignedInt
public static int parseUnsignedInt(String s, int radix) throws NumberFormatException { """ Parses the string argument as an unsigned integer in the radix specified by the second argument. An unsigned integer maps the values usually associated with negative numbers to positive numbers larger than {@code MAX_VALUE}. The characters in the string must all be digits of the specified radix (as determined by whether {@link java.lang.Character#digit(char, int)} returns a nonnegative value), except that the first character may be an ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}). The resulting integer value is returned. <p>An exception of type {@code NumberFormatException} is thrown if any of the following situations occurs: <ul> <li>The first argument is {@code null} or is a string of length zero. <li>The radix is either smaller than {@link java.lang.Character#MIN_RADIX} or larger than {@link java.lang.Character#MAX_RADIX}. <li>Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign {@code '+'} ({@code '\u005Cu002B'}) provided that the string is longer than length 1. <li>The value represented by the string is larger than the largest unsigned {@code int}, 2<sup>32</sup>-1. </ul> @param s the {@code String} containing the unsigned integer representation to be parsed @param radix the radix to be used while parsing {@code s}. @return the integer represented by the string argument in the specified radix. @throws NumberFormatException if the {@code String} does not contain a parsable {@code int}. @since 1.8 """ if (s == null) { throw new NumberFormatException("null"); } int len = s.length(); if (len > 0) { char firstChar = s.charAt(0); if (firstChar == '-') { throw new NumberFormatException(String.format("Illegal leading minus sign " + "on unsigned string %s.", s)); } else { if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits return parseInt(s, radix); } else { long ell = Long.parseLong(s, radix); if ((ell & 0xffff_ffff_0000_0000L) == 0) { return (int) ell; } else { throw new NumberFormatException(String.format("String value %s exceeds " + "range of unsigned int.", s)); } } } } else { throw NumberFormatException.forInputString(s); } }
java
public static int parseUnsignedInt(String s, int radix) throws NumberFormatException { if (s == null) { throw new NumberFormatException("null"); } int len = s.length(); if (len > 0) { char firstChar = s.charAt(0); if (firstChar == '-') { throw new NumberFormatException(String.format("Illegal leading minus sign " + "on unsigned string %s.", s)); } else { if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits return parseInt(s, radix); } else { long ell = Long.parseLong(s, radix); if ((ell & 0xffff_ffff_0000_0000L) == 0) { return (int) ell; } else { throw new NumberFormatException(String.format("String value %s exceeds " + "range of unsigned int.", s)); } } } } else { throw NumberFormatException.forInputString(s); } }
[ "public", "static", "int", "parseUnsignedInt", "(", "String", "s", ",", "int", "radix", ")", "throws", "NumberFormatException", "{", "if", "(", "s", "==", "null", ")", "{", "throw", "new", "NumberFormatException", "(", "\"null\"", ")", ";", "}", "int", "len", "=", "s", ".", "length", "(", ")", ";", "if", "(", "len", ">", "0", ")", "{", "char", "firstChar", "=", "s", ".", "charAt", "(", "0", ")", ";", "if", "(", "firstChar", "==", "'", "'", ")", "{", "throw", "new", "NumberFormatException", "(", "String", ".", "format", "(", "\"Illegal leading minus sign \"", "+", "\"on unsigned string %s.\"", ",", "s", ")", ")", ";", "}", "else", "{", "if", "(", "len", "<=", "5", "||", "// Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits", "(", "radix", "==", "10", "&&", "len", "<=", "9", ")", ")", "{", "// Integer.MAX_VALUE in base 10 is 10 digits", "return", "parseInt", "(", "s", ",", "radix", ")", ";", "}", "else", "{", "long", "ell", "=", "Long", ".", "parseLong", "(", "s", ",", "radix", ")", ";", "if", "(", "(", "ell", "&", "0xffff_ffff_0000_0000", "L", ")", "==", "0", ")", "{", "return", "(", "int", ")", "ell", ";", "}", "else", "{", "throw", "new", "NumberFormatException", "(", "String", ".", "format", "(", "\"String value %s exceeds \"", "+", "\"range of unsigned int.\"", ",", "s", ")", ")", ";", "}", "}", "}", "}", "else", "{", "throw", "NumberFormatException", ".", "forInputString", "(", "s", ")", ";", "}", "}" ]
Parses the string argument as an unsigned integer in the radix specified by the second argument. An unsigned integer maps the values usually associated with negative numbers to positive numbers larger than {@code MAX_VALUE}. The characters in the string must all be digits of the specified radix (as determined by whether {@link java.lang.Character#digit(char, int)} returns a nonnegative value), except that the first character may be an ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}). The resulting integer value is returned. <p>An exception of type {@code NumberFormatException} is thrown if any of the following situations occurs: <ul> <li>The first argument is {@code null} or is a string of length zero. <li>The radix is either smaller than {@link java.lang.Character#MIN_RADIX} or larger than {@link java.lang.Character#MAX_RADIX}. <li>Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign {@code '+'} ({@code '\u005Cu002B'}) provided that the string is longer than length 1. <li>The value represented by the string is larger than the largest unsigned {@code int}, 2<sup>32</sup>-1. </ul> @param s the {@code String} containing the unsigned integer representation to be parsed @param radix the radix to be used while parsing {@code s}. @return the integer represented by the string argument in the specified radix. @throws NumberFormatException if the {@code String} does not contain a parsable {@code int}. @since 1.8
[ "Parses", "the", "string", "argument", "as", "an", "unsigned", "integer", "in", "the", "radix", "specified", "by", "the", "second", "argument", ".", "An", "unsigned", "integer", "maps", "the", "values", "usually", "associated", "with", "negative", "numbers", "to", "positive", "numbers", "larger", "than", "{", "@code", "MAX_VALUE", "}", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java#L478-L509
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java
BouncyCastleUtil.getCertificateType
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException { """ Returns the certificate type of the given certificate. Please see {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType} for details for determining the certificate type. @param cert the certificate to get the type of. @param trustedCerts the trusted certificates to double check the {@link GSIConstants#EEC GSIConstants.EEC} certificate against. @return the certificate type as determined by {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType}. @exception CertificateException if something goes wrong. """ try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); Collection c = trustedCerts.getCertificates(selector); if (c != null && c.size() > 0) { type = GSIConstants.CertificateType.CA; } } return type; } catch (Exception e) { // but this should not happen throw new CertificateException("", e); } }
java
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException { try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); Collection c = trustedCerts.getCertificates(selector); if (c != null && c.size() > 0) { type = GSIConstants.CertificateType.CA; } } return type; } catch (Exception e) { // but this should not happen throw new CertificateException("", e); } }
[ "public", "static", "GSIConstants", ".", "CertificateType", "getCertificateType", "(", "X509Certificate", "cert", ",", "CertStore", "trustedCerts", ")", "throws", "CertificateException", "{", "try", "{", "TBSCertificateStructure", "crt", "=", "getTBSCertificateStructure", "(", "cert", ")", ";", "GSIConstants", ".", "CertificateType", "type", "=", "getCertificateType", "(", "crt", ")", ";", "// check subject of the cert in trusted cert list", "// to make sure the cert is not a ca cert", "if", "(", "type", "==", "GSIConstants", ".", "CertificateType", ".", "EEC", ")", "{", "X509CertSelector", "selector", "=", "new", "X509CertSelector", "(", ")", ";", "selector", ".", "setSubject", "(", "cert", ".", "getSubjectX500Principal", "(", ")", ")", ";", "Collection", "c", "=", "trustedCerts", ".", "getCertificates", "(", "selector", ")", ";", "if", "(", "c", "!=", "null", "&&", "c", ".", "size", "(", ")", ">", "0", ")", "{", "type", "=", "GSIConstants", ".", "CertificateType", ".", "CA", ";", "}", "}", "return", "type", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// but this should not happen", "throw", "new", "CertificateException", "(", "\"\"", ",", "e", ")", ";", "}", "}" ]
Returns the certificate type of the given certificate. Please see {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType} for details for determining the certificate type. @param cert the certificate to get the type of. @param trustedCerts the trusted certificates to double check the {@link GSIConstants#EEC GSIConstants.EEC} certificate against. @return the certificate type as determined by {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType}. @exception CertificateException if something goes wrong.
[ "Returns", "the", "certificate", "type", "of", "the", "given", "certificate", ".", "Please", "see", "{", "@link", "#getCertificateType", "(", "TBSCertificateStructure", "TrustedCertificates", ")", "getCertificateType", "}", "for", "details", "for", "determining", "the", "certificate", "type", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java#L181-L202
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/log/FormatterConsoleLog.java
FormatterConsoleLog.formatMessage
String formatMessage(int msgLogLevel, String module, String msg) { """ Formats log message for console output. Short version. @param msgLogLevel Message log level. @param module SDK module details @param msg Log message. @return Formatted log message. """ return getLevelTag(msgLogLevel) + module + ": " + msg; }
java
String formatMessage(int msgLogLevel, String module, String msg) { return getLevelTag(msgLogLevel) + module + ": " + msg; }
[ "String", "formatMessage", "(", "int", "msgLogLevel", ",", "String", "module", ",", "String", "msg", ")", "{", "return", "getLevelTag", "(", "msgLogLevel", ")", "+", "module", "+", "\": \"", "+", "msg", ";", "}" ]
Formats log message for console output. Short version. @param msgLogLevel Message log level. @param module SDK module details @param msg Log message. @return Formatted log message.
[ "Formats", "log", "message", "for", "console", "output", ".", "Short", "version", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/log/FormatterConsoleLog.java#L39-L41
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/type/GeometryTypeNameFromConstraint.java
GeometryTypeNameFromConstraint.getGeometryTypeNameFromConstraint
public static String getGeometryTypeNameFromConstraint(String constraint, int numericPrecision) { """ Parse the constraint and return the Geometry type name. @param constraint Constraint on geometry type @param numericPrecision of the geometry type @return Geometry type """ int geometryTypeCode = GeometryTypeFromConstraint.geometryTypeFromConstraint(constraint, numericPrecision); return SFSUtilities.getGeometryTypeNameFromCode(geometryTypeCode); }
java
public static String getGeometryTypeNameFromConstraint(String constraint, int numericPrecision) { int geometryTypeCode = GeometryTypeFromConstraint.geometryTypeFromConstraint(constraint, numericPrecision); return SFSUtilities.getGeometryTypeNameFromCode(geometryTypeCode); }
[ "public", "static", "String", "getGeometryTypeNameFromConstraint", "(", "String", "constraint", ",", "int", "numericPrecision", ")", "{", "int", "geometryTypeCode", "=", "GeometryTypeFromConstraint", ".", "geometryTypeFromConstraint", "(", "constraint", ",", "numericPrecision", ")", ";", "return", "SFSUtilities", ".", "getGeometryTypeNameFromCode", "(", "geometryTypeCode", ")", ";", "}" ]
Parse the constraint and return the Geometry type name. @param constraint Constraint on geometry type @param numericPrecision of the geometry type @return Geometry type
[ "Parse", "the", "constraint", "and", "return", "the", "Geometry", "type", "name", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/type/GeometryTypeNameFromConstraint.java#L49-L52
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/ShuttleListBinding.java
ShuttleListBinding.equalByComparator
private boolean equalByComparator(Object o1, Object o2) { """ Using the configured comparator (or equals if not configured), determine if two objects are equal. @param o1 Object to compare @param o2 Object to compare @return boolean true if objects are equal """ return comparator == null ? o1.equals(o2) : comparator.compare(o1, o2) == 0; }
java
private boolean equalByComparator(Object o1, Object o2) { return comparator == null ? o1.equals(o2) : comparator.compare(o1, o2) == 0; }
[ "private", "boolean", "equalByComparator", "(", "Object", "o1", ",", "Object", "o2", ")", "{", "return", "comparator", "==", "null", "?", "o1", ".", "equals", "(", "o2", ")", ":", "comparator", ".", "compare", "(", "o1", ",", "o2", ")", "==", "0", ";", "}" ]
Using the configured comparator (or equals if not configured), determine if two objects are equal. @param o1 Object to compare @param o2 Object to compare @return boolean true if objects are equal
[ "Using", "the", "configured", "comparator", "(", "or", "equals", "if", "not", "configured", ")", "determine", "if", "two", "objects", "are", "equal", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/ShuttleListBinding.java#L400-L402
apache/groovy
subprojects/groovy-sql/src/main/java/groovy/sql/GroovyResultSetExtension.java
GroovyResultSetExtension.setProperty
public void setProperty(String columnName, Object newValue) { """ Updates the designated column with an <code>Object</code> value. @param columnName the SQL name of the column @param newValue the updated value @throws MissingPropertyException if an SQLException happens while setting the new value @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) @see ResultSet#updateObject(java.lang.String, java.lang.Object) """ try { getResultSet().updateObject(columnName, newValue); updated = true; } catch (SQLException e) { throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e); } }
java
public void setProperty(String columnName, Object newValue) { try { getResultSet().updateObject(columnName, newValue); updated = true; } catch (SQLException e) { throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e); } }
[ "public", "void", "setProperty", "(", "String", "columnName", ",", "Object", "newValue", ")", "{", "try", "{", "getResultSet", "(", ")", ".", "updateObject", "(", "columnName", ",", "newValue", ")", ";", "updated", "=", "true", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "MissingPropertyException", "(", "columnName", ",", "GroovyResultSetProxy", ".", "class", ",", "e", ")", ";", "}", "}" ]
Updates the designated column with an <code>Object</code> value. @param columnName the SQL name of the column @param newValue the updated value @throws MissingPropertyException if an SQLException happens while setting the new value @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object) @see ResultSet#updateObject(java.lang.String, java.lang.Object)
[ "Updates", "the", "designated", "column", "with", "an", "<code", ">", "Object<", "/", "code", ">", "value", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/GroovyResultSetExtension.java#L133-L141
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/MutableDocument.java
MutableDocument.setString
@NonNull @Override public MutableDocument setString(@NonNull String key, String value) { """ Set a String value for the given key @param key the key. @param key the String value. @return this MutableDocument instance """ return setValue(key, value); }
java
@NonNull @Override public MutableDocument setString(@NonNull String key, String value) { return setValue(key, value); }
[ "@", "NonNull", "@", "Override", "public", "MutableDocument", "setString", "(", "@", "NonNull", "String", "key", ",", "String", "value", ")", "{", "return", "setValue", "(", "key", ",", "value", ")", ";", "}" ]
Set a String value for the given key @param key the key. @param key the String value. @return this MutableDocument instance
[ "Set", "a", "String", "value", "for", "the", "given", "key" ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableDocument.java#L158-L162
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/AccountsApi.java
AccountsApi.updateCustomField
public CustomFields updateCustomField(String accountId, String customFieldId, CustomField customField) throws ApiException { """ Updates an existing account custom field. @param accountId The external account number (int) or account ID Guid. (required) @param customFieldId (required) @param customField (optional) @return CustomFields """ return updateCustomField(accountId, customFieldId, customField, null); }
java
public CustomFields updateCustomField(String accountId, String customFieldId, CustomField customField) throws ApiException { return updateCustomField(accountId, customFieldId, customField, null); }
[ "public", "CustomFields", "updateCustomField", "(", "String", "accountId", ",", "String", "customFieldId", ",", "CustomField", "customField", ")", "throws", "ApiException", "{", "return", "updateCustomField", "(", "accountId", ",", "customFieldId", ",", "customField", ",", "null", ")", ";", "}" ]
Updates an existing account custom field. @param accountId The external account number (int) or account ID Guid. (required) @param customFieldId (required) @param customField (optional) @return CustomFields
[ "Updates", "an", "existing", "account", "custom", "field", "." ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L2736-L2738
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java
AffectedDeploymentOverlay.redeployLinksAndTransformOperation
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException { """ It will look for all the deployments under the deploymentsRootAddress with a runtimeName in the specified list of runtime names and then transform the operation so that every server having those deployments will redeploy the affected deployments. @see #transformOperation @param removeOperation @param context @param deploymentsRootAddress @param runtimeNames @throws OperationFailedException """ Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames); Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create(); if (deploymentNames.isEmpty()) { for (String s : runtimeNames) { ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue()); } } if(removeOperation != null) { opBuilder.addStep(removeOperation); } for (String deploymentName : deploymentNames) { opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName))); } List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS); if (transformers == null) { context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>()); } final ModelNode slave = opBuilder.build().getOperation(); transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress())); }
java
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException { Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames); Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create(); if (deploymentNames.isEmpty()) { for (String s : runtimeNames) { ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue()); } } if(removeOperation != null) { opBuilder.addStep(removeOperation); } for (String deploymentName : deploymentNames) { opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName))); } List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS); if (transformers == null) { context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>()); } final ModelNode slave = opBuilder.build().getOperation(); transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress())); }
[ "public", "static", "void", "redeployLinksAndTransformOperation", "(", "OperationContext", "context", ",", "ModelNode", "removeOperation", ",", "PathAddress", "deploymentsRootAddress", ",", "Set", "<", "String", ">", "runtimeNames", ")", "throws", "OperationFailedException", "{", "Set", "<", "String", ">", "deploymentNames", "=", "listDeployments", "(", "context", ".", "readResourceFromRoot", "(", "deploymentsRootAddress", ")", ",", "runtimeNames", ")", ";", "Operations", ".", "CompositeOperationBuilder", "opBuilder", "=", "Operations", ".", "CompositeOperationBuilder", ".", "create", "(", ")", ";", "if", "(", "deploymentNames", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "String", "s", ":", "runtimeNames", ")", "{", "ServerLogger", ".", "ROOT_LOGGER", ".", "debugf", "(", "\"We haven't found any deployment for %s in server-group %s\"", ",", "s", ",", "deploymentsRootAddress", ".", "getLastElement", "(", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", "if", "(", "removeOperation", "!=", "null", ")", "{", "opBuilder", ".", "addStep", "(", "removeOperation", ")", ";", "}", "for", "(", "String", "deploymentName", ":", "deploymentNames", ")", "{", "opBuilder", ".", "addStep", "(", "addRedeployStep", "(", "deploymentsRootAddress", ".", "append", "(", "DEPLOYMENT", ",", "deploymentName", ")", ")", ")", ";", "}", "List", "<", "DomainOperationTransmuter", ">", "transformers", "=", "context", ".", "getAttachment", "(", "OperationAttachments", ".", "SLAVE_SERVER_OPERATION_TRANSMUTERS", ")", ";", "if", "(", "transformers", "==", "null", ")", "{", "context", ".", "attach", "(", "OperationAttachments", ".", "SLAVE_SERVER_OPERATION_TRANSMUTERS", ",", "transformers", "=", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "final", "ModelNode", "slave", "=", "opBuilder", ".", "build", "(", ")", ".", "getOperation", "(", ")", ";", "transformers", ".", "add", "(", "new", "OverlayOperationTransmuter", "(", "slave", ",", "context", ".", "getCurrentAddress", "(", ")", ")", ")", ";", "}" ]
It will look for all the deployments under the deploymentsRootAddress with a runtimeName in the specified list of runtime names and then transform the operation so that every server having those deployments will redeploy the affected deployments. @see #transformOperation @param removeOperation @param context @param deploymentsRootAddress @param runtimeNames @throws OperationFailedException
[ "It", "will", "look", "for", "all", "the", "deployments", "under", "the", "deploymentsRootAddress", "with", "a", "runtimeName", "in", "the", "specified", "list", "of", "runtime", "names", "and", "then", "transform", "the", "operation", "so", "that", "every", "server", "having", "those", "deployments", "will", "redeploy", "the", "affected", "deployments", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java#L196-L216
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java
JBossASClient.createReadAttributeRequest
public static ModelNode createReadAttributeRequest(String attributeName, Address address) { """ Convienence method that allows you to create request that reads a single attribute value to a resource. @param attributeName the name of the attribute whose value is to be read @param address identifies the resource @return the request """ return createReadAttributeRequest(false, attributeName, address); }
java
public static ModelNode createReadAttributeRequest(String attributeName, Address address) { return createReadAttributeRequest(false, attributeName, address); }
[ "public", "static", "ModelNode", "createReadAttributeRequest", "(", "String", "attributeName", ",", "Address", "address", ")", "{", "return", "createReadAttributeRequest", "(", "false", ",", "attributeName", ",", "address", ")", ";", "}" ]
Convienence method that allows you to create request that reads a single attribute value to a resource. @param attributeName the name of the attribute whose value is to be read @param address identifies the resource @return the request
[ "Convienence", "method", "that", "allows", "you", "to", "create", "request", "that", "reads", "a", "single", "attribute", "value", "to", "a", "resource", "." ]
train
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java#L82-L84
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/TableAppender.java
TableAppender.flushAllAvailableRows
public void flushAllAvailableRows(final XMLUtil util, final Appendable appendable) throws IOException { """ Open the table, flush all rows from start, but do not freeze the table @param util a XMLUtil instance for writing XML @param appendable where to write @throws IOException if an I/O error occurs during the flush """ this.appendPreamble(util, appendable); this.appendRows(util, appendable, 0); }
java
public void flushAllAvailableRows(final XMLUtil util, final Appendable appendable) throws IOException { this.appendPreamble(util, appendable); this.appendRows(util, appendable, 0); }
[ "public", "void", "flushAllAvailableRows", "(", "final", "XMLUtil", "util", ",", "final", "Appendable", "appendable", ")", "throws", "IOException", "{", "this", ".", "appendPreamble", "(", "util", ",", "appendable", ")", ";", "this", ".", "appendRows", "(", "util", ",", "appendable", ",", "0", ")", ";", "}" ]
Open the table, flush all rows from start, but do not freeze the table @param util a XMLUtil instance for writing XML @param appendable where to write @throws IOException if an I/O error occurs during the flush
[ "Open", "the", "table", "flush", "all", "rows", "from", "start", "but", "do", "not", "freeze", "the", "table" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/TableAppender.java#L105-L108
btrplace/scheduler
json/src/main/java/org/btrplace/json/JSONs.java
JSONs.requiredDouble
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException { """ Read an expected double. @param o the object to parse @param id the key in the map that points to the double @return the double @throws JSONConverterException if the key does not point to a double """ checkKeys(o, id); Object x = o.get(id); if (!(x instanceof Number)) { throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'."); } return ((Number) x).doubleValue(); }
java
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException { checkKeys(o, id); Object x = o.get(id); if (!(x instanceof Number)) { throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'."); } return ((Number) x).doubleValue(); }
[ "public", "static", "double", "requiredDouble", "(", "JSONObject", "o", ",", "String", "id", ")", "throws", "JSONConverterException", "{", "checkKeys", "(", "o", ",", "id", ")", ";", "Object", "x", "=", "o", ".", "get", "(", "id", ")", ";", "if", "(", "!", "(", "x", "instanceof", "Number", ")", ")", "{", "throw", "new", "JSONConverterException", "(", "\"Number expected at key '\"", "+", "id", "+", "\"' but was '\"", "+", "x", ".", "getClass", "(", ")", "+", "\"'.\"", ")", ";", "}", "return", "(", "(", "Number", ")", "x", ")", ".", "doubleValue", "(", ")", ";", "}" ]
Read an expected double. @param o the object to parse @param id the key in the map that points to the double @return the double @throws JSONConverterException if the key does not point to a double
[ "Read", "an", "expected", "double", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/JSONs.java#L158-L165
OpenLiberty/open-liberty
dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/jaas/JAASConfigurationImpl.java
JAASConfigurationImpl.ensureProxyIsNotSpecifyInSystemDefaultEntry
private void ensureProxyIsNotSpecifyInSystemDefaultEntry(String entryName, List<JAASLoginModuleConfig> loginModules) { """ The proxy (WSLoginModuleProxy) can not be configured for the system.DEFAULT. @param entryName @param loginModules """ for (Iterator<JAASLoginModuleConfig> i = loginModules.iterator(); i.hasNext();) { JAASLoginModuleConfig loginModule = i.next(); if (loginModule.getId().equalsIgnoreCase(JAASLoginModuleConfig.PROXY)) { Tr.warning(tc, "JAAS_PROXY_IS_NOT_SUPPORT_IN_SYSTEM_DEFAULT"); i.remove(); } } }
java
private void ensureProxyIsNotSpecifyInSystemDefaultEntry(String entryName, List<JAASLoginModuleConfig> loginModules) { for (Iterator<JAASLoginModuleConfig> i = loginModules.iterator(); i.hasNext();) { JAASLoginModuleConfig loginModule = i.next(); if (loginModule.getId().equalsIgnoreCase(JAASLoginModuleConfig.PROXY)) { Tr.warning(tc, "JAAS_PROXY_IS_NOT_SUPPORT_IN_SYSTEM_DEFAULT"); i.remove(); } } }
[ "private", "void", "ensureProxyIsNotSpecifyInSystemDefaultEntry", "(", "String", "entryName", ",", "List", "<", "JAASLoginModuleConfig", ">", "loginModules", ")", "{", "for", "(", "Iterator", "<", "JAASLoginModuleConfig", ">", "i", "=", "loginModules", ".", "iterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "JAASLoginModuleConfig", "loginModule", "=", "i", ".", "next", "(", ")", ";", "if", "(", "loginModule", ".", "getId", "(", ")", ".", "equalsIgnoreCase", "(", "JAASLoginModuleConfig", ".", "PROXY", ")", ")", "{", "Tr", ".", "warning", "(", "tc", ",", "\"JAAS_PROXY_IS_NOT_SUPPORT_IN_SYSTEM_DEFAULT\"", ")", ";", "i", ".", "remove", "(", ")", ";", "}", "}", "}" ]
The proxy (WSLoginModuleProxy) can not be configured for the system.DEFAULT. @param entryName @param loginModules
[ "The", "proxy", "(", "WSLoginModuleProxy", ")", "can", "not", "be", "configured", "for", "the", "system", ".", "DEFAULT", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/jaas/JAASConfigurationImpl.java#L121-L129
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/BaseMessageItemStream.java
BaseMessageItemStream.setWatermarks
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark) { """ Set the MsgStore watermarks so that we get informed the next time the message depth crosses either of them (510343) @param currentDepth @throws SevereMessageStoreException @throws NotInMessageStore """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "setWatermarks", new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark) }); try { setWatermarks(nextLowWatermark, nextHighWatermark, -1, -1); } catch (MessageStoreException e) { // MessageStoreException shouldn't occur so FFDC. FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.BaseMessageItemStream.setWatermarks", "1:702:1.24", this); SibTr.exception(tc, e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "setWatermarks"); }
java
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "setWatermarks", new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark) }); try { setWatermarks(nextLowWatermark, nextHighWatermark, -1, -1); } catch (MessageStoreException e) { // MessageStoreException shouldn't occur so FFDC. FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.BaseMessageItemStream.setWatermarks", "1:702:1.24", this); SibTr.exception(tc, e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "setWatermarks"); }
[ "protected", "void", "setWatermarks", "(", "long", "nextLowWatermark", ",", "long", "nextHighWatermark", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"setWatermarks\"", ",", "new", "Object", "[", "]", "{", "new", "Long", "(", "nextLowWatermark", ")", ",", "new", "Long", "(", "nextHighWatermark", ")", "}", ")", ";", "try", "{", "setWatermarks", "(", "nextLowWatermark", ",", "nextHighWatermark", ",", "-", "1", ",", "-", "1", ")", ";", "}", "catch", "(", "MessageStoreException", "e", ")", "{", "// MessageStoreException shouldn't occur so FFDC.", "FFDCFilter", ".", "processException", "(", "e", ",", "\"com.ibm.ws.sib.processor.impl.store.itemstreams.BaseMessageItemStream.setWatermarks\"", ",", "\"1:702:1.24\"", ",", "this", ")", ";", "SibTr", ".", "exception", "(", "tc", ",", "e", ")", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"setWatermarks\"", ")", ";", "}" ]
Set the MsgStore watermarks so that we get informed the next time the message depth crosses either of them (510343) @param currentDepth @throws SevereMessageStoreException @throws NotInMessageStore
[ "Set", "the", "MsgStore", "watermarks", "so", "that", "we", "get", "informed", "the", "next", "time", "the", "message", "depth", "crosses", "either", "of", "them", "(", "510343", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/BaseMessageItemStream.java#L676-L698
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java
OjbTagsHandler.forAllIndices
public void forAllIndices(String template, Properties attributes) throws XDocletException { """ Processes the template for all indices of the current table. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block" @doc.param name="unique" optional="true" description="Whether to process the unique indices or not" values="true,false" """ boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false); // first the default index _curIndexDef = _curTableDef.getIndex(null); if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique())) { generate(template); } for (Iterator it = _curTableDef.getIndices(); it.hasNext(); ) { _curIndexDef = (IndexDef)it.next(); if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique())) { generate(template); } } _curIndexDef = null; }
java
public void forAllIndices(String template, Properties attributes) throws XDocletException { boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false); // first the default index _curIndexDef = _curTableDef.getIndex(null); if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique())) { generate(template); } for (Iterator it = _curTableDef.getIndices(); it.hasNext(); ) { _curIndexDef = (IndexDef)it.next(); if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique())) { generate(template); } } _curIndexDef = null; }
[ "public", "void", "forAllIndices", "(", "String", "template", ",", "Properties", "attributes", ")", "throws", "XDocletException", "{", "boolean", "processUnique", "=", "TypeConversionUtil", ".", "stringToBoolean", "(", "attributes", ".", "getProperty", "(", "ATTRIBUTE_UNIQUE", ")", ",", "false", ")", ";", "// first the default index\r", "_curIndexDef", "=", "_curTableDef", ".", "getIndex", "(", "null", ")", ";", "if", "(", "(", "_curIndexDef", "!=", "null", ")", "&&", "(", "processUnique", "==", "_curIndexDef", ".", "isUnique", "(", ")", ")", ")", "{", "generate", "(", "template", ")", ";", "}", "for", "(", "Iterator", "it", "=", "_curTableDef", ".", "getIndices", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "_curIndexDef", "=", "(", "IndexDef", ")", "it", ".", "next", "(", ")", ";", "if", "(", "!", "_curIndexDef", ".", "isDefault", "(", ")", "&&", "(", "processUnique", "==", "_curIndexDef", ".", "isUnique", "(", ")", ")", ")", "{", "generate", "(", "template", ")", ";", "}", "}", "_curIndexDef", "=", "null", ";", "}" ]
Processes the template for all indices of the current table. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block" @doc.param name="unique" optional="true" description="Whether to process the unique indices or not" values="true,false"
[ "Processes", "the", "template", "for", "all", "indices", "of", "the", "current", "table", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1402-L1421
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java
CommerceOrderPersistenceImpl.findByBillingAddressId
@Override public List<CommerceOrder> findByBillingAddressId(long billingAddressId, int start, int end) { """ Returns a range of all the commerce orders where billingAddressId = &#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 CommerceOrderModelImpl}. 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 billingAddressId the billing address ID @param start the lower bound of the range of commerce orders @param end the upper bound of the range of commerce orders (not inclusive) @return the range of matching commerce orders """ return findByBillingAddressId(billingAddressId, start, end, null); }
java
@Override public List<CommerceOrder> findByBillingAddressId(long billingAddressId, int start, int end) { return findByBillingAddressId(billingAddressId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceOrder", ">", "findByBillingAddressId", "(", "long", "billingAddressId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByBillingAddressId", "(", "billingAddressId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce orders where billingAddressId = &#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 CommerceOrderModelImpl}. 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 billingAddressId the billing address ID @param start the lower bound of the range of commerce orders @param end the upper bound of the range of commerce orders (not inclusive) @return the range of matching commerce orders
[ "Returns", "a", "range", "of", "all", "the", "commerce", "orders", "where", "billingAddressId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L2538-L2542
Azure/azure-sdk-for-java
batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java
JobsInner.listRemoteLoginInformationWithServiceResponseAsync
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> listRemoteLoginInformationWithServiceResponseAsync(final String resourceGroupName, final String workspaceName, final String experimentName, final String jobName) { """ Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param experimentName The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RemoteLoginInformationInner&gt; object """ return listRemoteLoginInformationSinglePageAsync(resourceGroupName, workspaceName, experimentName, jobName) .concatMap(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Observable<ServiceResponse<Page<RemoteLoginInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> call(ServiceResponse<Page<RemoteLoginInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listRemoteLoginInformationNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> listRemoteLoginInformationWithServiceResponseAsync(final String resourceGroupName, final String workspaceName, final String experimentName, final String jobName) { return listRemoteLoginInformationSinglePageAsync(resourceGroupName, workspaceName, experimentName, jobName) .concatMap(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Observable<ServiceResponse<Page<RemoteLoginInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> call(ServiceResponse<Page<RemoteLoginInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listRemoteLoginInformationNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", ">", "listRemoteLoginInformationWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "workspaceName", ",", "final", "String", "experimentName", ",", "final", "String", "jobName", ")", "{", "return", "listRemoteLoginInformationSinglePageAsync", "(", "resourceGroupName", ",", "workspaceName", ",", "experimentName", ",", "jobName", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listRemoteLoginInformationNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param experimentName The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RemoteLoginInformationInner&gt; object
[ "Gets", "a", "list", "of", "currently", "existing", "nodes", "which", "were", "used", "for", "the", "Job", "execution", ".", "The", "returned", "information", "contains", "the", "node", "ID", "its", "public", "IP", "and", "SSH", "port", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java#L1099-L1111
auth0/auth0-java
src/main/java/com/auth0/client/auth/AuthorizeUrlBuilder.java
AuthorizeUrlBuilder.newInstance
static AuthorizeUrlBuilder newInstance(HttpUrl baseUrl, String clientId, String redirectUri) { """ Creates an instance of the {@link AuthorizeUrlBuilder} using the given domain and base parameters. @param baseUrl the base url constructed from a valid domain. @param clientId the application's client_id value to set @param redirectUri the redirect_uri value to set. Must be already URL Encoded and must be white-listed in your Auth0's dashboard. @return a new instance of the {@link AuthorizeUrlBuilder} to configure. """ return new AuthorizeUrlBuilder(baseUrl, clientId, redirectUri); }
java
static AuthorizeUrlBuilder newInstance(HttpUrl baseUrl, String clientId, String redirectUri) { return new AuthorizeUrlBuilder(baseUrl, clientId, redirectUri); }
[ "static", "AuthorizeUrlBuilder", "newInstance", "(", "HttpUrl", "baseUrl", ",", "String", "clientId", ",", "String", "redirectUri", ")", "{", "return", "new", "AuthorizeUrlBuilder", "(", "baseUrl", ",", "clientId", ",", "redirectUri", ")", ";", "}" ]
Creates an instance of the {@link AuthorizeUrlBuilder} using the given domain and base parameters. @param baseUrl the base url constructed from a valid domain. @param clientId the application's client_id value to set @param redirectUri the redirect_uri value to set. Must be already URL Encoded and must be white-listed in your Auth0's dashboard. @return a new instance of the {@link AuthorizeUrlBuilder} to configure.
[ "Creates", "an", "instance", "of", "the", "{", "@link", "AuthorizeUrlBuilder", "}", "using", "the", "given", "domain", "and", "base", "parameters", "." ]
train
https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/AuthorizeUrlBuilder.java#L27-L29
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Paginator.java
Paginator.setCurrentPageIndex
public void setCurrentPageIndex(int currentPageIndex, boolean skipCheck) { """ Sets an index of a current page. This method will make a quick count query to check that the index you are setting is within the boundaries. @param currentPageIndex index of a current page. @param skipCheck <code>true</code> to skip the upper boundary check (will not make a call to DB). """ if( currentPageIndex < 1){ throw new IndexOutOfBoundsException("currentPageIndex cannot be < 1"); } if(!skipCheck){ if(currentPageIndex > pageCount()){ throw new IndexOutOfBoundsException("currentPageIndex it outside of record set boundaries. "); } } this.currentPageIndex = currentPageIndex; }
java
public void setCurrentPageIndex(int currentPageIndex, boolean skipCheck){ if( currentPageIndex < 1){ throw new IndexOutOfBoundsException("currentPageIndex cannot be < 1"); } if(!skipCheck){ if(currentPageIndex > pageCount()){ throw new IndexOutOfBoundsException("currentPageIndex it outside of record set boundaries. "); } } this.currentPageIndex = currentPageIndex; }
[ "public", "void", "setCurrentPageIndex", "(", "int", "currentPageIndex", ",", "boolean", "skipCheck", ")", "{", "if", "(", "currentPageIndex", "<", "1", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"currentPageIndex cannot be < 1\"", ")", ";", "}", "if", "(", "!", "skipCheck", ")", "{", "if", "(", "currentPageIndex", ">", "pageCount", "(", ")", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"currentPageIndex it outside of record set boundaries. \"", ")", ";", "}", "}", "this", ".", "currentPageIndex", "=", "currentPageIndex", ";", "}" ]
Sets an index of a current page. This method will make a quick count query to check that the index you are setting is within the boundaries. @param currentPageIndex index of a current page. @param skipCheck <code>true</code> to skip the upper boundary check (will not make a call to DB).
[ "Sets", "an", "index", "of", "a", "current", "page", ".", "This", "method", "will", "make", "a", "quick", "count", "query", "to", "check", "that", "the", "index", "you", "are", "setting", "is", "within", "the", "boundaries", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Paginator.java#L398-L409
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WSubMenu.java
WSubMenu.handleRequest
@Override public void handleRequest(final Request request) { """ Override handleRequest in order to perform processing for this component. This implementation checks for submenu selection and executes the associated action if it has been set. @param request the request being responded to. """ if (isDisabled()) { // Protect against client-side tampering of disabled/read-only fields. return; } if (isMenuPresent(request)) { // If current ajax trigger, process menu for current selections if (AjaxHelper.isCurrentAjaxTrigger(this)) { WMenu menu = WebUtilities.getAncestorOfClass(WMenu.class, this); menu.handleRequest(request); // Execute associated action, if set final Action action = getAction(); if (action != null) { final ActionEvent event = new ActionEvent(this, this.getActionCommand(), this.getActionObject()); Runnable later = new Runnable() { @Override public void run() { action.execute(event); } }; invokeLater(later); } } boolean openState = "true".equals(request.getParameter(getId() + ".open")); setOpen(openState); } }
java
@Override public void handleRequest(final Request request) { if (isDisabled()) { // Protect against client-side tampering of disabled/read-only fields. return; } if (isMenuPresent(request)) { // If current ajax trigger, process menu for current selections if (AjaxHelper.isCurrentAjaxTrigger(this)) { WMenu menu = WebUtilities.getAncestorOfClass(WMenu.class, this); menu.handleRequest(request); // Execute associated action, if set final Action action = getAction(); if (action != null) { final ActionEvent event = new ActionEvent(this, this.getActionCommand(), this.getActionObject()); Runnable later = new Runnable() { @Override public void run() { action.execute(event); } }; invokeLater(later); } } boolean openState = "true".equals(request.getParameter(getId() + ".open")); setOpen(openState); } }
[ "@", "Override", "public", "void", "handleRequest", "(", "final", "Request", "request", ")", "{", "if", "(", "isDisabled", "(", ")", ")", "{", "// Protect against client-side tampering of disabled/read-only fields.", "return", ";", "}", "if", "(", "isMenuPresent", "(", "request", ")", ")", "{", "// If current ajax trigger, process menu for current selections", "if", "(", "AjaxHelper", ".", "isCurrentAjaxTrigger", "(", "this", ")", ")", "{", "WMenu", "menu", "=", "WebUtilities", ".", "getAncestorOfClass", "(", "WMenu", ".", "class", ",", "this", ")", ";", "menu", ".", "handleRequest", "(", "request", ")", ";", "// Execute associated action, if set", "final", "Action", "action", "=", "getAction", "(", ")", ";", "if", "(", "action", "!=", "null", ")", "{", "final", "ActionEvent", "event", "=", "new", "ActionEvent", "(", "this", ",", "this", ".", "getActionCommand", "(", ")", ",", "this", ".", "getActionObject", "(", ")", ")", ";", "Runnable", "later", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "action", ".", "execute", "(", "event", ")", ";", "}", "}", ";", "invokeLater", "(", "later", ")", ";", "}", "}", "boolean", "openState", "=", "\"true\"", ".", "equals", "(", "request", ".", "getParameter", "(", "getId", "(", ")", "+", "\".open\"", ")", ")", ";", "setOpen", "(", "openState", ")", ";", "}", "}" ]
Override handleRequest in order to perform processing for this component. This implementation checks for submenu selection and executes the associated action if it has been set. @param request the request being responded to.
[ "Override", "handleRequest", "in", "order", "to", "perform", "processing", "for", "this", "component", ".", "This", "implementation", "checks", "for", "submenu", "selection", "and", "executes", "the", "associated", "action", "if", "it", "has", "been", "set", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WSubMenu.java#L519-L553
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
WhiteboxImpl.findField
private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) { """ Find field. @param object the object @param strategy the strategy @param where the where @return the field """ return findSingleFieldUsingStrategy(strategy, object, false, where); }
java
private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) { return findSingleFieldUsingStrategy(strategy, object, false, where); }
[ "private", "static", "Field", "findField", "(", "Object", "object", ",", "FieldMatcherStrategy", "strategy", ",", "Class", "<", "?", ">", "where", ")", "{", "return", "findSingleFieldUsingStrategy", "(", "strategy", ",", "object", ",", "false", ",", "where", ")", ";", "}" ]
Find field. @param object the object @param strategy the strategy @param where the where @return the field
[ "Find", "field", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L465-L467
centic9/commons-dost
src/main/java/org/dstadler/commons/svn/SVNCommands.java
SVNCommands.getRemoteFileContent
public static InputStream getRemoteFileContent(String file, long revision, String baseUrl, String user, String pwd) throws IOException { """ Retrieve the contents of a file from the web-interface of the SVN server. @param file The file to fetch from the SVN server via @param revision The SVN revision to use @param baseUrl The SVN url to connect to @param user The SVN user or null if the default user from the machine should be used @param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file. @return An InputStream which provides the content of the revision of the specified file @throws IOException Execution of the SVN sub-process failed or the sub-process returned a exit value indicating a failure """ // svn cat -r 666 file CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_CAT); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument("-r"); cmdLine.addArgument(Long.toString(revision)); cmdLine.addArgument(baseUrl + file); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
java
public static InputStream getRemoteFileContent(String file, long revision, String baseUrl, String user, String pwd) throws IOException { // svn cat -r 666 file CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_CAT); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument("-r"); cmdLine.addArgument(Long.toString(revision)); cmdLine.addArgument(baseUrl + file); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
[ "public", "static", "InputStream", "getRemoteFileContent", "(", "String", "file", ",", "long", "revision", ",", "String", "baseUrl", ",", "String", "user", ",", "String", "pwd", ")", "throws", "IOException", "{", "// svn cat -r 666 file", "CommandLine", "cmdLine", "=", "new", "CommandLine", "(", "SVN_CMD", ")", ";", "cmdLine", ".", "addArgument", "(", "CMD_CAT", ")", ";", "addDefaultArguments", "(", "cmdLine", ",", "user", ",", "pwd", ")", ";", "cmdLine", ".", "addArgument", "(", "\"-r\"", ")", ";", "cmdLine", ".", "addArgument", "(", "Long", ".", "toString", "(", "revision", ")", ")", ";", "cmdLine", ".", "addArgument", "(", "baseUrl", "+", "file", ")", ";", "return", "ExecutionHelper", ".", "getCommandResult", "(", "cmdLine", ",", "new", "File", "(", "\".\"", ")", ",", "0", ",", "120000", ")", ";", "}" ]
Retrieve the contents of a file from the web-interface of the SVN server. @param file The file to fetch from the SVN server via @param revision The SVN revision to use @param baseUrl The SVN url to connect to @param user The SVN user or null if the default user from the machine should be used @param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file. @return An InputStream which provides the content of the revision of the specified file @throws IOException Execution of the SVN sub-process failed or the sub-process returned a exit value indicating a failure
[ "Retrieve", "the", "contents", "of", "a", "file", "from", "the", "web", "-", "interface", "of", "the", "SVN", "server", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L229-L239
apache/incubator-gobblin
gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanAjaxAPIClient.java
AzkabanAjaxAPIClient.createAzkabanProject
public static String createAzkabanProject(String sessionId, String zipFilePath, AzkabanProjectConfig azkabanProjectConfig) throws IOException { """ * Creates an Azkaban project and uploads the zip file. If proxy user and group permissions are specified in Azkaban Project Config, then this method also adds it to the project configuration. @param sessionId Session Id. @param zipFilePath Zip file to upload. @param azkabanProjectConfig Azkaban Project Config. @return Project Id. @throws IOException """ Map<String, String> params = Maps.newHashMap(); params.put("ajax", "executeFlow"); params.put("name", azkabanProjectConfig.getAzkabanProjectName()); params.put("description", azkabanProjectConfig.getAzkabanProjectDescription()); executePostRequest(preparePostRequest(azkabanProjectConfig.getAzkabanServerUrl() + "/manager?action=create", sessionId, params)); // Add proxy user if any if (azkabanProjectConfig.getAzkabanUserToProxy().isPresent()) { Iterable<String> proxyUsers = SPLIT_ON_COMMA.split(azkabanProjectConfig.getAzkabanUserToProxy().get()); for (String user : proxyUsers) { addProxyUser(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), user); } } // Add group permissions if any // TODO: Support users (not just groups), and different permission types // (though we can add users, we only support groups at the moment and award them with admin permissions) if (StringUtils.isNotBlank(azkabanProjectConfig.getAzkabanGroupAdminUsers())) { String [] groups = StringUtils.split(azkabanProjectConfig.getAzkabanGroupAdminUsers(), ","); for (String group : groups) { addUserPermission(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), group, true, true, false, false,false, false); } } // Upload zip file to azkaban and return projectId return uploadZipFileToAzkaban(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), zipFilePath); }
java
public static String createAzkabanProject(String sessionId, String zipFilePath, AzkabanProjectConfig azkabanProjectConfig) throws IOException { Map<String, String> params = Maps.newHashMap(); params.put("ajax", "executeFlow"); params.put("name", azkabanProjectConfig.getAzkabanProjectName()); params.put("description", azkabanProjectConfig.getAzkabanProjectDescription()); executePostRequest(preparePostRequest(azkabanProjectConfig.getAzkabanServerUrl() + "/manager?action=create", sessionId, params)); // Add proxy user if any if (azkabanProjectConfig.getAzkabanUserToProxy().isPresent()) { Iterable<String> proxyUsers = SPLIT_ON_COMMA.split(azkabanProjectConfig.getAzkabanUserToProxy().get()); for (String user : proxyUsers) { addProxyUser(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), user); } } // Add group permissions if any // TODO: Support users (not just groups), and different permission types // (though we can add users, we only support groups at the moment and award them with admin permissions) if (StringUtils.isNotBlank(azkabanProjectConfig.getAzkabanGroupAdminUsers())) { String [] groups = StringUtils.split(azkabanProjectConfig.getAzkabanGroupAdminUsers(), ","); for (String group : groups) { addUserPermission(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), group, true, true, false, false,false, false); } } // Upload zip file to azkaban and return projectId return uploadZipFileToAzkaban(sessionId, azkabanProjectConfig.getAzkabanServerUrl(), azkabanProjectConfig.getAzkabanProjectName(), zipFilePath); }
[ "public", "static", "String", "createAzkabanProject", "(", "String", "sessionId", ",", "String", "zipFilePath", ",", "AzkabanProjectConfig", "azkabanProjectConfig", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "Maps", ".", "newHashMap", "(", ")", ";", "params", ".", "put", "(", "\"ajax\"", ",", "\"executeFlow\"", ")", ";", "params", ".", "put", "(", "\"name\"", ",", "azkabanProjectConfig", ".", "getAzkabanProjectName", "(", ")", ")", ";", "params", ".", "put", "(", "\"description\"", ",", "azkabanProjectConfig", ".", "getAzkabanProjectDescription", "(", ")", ")", ";", "executePostRequest", "(", "preparePostRequest", "(", "azkabanProjectConfig", ".", "getAzkabanServerUrl", "(", ")", "+", "\"/manager?action=create\"", ",", "sessionId", ",", "params", ")", ")", ";", "// Add proxy user if any", "if", "(", "azkabanProjectConfig", ".", "getAzkabanUserToProxy", "(", ")", ".", "isPresent", "(", ")", ")", "{", "Iterable", "<", "String", ">", "proxyUsers", "=", "SPLIT_ON_COMMA", ".", "split", "(", "azkabanProjectConfig", ".", "getAzkabanUserToProxy", "(", ")", ".", "get", "(", ")", ")", ";", "for", "(", "String", "user", ":", "proxyUsers", ")", "{", "addProxyUser", "(", "sessionId", ",", "azkabanProjectConfig", ".", "getAzkabanServerUrl", "(", ")", ",", "azkabanProjectConfig", ".", "getAzkabanProjectName", "(", ")", ",", "user", ")", ";", "}", "}", "// Add group permissions if any", "// TODO: Support users (not just groups), and different permission types", "// (though we can add users, we only support groups at the moment and award them with admin permissions)", "if", "(", "StringUtils", ".", "isNotBlank", "(", "azkabanProjectConfig", ".", "getAzkabanGroupAdminUsers", "(", ")", ")", ")", "{", "String", "[", "]", "groups", "=", "StringUtils", ".", "split", "(", "azkabanProjectConfig", ".", "getAzkabanGroupAdminUsers", "(", ")", ",", "\",\"", ")", ";", "for", "(", "String", "group", ":", "groups", ")", "{", "addUserPermission", "(", "sessionId", ",", "azkabanProjectConfig", ".", "getAzkabanServerUrl", "(", ")", ",", "azkabanProjectConfig", ".", "getAzkabanProjectName", "(", ")", ",", "group", ",", "true", ",", "true", ",", "false", ",", "false", ",", "false", ",", "false", ")", ";", "}", "}", "// Upload zip file to azkaban and return projectId", "return", "uploadZipFileToAzkaban", "(", "sessionId", ",", "azkabanProjectConfig", ".", "getAzkabanServerUrl", "(", ")", ",", "azkabanProjectConfig", ".", "getAzkabanProjectName", "(", ")", ",", "zipFilePath", ")", ";", "}" ]
* Creates an Azkaban project and uploads the zip file. If proxy user and group permissions are specified in Azkaban Project Config, then this method also adds it to the project configuration. @param sessionId Session Id. @param zipFilePath Zip file to upload. @param azkabanProjectConfig Azkaban Project Config. @return Project Id. @throws IOException
[ "*", "Creates", "an", "Azkaban", "project", "and", "uploads", "the", "zip", "file", ".", "If", "proxy", "user", "and", "group", "permissions", "are", "specified", "in", "Azkaban", "Project", "Config", "then", "this", "method", "also", "adds", "it", "to", "the", "project", "configuration", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanAjaxAPIClient.java#L122-L155
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setApiKey
public OmdbBuilder setApiKey(final String apiKey) throws OMDBException { """ Set the ApiKey @param apiKey The apikey needed for the contract @return @throws com.omertron.omdbapi.OMDBException """ if (StringUtils.isBlank(apiKey)) { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must provide an ApiKey"); } params.add(Param.APIKEY, apiKey); return this; }
java
public OmdbBuilder setApiKey(final String apiKey) throws OMDBException { if (StringUtils.isBlank(apiKey)) { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must provide an ApiKey"); } params.add(Param.APIKEY, apiKey); return this; }
[ "public", "OmdbBuilder", "setApiKey", "(", "final", "String", "apiKey", ")", "throws", "OMDBException", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "apiKey", ")", ")", "{", "throw", "new", "OMDBException", "(", "ApiExceptionType", ".", "AUTH_FAILURE", ",", "\"Must provide an ApiKey\"", ")", ";", "}", "params", ".", "add", "(", "Param", ".", "APIKEY", ",", "apiKey", ")", ";", "return", "this", ";", "}" ]
Set the ApiKey @param apiKey The apikey needed for the contract @return @throws com.omertron.omdbapi.OMDBException
[ "Set", "the", "ApiKey" ]
train
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L256-L262
kaazing/gateway
transport/spi/src/main/java/org/kaazing/gateway/transport/LoggingUtils.java
LoggingUtils.logIOException
private static void logIOException(String message, Logger logger, Throwable t) { """ IOExceptions ("Network connectivity has been lost or transport was closed at other end") can be frequent due to network timeouts (inactivity timeout) or loss of network connectivity so we only print info level and include a stack trace of the cause, if there is one. """ Throwable cause = t.getCause(); if (cause != null) { logger.info(message, cause); } else { logger.info(message); } }
java
private static void logIOException(String message, Logger logger, Throwable t) { Throwable cause = t.getCause(); if (cause != null) { logger.info(message, cause); } else { logger.info(message); } }
[ "private", "static", "void", "logIOException", "(", "String", "message", ",", "Logger", "logger", ",", "Throwable", "t", ")", "{", "Throwable", "cause", "=", "t", ".", "getCause", "(", ")", ";", "if", "(", "cause", "!=", "null", ")", "{", "logger", ".", "info", "(", "message", ",", "cause", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "message", ")", ";", "}", "}" ]
IOExceptions ("Network connectivity has been lost or transport was closed at other end") can be frequent due to network timeouts (inactivity timeout) or loss of network connectivity so we only print info level and include a stack trace of the cause, if there is one.
[ "IOExceptions", "(", "Network", "connectivity", "has", "been", "lost", "or", "transport", "was", "closed", "at", "other", "end", ")", "can", "be", "frequent", "due", "to", "network", "timeouts", "(", "inactivity", "timeout", ")", "or", "loss", "of", "network", "connectivity", "so", "we", "only", "print", "info", "level", "and", "include", "a", "stack", "trace", "of", "the", "cause", "if", "there", "is", "one", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/transport/spi/src/main/java/org/kaazing/gateway/transport/LoggingUtils.java#L124-L131