repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
Azure/azure-sdk-for-java
batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/ClustersInner.java
ClustersInner.listRemoteLoginInformationAsync
public Observable<Page<RemoteLoginInformationInner>> listRemoteLoginInformationAsync(final String resourceGroupName, final String workspaceName, final String clusterName) { return listRemoteLoginInformationWithServiceResponseAsync(resourceGroupName, workspaceName, clusterName) .map(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Page<RemoteLoginInformationInner>>() { @Override public Page<RemoteLoginInformationInner> call(ServiceResponse<Page<RemoteLoginInformationInner>> response) { return response.body(); } }); }
java
public Observable<Page<RemoteLoginInformationInner>> listRemoteLoginInformationAsync(final String resourceGroupName, final String workspaceName, final String clusterName) { return listRemoteLoginInformationWithServiceResponseAsync(resourceGroupName, workspaceName, clusterName) .map(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Page<RemoteLoginInformationInner>>() { @Override public Page<RemoteLoginInformationInner> call(ServiceResponse<Page<RemoteLoginInformationInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", "listRemoteLoginInformationAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "workspaceName", ",", "final", "String", "clusterName", ")", "{", "return", "listRemoteLoginInformationWithServiceResponseAsync", "(", "resourceGroupName", ",", "workspaceName", ",", "clusterName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", ",", "Page", "<", "RemoteLoginInformationInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "RemoteLoginInformationInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RemoteLoginInformationInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get the IP address, port of all the compute nodes in the Cluster. @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 clusterName The name of the cluster within the specified resource group. Cluster 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
[ "Get", "the", "IP", "address", "port", "of", "all", "the", "compute", "nodes", "in", "the", "Cluster", "." ]
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/ClustersInner.java#L1185-L1193
czyzby/gdx-lml
autumn/src/main/java/com/github/czyzby/autumn/context/ContextInitializer.java
ContextInitializer.invokeProcessorActionsAfterInitiation
private void invokeProcessorActionsAfterInitiation(final Context context, final ContextDestroyer destroyer) { for (final AnnotationProcessor<?> processor : processors) { processor.doAfterScanning(this, context, destroyer); } }
java
private void invokeProcessorActionsAfterInitiation(final Context context, final ContextDestroyer destroyer) { for (final AnnotationProcessor<?> processor : processors) { processor.doAfterScanning(this, context, destroyer); } }
[ "private", "void", "invokeProcessorActionsAfterInitiation", "(", "final", "Context", "context", ",", "final", "ContextDestroyer", "destroyer", ")", "{", "for", "(", "final", "AnnotationProcessor", "<", "?", ">", "processor", ":", "processors", ")", "{", "processor", ".", "doAfterScanning", "(", "this", ",", "context", ",", "destroyer", ")", ";", "}", "}" ]
Calls {@link AnnotationProcessor#doAfterScanning(ContextInitializer, Context, ContextDestroyer)} with "this" argument on each processor. @param context might be required by some processors to finish up. @param destroyer used to register destruction callbacks.
[ "Calls", "{" ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/autumn/src/main/java/com/github/czyzby/autumn/context/ContextInitializer.java#L349-L353
geomajas/geomajas-project-client-gwt
common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java
HtmlBuilder.openTag
private static String openTag(String tag, String clazz, String style, boolean contentIsHtml, String... content) { StringBuilder result = new StringBuilder("<").append(tag); if (clazz != null && !"".equals(clazz)) { result.append(" ").append(Html.Attribute.CLASS).append("='").append(clazz).append("'"); } if (style != null && !"".equals(style)) { result.append(" ").append(Html.Attribute.STYLE).append("='").append(style).append("'"); } result.append(">"); if (content != null && content.length > 0) { for (String c : content) { if (contentIsHtml) { result.append(c); } else { result.append(htmlEncode(c)); } } } return result.toString(); }
java
private static String openTag(String tag, String clazz, String style, boolean contentIsHtml, String... content) { StringBuilder result = new StringBuilder("<").append(tag); if (clazz != null && !"".equals(clazz)) { result.append(" ").append(Html.Attribute.CLASS).append("='").append(clazz).append("'"); } if (style != null && !"".equals(style)) { result.append(" ").append(Html.Attribute.STYLE).append("='").append(style).append("'"); } result.append(">"); if (content != null && content.length > 0) { for (String c : content) { if (contentIsHtml) { result.append(c); } else { result.append(htmlEncode(c)); } } } return result.toString(); }
[ "private", "static", "String", "openTag", "(", "String", "tag", ",", "String", "clazz", ",", "String", "style", ",", "boolean", "contentIsHtml", ",", "String", "...", "content", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "\"<\"", ")", ".", "append", "(", "tag", ")", ";", "if", "(", "clazz", "!=", "null", "&&", "!", "\"\"", ".", "equals", "(", "clazz", ")", ")", "{", "result", ".", "append", "(", "\" \"", ")", ".", "append", "(", "Html", ".", "Attribute", ".", "CLASS", ")", ".", "append", "(", "\"='\"", ")", ".", "append", "(", "clazz", ")", ".", "append", "(", "\"'\"", ")", ";", "}", "if", "(", "style", "!=", "null", "&&", "!", "\"\"", ".", "equals", "(", "style", ")", ")", "{", "result", ".", "append", "(", "\" \"", ")", ".", "append", "(", "Html", ".", "Attribute", ".", "STYLE", ")", ".", "append", "(", "\"='\"", ")", ".", "append", "(", "style", ")", ".", "append", "(", "\"'\"", ")", ";", "}", "result", ".", "append", "(", "\">\"", ")", ";", "if", "(", "content", "!=", "null", "&&", "content", ".", "length", ">", "0", ")", "{", "for", "(", "String", "c", ":", "content", ")", "{", "if", "(", "contentIsHtml", ")", "{", "result", ".", "append", "(", "c", ")", ";", "}", "else", "{", "result", ".", "append", "(", "htmlEncode", "(", "c", ")", ")", ";", "}", "}", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Build a String containing a HTML opening tag with given CSS class and/or style and concatenates the given content. @param tag String name of HTML tag @param clazz CSS class of the tag @param style style for tag (plain CSS) @param contentIsHtml if false content is prepared with {@link HtmlBuilder#htmlEncode(String)}. @param content content string @return HTML tag element as string
[ "Build", "a", "String", "containing", "a", "HTML", "opening", "tag", "with", "given", "CSS", "class", "and", "/", "or", "style", "and", "concatenates", "the", "given", "content", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L419-L439
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemuser_binding.java
systemuser_binding.get
public static systemuser_binding get(nitro_service service, String username) throws Exception{ systemuser_binding obj = new systemuser_binding(); obj.set_username(username); systemuser_binding response = (systemuser_binding) obj.get_resource(service); return response; }
java
public static systemuser_binding get(nitro_service service, String username) throws Exception{ systemuser_binding obj = new systemuser_binding(); obj.set_username(username); systemuser_binding response = (systemuser_binding) obj.get_resource(service); return response; }
[ "public", "static", "systemuser_binding", "get", "(", "nitro_service", "service", ",", "String", "username", ")", "throws", "Exception", "{", "systemuser_binding", "obj", "=", "new", "systemuser_binding", "(", ")", ";", "obj", ".", "set_username", "(", "username", ")", ";", "systemuser_binding", "response", "=", "(", "systemuser_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch systemuser_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "systemuser_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemuser_binding.java#L114-L119
EsotericSoftware/kryo
src/com/esotericsoftware/kryo/util/Generics.java
Generics.pushTypeVariables
public int pushTypeVariables (GenericsHierarchy hierarchy, GenericType[] args) { int startSize = this.argumentsSize; // Ensure arguments capacity. int sizeNeeded = startSize + hierarchy.total; if (sizeNeeded > arguments.length) { Type[] newArray = new Type[Math.max(sizeNeeded, arguments.length << 1)]; System.arraycopy(arguments, 0, newArray, 0, startSize); arguments = newArray; } // Resolve and store the type arguments. int[] counts = hierarchy.counts; TypeVariable[] params = hierarchy.parameters; for (int i = 0, p = 0, n = args.length; i < n; i++) { GenericType arg = args[i]; Class resolved = arg.resolve(this); if (resolved == null) continue; int count = counts[i]; if (arg == null) p += count; else { for (int nn = p + count; p < nn; p++) { arguments[argumentsSize] = params[p]; arguments[argumentsSize + 1] = resolved; argumentsSize += 2; } } } return argumentsSize - startSize; }
java
public int pushTypeVariables (GenericsHierarchy hierarchy, GenericType[] args) { int startSize = this.argumentsSize; // Ensure arguments capacity. int sizeNeeded = startSize + hierarchy.total; if (sizeNeeded > arguments.length) { Type[] newArray = new Type[Math.max(sizeNeeded, arguments.length << 1)]; System.arraycopy(arguments, 0, newArray, 0, startSize); arguments = newArray; } // Resolve and store the type arguments. int[] counts = hierarchy.counts; TypeVariable[] params = hierarchy.parameters; for (int i = 0, p = 0, n = args.length; i < n; i++) { GenericType arg = args[i]; Class resolved = arg.resolve(this); if (resolved == null) continue; int count = counts[i]; if (arg == null) p += count; else { for (int nn = p + count; p < nn; p++) { arguments[argumentsSize] = params[p]; arguments[argumentsSize + 1] = resolved; argumentsSize += 2; } } } return argumentsSize - startSize; }
[ "public", "int", "pushTypeVariables", "(", "GenericsHierarchy", "hierarchy", ",", "GenericType", "[", "]", "args", ")", "{", "int", "startSize", "=", "this", ".", "argumentsSize", ";", "// Ensure arguments capacity.", "int", "sizeNeeded", "=", "startSize", "+", "hierarchy", ".", "total", ";", "if", "(", "sizeNeeded", ">", "arguments", ".", "length", ")", "{", "Type", "[", "]", "newArray", "=", "new", "Type", "[", "Math", ".", "max", "(", "sizeNeeded", ",", "arguments", ".", "length", "<<", "1", ")", "]", ";", "System", ".", "arraycopy", "(", "arguments", ",", "0", ",", "newArray", ",", "0", ",", "startSize", ")", ";", "arguments", "=", "newArray", ";", "}", "// Resolve and store the type arguments.", "int", "[", "]", "counts", "=", "hierarchy", ".", "counts", ";", "TypeVariable", "[", "]", "params", "=", "hierarchy", ".", "parameters", ";", "for", "(", "int", "i", "=", "0", ",", "p", "=", "0", ",", "n", "=", "args", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "GenericType", "arg", "=", "args", "[", "i", "]", ";", "Class", "resolved", "=", "arg", ".", "resolve", "(", "this", ")", ";", "if", "(", "resolved", "==", "null", ")", "continue", ";", "int", "count", "=", "counts", "[", "i", "]", ";", "if", "(", "arg", "==", "null", ")", "p", "+=", "count", ";", "else", "{", "for", "(", "int", "nn", "=", "p", "+", "count", ";", "p", "<", "nn", ";", "p", "++", ")", "{", "arguments", "[", "argumentsSize", "]", "=", "params", "[", "p", "]", ";", "arguments", "[", "argumentsSize", "+", "1", "]", "=", "resolved", ";", "argumentsSize", "+=", "2", ";", "}", "}", "}", "return", "argumentsSize", "-", "startSize", ";", "}" ]
Stores the types of the type parameters for the specified class hierarchy. Must be balanced by {@link #popTypeVariables(int)} if >0 is returned. @param args May contain null for type arguments that aren't known. @return The number of entries that were pushed.
[ "Stores", "the", "types", "of", "the", "type", "parameters", "for", "the", "specified", "class", "hierarchy", ".", "Must", "be", "balanced", "by", "{" ]
train
https://github.com/EsotericSoftware/kryo/blob/a8be1ab26f347f299a3c3f7171d6447dd5390845/src/com/esotericsoftware/kryo/util/Generics.java#L119-L150
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/OverrideService.java
OverrideService.disableAllOverrides
public void disableAllOverrides(int pathID, String clientUUID) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.ENABLED_OVERRIDES_PATH_ID + " = ? " + " AND " + Constants.GENERIC_CLIENT_UUID + " = ? " ); statement.setInt(1, pathID); statement.setString(2, clientUUID); statement.execute(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
public void disableAllOverrides(int pathID, String clientUUID) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.ENABLED_OVERRIDES_PATH_ID + " = ? " + " AND " + Constants.GENERIC_CLIENT_UUID + " = ? " ); statement.setInt(1, pathID); statement.setString(2, clientUUID); statement.execute(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
[ "public", "void", "disableAllOverrides", "(", "int", "pathID", ",", "String", "clientUUID", ")", "{", "PreparedStatement", "statement", "=", "null", ";", "try", "(", "Connection", "sqlConnection", "=", "sqlService", ".", "getConnection", "(", ")", ")", "{", "statement", "=", "sqlConnection", ".", "prepareStatement", "(", "\"DELETE FROM \"", "+", "Constants", ".", "DB_TABLE_ENABLED_OVERRIDE", "+", "\" WHERE \"", "+", "Constants", ".", "ENABLED_OVERRIDES_PATH_ID", "+", "\" = ? \"", "+", "\" AND \"", "+", "Constants", ".", "GENERIC_CLIENT_UUID", "+", "\" = ? \"", ")", ";", "statement", ".", "setInt", "(", "1", ",", "pathID", ")", ";", "statement", ".", "setString", "(", "2", ",", "clientUUID", ")", ";", "statement", ".", "execute", "(", ")", ";", "statement", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "try", "{", "if", "(", "statement", "!=", "null", ")", "{", "statement", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}" ]
Disable all overrides for a specified path @param pathID ID of path containing overrides @param clientUUID UUID of client
[ "Disable", "all", "overrides", "for", "a", "specified", "path" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/OverrideService.java#L528-L550
BlueBrain/bluima
modules/bluima_pdf/src/main/java/edu/psu/seersuite/extractors/tableextractor/extraction/BoxTableExtractor.java
BoxTableExtractor.getTableStructure
public void getTableStructure (int cc, TableCandidate tc, ArrayList<TextPiece> wordsOfAPage) { float minGapBtwColumns = 1000.0f; float[] leftX_tableColumns = tc.getLeftX_tableColumns(); float[] rightX_tableColumns = tc.getRightX_tableColumns(); int YNum = tc.getRows().size(); for (int zz=1; zz<cc; zz++) { float thisColumnGap = leftX_tableColumns[zz]-rightX_tableColumns[zz-1]; if (thisColumnGap<minGapBtwColumns) minGapBtwColumns = thisColumnGap; } double columnGapThreshold = 0.0; //if (withoutKwd==true) columnGapThreshold = parameters.ave_X_Gap_inLine*1.6; if (minGapBtwColumns>columnGapThreshold) { getEachCellContent(YNum, cc, tc); getRealHeadingBasedOnCells(YNum, cc, tc); getColumnHeading(tc); getRowHeadingBasedOnCells(tc); tc.setMetadataStructureLevel(YNum, cc, wordsOfAPage, m_docInfo); //tc.setMetaStructureLevelx(YNum, cc, wordsOfAPage, m_docInfo); if ( (tc.getFootnoteBeginRow()>1) & (tc.getMaxColumnNumber()>1) ) {} else tc.setValid(false); } else { m_docInfo.setErrorMsg("Although we detected some tabular structures in page " + (tc.getPageId_thisTable()+1) + ", we do not treat them as tables because the space gaps between columns are not large enough."); } }
java
public void getTableStructure (int cc, TableCandidate tc, ArrayList<TextPiece> wordsOfAPage) { float minGapBtwColumns = 1000.0f; float[] leftX_tableColumns = tc.getLeftX_tableColumns(); float[] rightX_tableColumns = tc.getRightX_tableColumns(); int YNum = tc.getRows().size(); for (int zz=1; zz<cc; zz++) { float thisColumnGap = leftX_tableColumns[zz]-rightX_tableColumns[zz-1]; if (thisColumnGap<minGapBtwColumns) minGapBtwColumns = thisColumnGap; } double columnGapThreshold = 0.0; //if (withoutKwd==true) columnGapThreshold = parameters.ave_X_Gap_inLine*1.6; if (minGapBtwColumns>columnGapThreshold) { getEachCellContent(YNum, cc, tc); getRealHeadingBasedOnCells(YNum, cc, tc); getColumnHeading(tc); getRowHeadingBasedOnCells(tc); tc.setMetadataStructureLevel(YNum, cc, wordsOfAPage, m_docInfo); //tc.setMetaStructureLevelx(YNum, cc, wordsOfAPage, m_docInfo); if ( (tc.getFootnoteBeginRow()>1) & (tc.getMaxColumnNumber()>1) ) {} else tc.setValid(false); } else { m_docInfo.setErrorMsg("Although we detected some tabular structures in page " + (tc.getPageId_thisTable()+1) + ", we do not treat them as tables because the space gaps between columns are not large enough."); } }
[ "public", "void", "getTableStructure", "(", "int", "cc", ",", "TableCandidate", "tc", ",", "ArrayList", "<", "TextPiece", ">", "wordsOfAPage", ")", "{", "float", "minGapBtwColumns", "=", "1000.0f", ";", "float", "[", "]", "leftX_tableColumns", "=", "tc", ".", "getLeftX_tableColumns", "(", ")", ";", "float", "[", "]", "rightX_tableColumns", "=", "tc", ".", "getRightX_tableColumns", "(", ")", ";", "int", "YNum", "=", "tc", ".", "getRows", "(", ")", ".", "size", "(", ")", ";", "for", "(", "int", "zz", "=", "1", ";", "zz", "<", "cc", ";", "zz", "++", ")", "{", "float", "thisColumnGap", "=", "leftX_tableColumns", "[", "zz", "]", "-", "rightX_tableColumns", "[", "zz", "-", "1", "]", ";", "if", "(", "thisColumnGap", "<", "minGapBtwColumns", ")", "minGapBtwColumns", "=", "thisColumnGap", ";", "}", "double", "columnGapThreshold", "=", "0.0", ";", "//if (withoutKwd==true) columnGapThreshold = parameters.ave_X_Gap_inLine*1.6;\t\r", "if", "(", "minGapBtwColumns", ">", "columnGapThreshold", ")", "{", "getEachCellContent", "(", "YNum", ",", "cc", ",", "tc", ")", ";", "getRealHeadingBasedOnCells", "(", "YNum", ",", "cc", ",", "tc", ")", ";", "getColumnHeading", "(", "tc", ")", ";", "getRowHeadingBasedOnCells", "(", "tc", ")", ";", "tc", ".", "setMetadataStructureLevel", "(", "YNum", ",", "cc", ",", "wordsOfAPage", ",", "m_docInfo", ")", ";", "//tc.setMetaStructureLevelx(YNum, cc, wordsOfAPage, m_docInfo);\r", "if", "(", "(", "tc", ".", "getFootnoteBeginRow", "(", ")", ">", "1", ")", "&", "(", "tc", ".", "getMaxColumnNumber", "(", ")", ">", "1", ")", ")", "{", "}", "else", "tc", ".", "setValid", "(", "false", ")", ";", "}", "else", "{", "m_docInfo", ".", "setErrorMsg", "(", "\"Although we detected some tabular structures in page \"", "+", "(", "tc", ".", "getPageId_thisTable", "(", ")", "+", "1", ")", "+", "\", we do not treat them as tables because the space gaps between columns are not large enough.\"", ")", ";", "}", "}" ]
Implements the table structure decomposition step @param cc the number of the table columns @param tc the object of the table candidate @param wordsOfAPage the list of all the words in a document page
[ "Implements", "the", "table", "structure", "decomposition", "step" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/edu/psu/seersuite/extractors/tableextractor/extraction/BoxTableExtractor.java#L1662-L1689
dspinellis/UMLGraph
src/main/java/org/umlgraph/doclet/UmlGraphDoc.java
UmlGraphDoc.runGraphviz
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) { if (dotExecutable == null) { dotExecutable = "dot"; } File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot"); File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg"); try { Process p = Runtime.getRuntime().exec(new String [] { dotExecutable, "-Tsvg", "-o", svgFile.getAbsolutePath(), dotFile.getAbsolutePath() }); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while((line = reader.readLine()) != null) root.printWarning(line); int result = p.waitFor(); if (result != 0) root.printWarning("Errors running Graphviz on " + dotFile); } catch (Exception e) { e.printStackTrace(); System.err.println("Ensure that dot is in your path and that its path does not contain spaces"); } }
java
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) { if (dotExecutable == null) { dotExecutable = "dot"; } File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot"); File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg"); try { Process p = Runtime.getRuntime().exec(new String [] { dotExecutable, "-Tsvg", "-o", svgFile.getAbsolutePath(), dotFile.getAbsolutePath() }); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while((line = reader.readLine()) != null) root.printWarning(line); int result = p.waitFor(); if (result != 0) root.printWarning("Errors running Graphviz on " + dotFile); } catch (Exception e) { e.printStackTrace(); System.err.println("Ensure that dot is in your path and that its path does not contain spaces"); } }
[ "private", "static", "void", "runGraphviz", "(", "String", "dotExecutable", ",", "String", "outputFolder", ",", "String", "packageName", ",", "String", "name", ",", "RootDoc", "root", ")", "{", "if", "(", "dotExecutable", "==", "null", ")", "{", "dotExecutable", "=", "\"dot\"", ";", "}", "File", "dotFile", "=", "new", "File", "(", "outputFolder", ",", "packageName", ".", "replace", "(", "\".\"", ",", "\"/\"", ")", "+", "\"/\"", "+", "name", "+", "\".dot\"", ")", ";", "File", "svgFile", "=", "new", "File", "(", "outputFolder", ",", "packageName", ".", "replace", "(", "\".\"", ",", "\"/\"", ")", "+", "\"/\"", "+", "name", "+", "\".svg\"", ")", ";", "try", "{", "Process", "p", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "exec", "(", "new", "String", "[", "]", "{", "dotExecutable", ",", "\"-Tsvg\"", ",", "\"-o\"", ",", "svgFile", ".", "getAbsolutePath", "(", ")", ",", "dotFile", ".", "getAbsolutePath", "(", ")", "}", ")", ";", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "p", ".", "getErrorStream", "(", ")", ")", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "root", ".", "printWarning", "(", "line", ")", ";", "int", "result", "=", "p", ".", "waitFor", "(", ")", ";", "if", "(", "result", "!=", "0", ")", "root", ".", "printWarning", "(", "\"Errors running Graphviz on \"", "+", "dotFile", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "System", ".", "err", ".", "println", "(", "\"Ensure that dot is in your path and that its path does not contain spaces\"", ")", ";", "}", "}" ]
Runs Graphviz dot building both a diagram (in png format) and a client side map for it.
[ "Runs", "Graphviz", "dot", "building", "both", "a", "diagram", "(", "in", "png", "format", ")", "and", "a", "client", "side", "map", "for", "it", "." ]
train
https://github.com/dspinellis/UMLGraph/blob/09576db5ae0ea63bfe30ef9fce88a513f9a8d843/src/main/java/org/umlgraph/doclet/UmlGraphDoc.java#L136-L162
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java
Validator.validateMatchRegex
public static <T extends CharSequence> T validateMatchRegex(String regex, T value, String errorMsg) throws ValidateException { if (false == isMactchRegex(regex, value)) { throw new ValidateException(errorMsg); } return value; }
java
public static <T extends CharSequence> T validateMatchRegex(String regex, T value, String errorMsg) throws ValidateException { if (false == isMactchRegex(regex, value)) { throw new ValidateException(errorMsg); } return value; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validateMatchRegex", "(", "String", "regex", ",", "T", "value", ",", "String", "errorMsg", ")", "throws", "ValidateException", "{", "if", "(", "false", "==", "isMactchRegex", "(", "regex", ",", "value", ")", ")", "{", "throw", "new", "ValidateException", "(", "errorMsg", ")", ";", "}", "return", "value", ";", "}" ]
通过正则表达式验证<br> 不符合正则抛出{@link ValidateException} 异常 @param <T> 字符串类型 @param regex 正则 @param value 值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常
[ "通过正则表达式验证<br", ">", "不符合正则抛出", "{", "@link", "ValidateException", "}", "异常" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L321-L326
Hygieia/Hygieia
collectors/misc/score/src/main/java/com/capitalone/dashboard/widget/GithubScmWidgetScore.java
GithubScmWidgetScore.getPercentCoverageForDays
private Double getPercentCoverageForDays(Iterable<Commit> commits, int days) { Set<String> dates = new HashSet<>(); for (Commit commit : commits) { dates.add(Constants.DAY_FORMAT.format(new Date(commit.getScmCommitTimestamp()))); } return (dates.size() / (double) days) * 100; }
java
private Double getPercentCoverageForDays(Iterable<Commit> commits, int days) { Set<String> dates = new HashSet<>(); for (Commit commit : commits) { dates.add(Constants.DAY_FORMAT.format(new Date(commit.getScmCommitTimestamp()))); } return (dates.size() / (double) days) * 100; }
[ "private", "Double", "getPercentCoverageForDays", "(", "Iterable", "<", "Commit", ">", "commits", ",", "int", "days", ")", "{", "Set", "<", "String", ">", "dates", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Commit", "commit", ":", "commits", ")", "{", "dates", ".", "add", "(", "Constants", ".", "DAY_FORMAT", ".", "format", "(", "new", "Date", "(", "commit", ".", "getScmCommitTimestamp", "(", ")", ")", ")", ")", ";", "}", "return", "(", "dates", ".", "size", "(", ")", "/", "(", "double", ")", "days", ")", "*", "100", ";", "}" ]
Calculate percentage of days with commits out of total days @param commits @param days @return percentage of days with commits
[ "Calculate", "percentage", "of", "days", "with", "commits", "out", "of", "total", "days" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/misc/score/src/main/java/com/capitalone/dashboard/widget/GithubScmWidgetScore.java#L164-L170
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/cpc/PreambleUtil.java
PreambleUtil.getHiFieldOffset
static long getHiFieldOffset(final Format format, final HiField hiField) { final int formatIdx = format.ordinal(); final int hiFieldIdx = hiField.ordinal(); final long fieldOffset = hiFieldOffset[formatIdx][hiFieldIdx] & 0xFF; //initially a byte if (fieldOffset == 0) { throw new SketchesStateException("Undefined preamble field given the Format: " + "Format: " + format.toString() + ", HiField: " + hiField.toString()); } return fieldOffset; }
java
static long getHiFieldOffset(final Format format, final HiField hiField) { final int formatIdx = format.ordinal(); final int hiFieldIdx = hiField.ordinal(); final long fieldOffset = hiFieldOffset[formatIdx][hiFieldIdx] & 0xFF; //initially a byte if (fieldOffset == 0) { throw new SketchesStateException("Undefined preamble field given the Format: " + "Format: " + format.toString() + ", HiField: " + hiField.toString()); } return fieldOffset; }
[ "static", "long", "getHiFieldOffset", "(", "final", "Format", "format", ",", "final", "HiField", "hiField", ")", "{", "final", "int", "formatIdx", "=", "format", ".", "ordinal", "(", ")", ";", "final", "int", "hiFieldIdx", "=", "hiField", ".", "ordinal", "(", ")", ";", "final", "long", "fieldOffset", "=", "hiFieldOffset", "[", "formatIdx", "]", "[", "hiFieldIdx", "]", "&", "0xFF", ";", "//initially a byte", "if", "(", "fieldOffset", "==", "0", ")", "{", "throw", "new", "SketchesStateException", "(", "\"Undefined preamble field given the Format: \"", "+", "\"Format: \"", "+", "format", ".", "toString", "(", ")", "+", "\", HiField: \"", "+", "hiField", ".", "toString", "(", ")", ")", ";", "}", "return", "fieldOffset", ";", "}" ]
Returns the defined byte offset from the start of the preamble given the <i>HiField</i> and the <i>Format</i>. Note this can not be used to obtain the stream offsets. @param format the desired <i>Format</i> @param hiField the desired preamble <i>HiField</i> after the first eight bytes. @return the defined byte offset from the start of the preamble for the given <i>HiField</i> and the <i>Format</i>.
[ "Returns", "the", "defined", "byte", "offset", "from", "the", "start", "of", "the", "preamble", "given", "the", "<i", ">", "HiField<", "/", "i", ">", "and", "the", "<i", ">", "Format<", "/", "i", ">", ".", "Note", "this", "can", "not", "be", "used", "to", "obtain", "the", "stream", "offsets", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/PreambleUtil.java#L275-L284
i-net-software/jlessc
src/com/inet/lib/less/FunctionExpression.java
FunctionExpression.getPercent
private double getPercent( int idx, double defaultValue, CssFormatter formatter ) { if( parameters.size() <= idx ) { return defaultValue; } return ColorUtils.getPercent( get( idx ), formatter ); }
java
private double getPercent( int idx, double defaultValue, CssFormatter formatter ) { if( parameters.size() <= idx ) { return defaultValue; } return ColorUtils.getPercent( get( idx ), formatter ); }
[ "private", "double", "getPercent", "(", "int", "idx", ",", "double", "defaultValue", ",", "CssFormatter", "formatter", ")", "{", "if", "(", "parameters", ".", "size", "(", ")", "<=", "idx", ")", "{", "return", "defaultValue", ";", "}", "return", "ColorUtils", ".", "getPercent", "(", "get", "(", "idx", ")", ",", "formatter", ")", ";", "}" ]
Get the idx parameter from the parameter list as percent (range 0 - 1). @param idx the index starting with 0 @param defaultValue the result if such a parameter idx does not exists. @param formatter current formatter @return the the percent value
[ "Get", "the", "idx", "parameter", "from", "the", "parameter", "list", "as", "percent", "(", "range", "0", "-", "1", ")", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/FunctionExpression.java#L963-L968
Whiley/WhileyCompiler
src/main/java/wyil/check/FlowTypeCheck.java
FlowTypeCheck.checkAssign
private Environment checkAssign(Stmt.Assign stmt, Environment environment, EnclosingScope scope) throws IOException { Tuple<LVal> lvals = stmt.getLeftHandSide(); Type[] types = new Type[lvals.size()]; for (int i = 0; i != lvals.size(); ++i) { types[i] = checkLVal(lvals.get(i), environment); } checkMultiExpressions(stmt.getRightHandSide(), environment, new Tuple<>(types)); return environment; }
java
private Environment checkAssign(Stmt.Assign stmt, Environment environment, EnclosingScope scope) throws IOException { Tuple<LVal> lvals = stmt.getLeftHandSide(); Type[] types = new Type[lvals.size()]; for (int i = 0; i != lvals.size(); ++i) { types[i] = checkLVal(lvals.get(i), environment); } checkMultiExpressions(stmt.getRightHandSide(), environment, new Tuple<>(types)); return environment; }
[ "private", "Environment", "checkAssign", "(", "Stmt", ".", "Assign", "stmt", ",", "Environment", "environment", ",", "EnclosingScope", "scope", ")", "throws", "IOException", "{", "Tuple", "<", "LVal", ">", "lvals", "=", "stmt", ".", "getLeftHandSide", "(", ")", ";", "Type", "[", "]", "types", "=", "new", "Type", "[", "lvals", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "lvals", ".", "size", "(", ")", ";", "++", "i", ")", "{", "types", "[", "i", "]", "=", "checkLVal", "(", "lvals", ".", "get", "(", "i", ")", ",", "environment", ")", ";", "}", "checkMultiExpressions", "(", "stmt", ".", "getRightHandSide", "(", ")", ",", "environment", ",", "new", "Tuple", "<>", "(", "types", ")", ")", ";", "return", "environment", ";", "}" ]
Type check an assignment statement. @param stmt Statement to type check @param environment Determines the type of all variables immediately going into this block @return
[ "Type", "check", "an", "assignment", "statement", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L441-L450
js-lib-com/commons
src/main/java/js/util/Files.java
Files.renameTo
public static void renameTo(File source, File destination) throws IOException { mkdirs(destination); // excerpt from File.renameTo API: // ... and it (n.b. File.renameTo) might not succeed if a file with the destination abstract pathname already exists // // so ensure destination does not exist destination.delete(); if(!source.renameTo(destination)) { throw new IOException(String.format("Fail to rename file |%s| to |%s|.", source, destination)); } }
java
public static void renameTo(File source, File destination) throws IOException { mkdirs(destination); // excerpt from File.renameTo API: // ... and it (n.b. File.renameTo) might not succeed if a file with the destination abstract pathname already exists // // so ensure destination does not exist destination.delete(); if(!source.renameTo(destination)) { throw new IOException(String.format("Fail to rename file |%s| to |%s|.", source, destination)); } }
[ "public", "static", "void", "renameTo", "(", "File", "source", ",", "File", "destination", ")", "throws", "IOException", "{", "mkdirs", "(", "destination", ")", ";", "// excerpt from File.renameTo API:\r", "// ... and it (n.b. File.renameTo) might not succeed if a file with the destination abstract pathname already exists\r", "//\r", "// so ensure destination does not exist\r", "destination", ".", "delete", "(", ")", ";", "if", "(", "!", "source", ".", "renameTo", "(", "destination", ")", ")", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Fail to rename file |%s| to |%s|.\"", ",", "source", ",", "destination", ")", ")", ";", "}", "}" ]
Thin wrapper for {@link File#renameTo(File)} throwing exception on fail. This method ensures destination file parent directories exist. If destination file already exist its content is silently overwritten. <p> Warning: if destination file exists, it is overwritten and its old content lost. @param source source file, @param destination destination file. @throws IOException if rename operation fails.
[ "Thin", "wrapper", "for", "{", "@link", "File#renameTo", "(", "File", ")", "}", "throwing", "exception", "on", "fail", ".", "This", "method", "ensures", "destination", "file", "parent", "directories", "exist", ".", "If", "destination", "file", "already", "exist", "its", "content", "is", "silently", "overwritten", ".", "<p", ">", "Warning", ":", "if", "destination", "file", "exists", "it", "is", "overwritten", "and", "its", "old", "content", "lost", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Files.java#L492-L505
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.addCustomPrebuiltDomainAsync
public Observable<List<UUID>> addCustomPrebuiltDomainAsync(UUID appId, String versionId, AddCustomPrebuiltDomainModelsOptionalParameter addCustomPrebuiltDomainOptionalParameter) { return addCustomPrebuiltDomainWithServiceResponseAsync(appId, versionId, addCustomPrebuiltDomainOptionalParameter).map(new Func1<ServiceResponse<List<UUID>>, List<UUID>>() { @Override public List<UUID> call(ServiceResponse<List<UUID>> response) { return response.body(); } }); }
java
public Observable<List<UUID>> addCustomPrebuiltDomainAsync(UUID appId, String versionId, AddCustomPrebuiltDomainModelsOptionalParameter addCustomPrebuiltDomainOptionalParameter) { return addCustomPrebuiltDomainWithServiceResponseAsync(appId, versionId, addCustomPrebuiltDomainOptionalParameter).map(new Func1<ServiceResponse<List<UUID>>, List<UUID>>() { @Override public List<UUID> call(ServiceResponse<List<UUID>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "UUID", ">", ">", "addCustomPrebuiltDomainAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "AddCustomPrebuiltDomainModelsOptionalParameter", "addCustomPrebuiltDomainOptionalParameter", ")", "{", "return", "addCustomPrebuiltDomainWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "addCustomPrebuiltDomainOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "UUID", ">", ">", ",", "List", "<", "UUID", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "UUID", ">", "call", "(", "ServiceResponse", "<", "List", "<", "UUID", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Adds a customizable prebuilt domain along with all of its models to this application. @param appId The application ID. @param versionId The version ID. @param addCustomPrebuiltDomainOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;UUID&gt; object
[ "Adds", "a", "customizable", "prebuilt", "domain", "along", "with", "all", "of", "its", "models", "to", "this", "application", "." ]
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#L5570-L5577
jbundle/webapp
upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java
UploadServlet.sendForm
public void sendForm(HttpServletRequest req, HttpServletResponse res, String strReceiveMessage, Properties properties) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.write("<html>" + RETURN + "<head>" + RETURN + "<title>" + this.getTitle() + "</title>" + RETURN + "</head>" + RETURN + "<body>" + RETURN + "<center><b>" + this.getTitle() + "</b></center><p />" + RETURN); String strServletPath = null; try { strServletPath = req.getRequestURI(); //Path(); } catch (Exception ex) { strServletPath = null; } if (strServletPath == null) strServletPath = "servlet/" + UploadServlet.class.getName(); // Never //strServletPath = "http://localhost/jbackup/servlet/com.tourgeek.jbackup.Servlet"; out.write(strReceiveMessage); // Status of previous upload out.write("<p /><form action=\"" + strServletPath + "\""); out.write(" method=\"post\"" + RETURN); out.write(" enctype=\"multipart/form-data\">" + RETURN); // TARGET=_top // out.write(" ACTION="http://www45.visto.com/?uid=219979&service=fileaccess&method=upload&nextpage=fa%3Dafter_upload.html&errorpage=fa_upload@.html&overwritepage=fa=upload_replace_dialog.html"> // out.write("What is your name? <INPUT TYPE=TEXT NAME=submitter> <BR>" + RETURN); String strFormHTML = this.getFormHTML(); if ((strFormHTML != null) && (strFormHTML.length() > 0)) out.write(strFormHTML); out.write("Which file to upload? <input type=\"file\" name=\"file\" />" + RETURN); this.writeAfterHTML(out, req, properties); out.write("<input type=\"submit\" value=\"upload\" />" + RETURN); out.write("</form></p>" + RETURN); out.write("</body>" + RETURN + "</html>" + RETURN); }
java
public void sendForm(HttpServletRequest req, HttpServletResponse res, String strReceiveMessage, Properties properties) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.write("<html>" + RETURN + "<head>" + RETURN + "<title>" + this.getTitle() + "</title>" + RETURN + "</head>" + RETURN + "<body>" + RETURN + "<center><b>" + this.getTitle() + "</b></center><p />" + RETURN); String strServletPath = null; try { strServletPath = req.getRequestURI(); //Path(); } catch (Exception ex) { strServletPath = null; } if (strServletPath == null) strServletPath = "servlet/" + UploadServlet.class.getName(); // Never //strServletPath = "http://localhost/jbackup/servlet/com.tourgeek.jbackup.Servlet"; out.write(strReceiveMessage); // Status of previous upload out.write("<p /><form action=\"" + strServletPath + "\""); out.write(" method=\"post\"" + RETURN); out.write(" enctype=\"multipart/form-data\">" + RETURN); // TARGET=_top // out.write(" ACTION="http://www45.visto.com/?uid=219979&service=fileaccess&method=upload&nextpage=fa%3Dafter_upload.html&errorpage=fa_upload@.html&overwritepage=fa=upload_replace_dialog.html"> // out.write("What is your name? <INPUT TYPE=TEXT NAME=submitter> <BR>" + RETURN); String strFormHTML = this.getFormHTML(); if ((strFormHTML != null) && (strFormHTML.length() > 0)) out.write(strFormHTML); out.write("Which file to upload? <input type=\"file\" name=\"file\" />" + RETURN); this.writeAfterHTML(out, req, properties); out.write("<input type=\"submit\" value=\"upload\" />" + RETURN); out.write("</form></p>" + RETURN); out.write("</body>" + RETURN + "</html>" + RETURN); }
[ "public", "void", "sendForm", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ",", "String", "strReceiveMessage", ",", "Properties", "properties", ")", "throws", "ServletException", ",", "IOException", "{", "res", ".", "setContentType", "(", "\"text/html\"", ")", ";", "PrintWriter", "out", "=", "res", ".", "getWriter", "(", ")", ";", "out", ".", "write", "(", "\"<html>\"", "+", "RETURN", "+", "\"<head>\"", "+", "RETURN", "+", "\"<title>\"", "+", "this", ".", "getTitle", "(", ")", "+", "\"</title>\"", "+", "RETURN", "+", "\"</head>\"", "+", "RETURN", "+", "\"<body>\"", "+", "RETURN", "+", "\"<center><b>\"", "+", "this", ".", "getTitle", "(", ")", "+", "\"</b></center><p />\"", "+", "RETURN", ")", ";", "String", "strServletPath", "=", "null", ";", "try", "{", "strServletPath", "=", "req", ".", "getRequestURI", "(", ")", ";", "//Path();", "}", "catch", "(", "Exception", "ex", ")", "{", "strServletPath", "=", "null", ";", "}", "if", "(", "strServletPath", "==", "null", ")", "strServletPath", "=", "\"servlet/\"", "+", "UploadServlet", ".", "class", ".", "getName", "(", ")", ";", "// Never", "//strServletPath = \"http://localhost/jbackup/servlet/com.tourgeek.jbackup.Servlet\";", "out", ".", "write", "(", "strReceiveMessage", ")", ";", "// Status of previous upload", "out", ".", "write", "(", "\"<p /><form action=\\\"\"", "+", "strServletPath", "+", "\"\\\"\"", ")", ";", "out", ".", "write", "(", "\" method=\\\"post\\\"\"", "+", "RETURN", ")", ";", "out", ".", "write", "(", "\" enctype=\\\"multipart/form-data\\\">\"", "+", "RETURN", ")", ";", "// TARGET=_top", "//\t\tout.write(\" ACTION=\"http://www45.visto.com/?uid=219979&service=fileaccess&method=upload&nextpage=fa%3Dafter_upload.html&errorpage=fa_upload@.html&overwritepage=fa=upload_replace_dialog.html\">", "//\t\tout.write(\"What is your name? <INPUT TYPE=TEXT NAME=submitter> <BR>\" + RETURN);", "String", "strFormHTML", "=", "this", ".", "getFormHTML", "(", ")", ";", "if", "(", "(", "strFormHTML", "!=", "null", ")", "&&", "(", "strFormHTML", ".", "length", "(", ")", ">", "0", ")", ")", "out", ".", "write", "(", "strFormHTML", ")", ";", "out", ".", "write", "(", "\"Which file to upload? <input type=\\\"file\\\" name=\\\"file\\\" />\"", "+", "RETURN", ")", ";", "this", ".", "writeAfterHTML", "(", "out", ",", "req", ",", "properties", ")", ";", "out", ".", "write", "(", "\"<input type=\\\"submit\\\" value=\\\"upload\\\" />\"", "+", "RETURN", ")", ";", "out", ".", "write", "(", "\"</form></p>\"", "+", "RETURN", ")", ";", "out", ".", "write", "(", "\"</body>\"", "+", "RETURN", "+", "\"</html>\"", "+", "RETURN", ")", ";", "}" ]
Process an HTML get or post. @exception ServletException From inherited class. @exception IOException From inherited class.
[ "Process", "an", "HTML", "get", "or", "post", "." ]
train
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java#L167-L207
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/MPXReader.java
MPXReader.populateProjectHeader
private void populateProjectHeader(Record record, ProjectProperties properties) throws MPXJException { properties.setProjectTitle(record.getString(0)); properties.setCompany(record.getString(1)); properties.setManager(record.getString(2)); properties.setDefaultCalendarName(record.getString(3)); properties.setStartDate(record.getDateTime(4)); properties.setFinishDate(record.getDateTime(5)); properties.setScheduleFrom(record.getScheduleFrom(6)); properties.setCurrentDate(record.getDateTime(7)); properties.setComments(record.getString(8)); properties.setCost(record.getCurrency(9)); properties.setBaselineCost(record.getCurrency(10)); properties.setActualCost(record.getCurrency(11)); properties.setWork(record.getDuration(12)); properties.setBaselineWork(record.getDuration(13)); properties.setActualWork(record.getDuration(14)); properties.setWork2(record.getPercentage(15)); properties.setDuration(record.getDuration(16)); properties.setBaselineDuration(record.getDuration(17)); properties.setActualDuration(record.getDuration(18)); properties.setPercentageComplete(record.getPercentage(19)); properties.setBaselineStart(record.getDateTime(20)); properties.setBaselineFinish(record.getDateTime(21)); properties.setActualStart(record.getDateTime(22)); properties.setActualFinish(record.getDateTime(23)); properties.setStartVariance(record.getDuration(24)); properties.setFinishVariance(record.getDuration(25)); properties.setSubject(record.getString(26)); properties.setAuthor(record.getString(27)); properties.setKeywords(record.getString(28)); }
java
private void populateProjectHeader(Record record, ProjectProperties properties) throws MPXJException { properties.setProjectTitle(record.getString(0)); properties.setCompany(record.getString(1)); properties.setManager(record.getString(2)); properties.setDefaultCalendarName(record.getString(3)); properties.setStartDate(record.getDateTime(4)); properties.setFinishDate(record.getDateTime(5)); properties.setScheduleFrom(record.getScheduleFrom(6)); properties.setCurrentDate(record.getDateTime(7)); properties.setComments(record.getString(8)); properties.setCost(record.getCurrency(9)); properties.setBaselineCost(record.getCurrency(10)); properties.setActualCost(record.getCurrency(11)); properties.setWork(record.getDuration(12)); properties.setBaselineWork(record.getDuration(13)); properties.setActualWork(record.getDuration(14)); properties.setWork2(record.getPercentage(15)); properties.setDuration(record.getDuration(16)); properties.setBaselineDuration(record.getDuration(17)); properties.setActualDuration(record.getDuration(18)); properties.setPercentageComplete(record.getPercentage(19)); properties.setBaselineStart(record.getDateTime(20)); properties.setBaselineFinish(record.getDateTime(21)); properties.setActualStart(record.getDateTime(22)); properties.setActualFinish(record.getDateTime(23)); properties.setStartVariance(record.getDuration(24)); properties.setFinishVariance(record.getDuration(25)); properties.setSubject(record.getString(26)); properties.setAuthor(record.getString(27)); properties.setKeywords(record.getString(28)); }
[ "private", "void", "populateProjectHeader", "(", "Record", "record", ",", "ProjectProperties", "properties", ")", "throws", "MPXJException", "{", "properties", ".", "setProjectTitle", "(", "record", ".", "getString", "(", "0", ")", ")", ";", "properties", ".", "setCompany", "(", "record", ".", "getString", "(", "1", ")", ")", ";", "properties", ".", "setManager", "(", "record", ".", "getString", "(", "2", ")", ")", ";", "properties", ".", "setDefaultCalendarName", "(", "record", ".", "getString", "(", "3", ")", ")", ";", "properties", ".", "setStartDate", "(", "record", ".", "getDateTime", "(", "4", ")", ")", ";", "properties", ".", "setFinishDate", "(", "record", ".", "getDateTime", "(", "5", ")", ")", ";", "properties", ".", "setScheduleFrom", "(", "record", ".", "getScheduleFrom", "(", "6", ")", ")", ";", "properties", ".", "setCurrentDate", "(", "record", ".", "getDateTime", "(", "7", ")", ")", ";", "properties", ".", "setComments", "(", "record", ".", "getString", "(", "8", ")", ")", ";", "properties", ".", "setCost", "(", "record", ".", "getCurrency", "(", "9", ")", ")", ";", "properties", ".", "setBaselineCost", "(", "record", ".", "getCurrency", "(", "10", ")", ")", ";", "properties", ".", "setActualCost", "(", "record", ".", "getCurrency", "(", "11", ")", ")", ";", "properties", ".", "setWork", "(", "record", ".", "getDuration", "(", "12", ")", ")", ";", "properties", ".", "setBaselineWork", "(", "record", ".", "getDuration", "(", "13", ")", ")", ";", "properties", ".", "setActualWork", "(", "record", ".", "getDuration", "(", "14", ")", ")", ";", "properties", ".", "setWork2", "(", "record", ".", "getPercentage", "(", "15", ")", ")", ";", "properties", ".", "setDuration", "(", "record", ".", "getDuration", "(", "16", ")", ")", ";", "properties", ".", "setBaselineDuration", "(", "record", ".", "getDuration", "(", "17", ")", ")", ";", "properties", ".", "setActualDuration", "(", "record", ".", "getDuration", "(", "18", ")", ")", ";", "properties", ".", "setPercentageComplete", "(", "record", ".", "getPercentage", "(", "19", ")", ")", ";", "properties", ".", "setBaselineStart", "(", "record", ".", "getDateTime", "(", "20", ")", ")", ";", "properties", ".", "setBaselineFinish", "(", "record", ".", "getDateTime", "(", "21", ")", ")", ";", "properties", ".", "setActualStart", "(", "record", ".", "getDateTime", "(", "22", ")", ")", ";", "properties", ".", "setActualFinish", "(", "record", ".", "getDateTime", "(", "23", ")", ")", ";", "properties", ".", "setStartVariance", "(", "record", ".", "getDuration", "(", "24", ")", ")", ";", "properties", ".", "setFinishVariance", "(", "record", ".", "getDuration", "(", "25", ")", ")", ";", "properties", ".", "setSubject", "(", "record", ".", "getString", "(", "26", ")", ")", ";", "properties", ".", "setAuthor", "(", "record", ".", "getString", "(", "27", ")", ")", ";", "properties", ".", "setKeywords", "(", "record", ".", "getString", "(", "28", ")", ")", ";", "}" ]
Populates the project header. @param record MPX record @param properties project properties @throws MPXJException
[ "Populates", "the", "project", "header", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXReader.java#L592-L623
op4j/op4j
src/main/java/org/op4j/functions/FnString.java
FnString.matchAndExtract
public static final Function<String,String> matchAndExtract(final String regex, final int group) { return new MatchAndExtract(regex, group); }
java
public static final Function<String,String> matchAndExtract(final String regex, final int group) { return new MatchAndExtract(regex, group); }
[ "public", "static", "final", "Function", "<", "String", ",", "String", ">", "matchAndExtract", "(", "final", "String", "regex", ",", "final", "int", "group", ")", "{", "return", "new", "MatchAndExtract", "(", "regex", ",", "group", ")", ";", "}" ]
<p> Matches the entire target String against the specified regular expression and extracts the specified group from it (as specified by <tt>java.util.regex.Matcher</tt>. </p> <p> Regular expressions must conform to the <tt>java.util.regex.Pattern</tt> format. </p> @param regex the regular expression to match against @param group the group number to be extracted @return the substring matching the group number
[ "<p", ">", "Matches", "the", "entire", "target", "String", "against", "the", "specified", "regular", "expression", "and", "extracts", "the", "specified", "group", "from", "it", "(", "as", "specified", "by", "<tt", ">", "java", ".", "util", ".", "regex", ".", "Matcher<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "Regular", "expressions", "must", "conform", "to", "the", "<tt", ">", "java", ".", "util", ".", "regex", ".", "Pattern<", "/", "tt", ">", "format", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/FnString.java#L1985-L1987
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/ImageHeaderReaderAbstract.java
ImageHeaderReaderAbstract.checkSkippedError
protected static void checkSkippedError(long skipped, int instead) throws IOException { if (skipped != instead) { throw new IOException(MESSAGE_SKIPPED + skipped + MESSAGE_BYTES_INSTEAD_OF + instead); } }
java
protected static void checkSkippedError(long skipped, int instead) throws IOException { if (skipped != instead) { throw new IOException(MESSAGE_SKIPPED + skipped + MESSAGE_BYTES_INSTEAD_OF + instead); } }
[ "protected", "static", "void", "checkSkippedError", "(", "long", "skipped", ",", "int", "instead", ")", "throws", "IOException", "{", "if", "(", "skipped", "!=", "instead", ")", "{", "throw", "new", "IOException", "(", "MESSAGE_SKIPPED", "+", "skipped", "+", "MESSAGE_BYTES_INSTEAD_OF", "+", "instead", ")", ";", "}", "}" ]
Skipped message error. @param skipped The skipped value. @param instead The instead value. @throws IOException If not skipped the right number of bytes.
[ "Skipped", "message", "error", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/ImageHeaderReaderAbstract.java#L88-L94
bsblabs/embed-for-vaadin
com.bsb.common.vaadin.embed/src/main/java/com/bsb/common/vaadin/embed/util/PropertiesHelper.java
PropertiesHelper.getIntProperty
public int getIntProperty(String key, int defaultValue) { final String value = properties.getProperty(key, String.valueOf(defaultValue)); return Integer.valueOf(value); }
java
public int getIntProperty(String key, int defaultValue) { final String value = properties.getProperty(key, String.valueOf(defaultValue)); return Integer.valueOf(value); }
[ "public", "int", "getIntProperty", "(", "String", "key", ",", "int", "defaultValue", ")", "{", "final", "String", "value", "=", "properties", ".", "getProperty", "(", "key", ",", "String", ".", "valueOf", "(", "defaultValue", ")", ")", ";", "return", "Integer", ".", "valueOf", "(", "value", ")", ";", "}" ]
Returns the int value for the specified property. If no such key is found, returns the <tt>defaultValue</tt> instead. @param key the key of the property @param defaultValue the default value if no such property is found @return an int value @see Properties#getProperty(String, String)
[ "Returns", "the", "int", "value", "for", "the", "specified", "property", ".", "If", "no", "such", "key", "is", "found", "returns", "the", "<tt", ">", "defaultValue<", "/", "tt", ">", "instead", "." ]
train
https://github.com/bsblabs/embed-for-vaadin/blob/f902e70def56ab54d287d2600f9c6eef9e66c225/com.bsb.common.vaadin.embed/src/main/java/com/bsb/common/vaadin/embed/util/PropertiesHelper.java#L65-L68
radkovo/jStyleParser
src/main/java/cz/vutbr/web/csskit/antlr4/CSSErrorStrategy.java
CSSErrorStrategy.consumeUntil
public void consumeUntil(Parser recognizer, IntervalSet follow, CSSLexerState.RecoveryMode mode, CSSLexerState ls) { CSSToken t; boolean finish; TokenStream input = recognizer.getInputStream(); do { Token next = input.LT(1); if (next instanceof CSSToken) { t = (CSSToken) input.LT(1); if (t.getType() == Token.EOF) { logger.trace("token eof "); break; } } else break; /* not a CSSToken, probably EOF */ // consume token if does not match finish = (t.getLexerState().isBalanced(mode, ls, t) && follow.contains(t.getType())); if (!finish) { logger.trace("Skipped: {}", t); input.consume(); } } while (!finish); }
java
public void consumeUntil(Parser recognizer, IntervalSet follow, CSSLexerState.RecoveryMode mode, CSSLexerState ls) { CSSToken t; boolean finish; TokenStream input = recognizer.getInputStream(); do { Token next = input.LT(1); if (next instanceof CSSToken) { t = (CSSToken) input.LT(1); if (t.getType() == Token.EOF) { logger.trace("token eof "); break; } } else break; /* not a CSSToken, probably EOF */ // consume token if does not match finish = (t.getLexerState().isBalanced(mode, ls, t) && follow.contains(t.getType())); if (!finish) { logger.trace("Skipped: {}", t); input.consume(); } } while (!finish); }
[ "public", "void", "consumeUntil", "(", "Parser", "recognizer", ",", "IntervalSet", "follow", ",", "CSSLexerState", ".", "RecoveryMode", "mode", ",", "CSSLexerState", "ls", ")", "{", "CSSToken", "t", ";", "boolean", "finish", ";", "TokenStream", "input", "=", "recognizer", ".", "getInputStream", "(", ")", ";", "do", "{", "Token", "next", "=", "input", ".", "LT", "(", "1", ")", ";", "if", "(", "next", "instanceof", "CSSToken", ")", "{", "t", "=", "(", "CSSToken", ")", "input", ".", "LT", "(", "1", ")", ";", "if", "(", "t", ".", "getType", "(", ")", "==", "Token", ".", "EOF", ")", "{", "logger", ".", "trace", "(", "\"token eof \"", ")", ";", "break", ";", "}", "}", "else", "break", ";", "/* not a CSSToken, probably EOF */", "// consume token if does not match", "finish", "=", "(", "t", ".", "getLexerState", "(", ")", ".", "isBalanced", "(", "mode", ",", "ls", ",", "t", ")", "&&", "follow", ".", "contains", "(", "t", ".", "getType", "(", ")", ")", ")", ";", "if", "(", "!", "finish", ")", "{", "logger", ".", "trace", "(", "\"Skipped: {}\"", ",", "t", ")", ";", "input", ".", "consume", "(", ")", ";", "}", "}", "while", "(", "!", "finish", ")", ";", "}" ]
Consumes token until lexer state is function-balanced and token from follow is matched.
[ "Consumes", "token", "until", "lexer", "state", "is", "function", "-", "balanced", "and", "token", "from", "follow", "is", "matched", "." ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/csskit/antlr4/CSSErrorStrategy.java#L104-L125
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/net/www/ParseUtil.java
ParseUtil.unescape
private static byte unescape(String s, int i) { return (byte) Integer.parseInt(s.substring(i+1,i+3),16); }
java
private static byte unescape(String s, int i) { return (byte) Integer.parseInt(s.substring(i+1,i+3),16); }
[ "private", "static", "byte", "unescape", "(", "String", "s", ",", "int", "i", ")", "{", "return", "(", "byte", ")", "Integer", ".", "parseInt", "(", "s", ".", "substring", "(", "i", "+", "1", ",", "i", "+", "3", ")", ",", "16", ")", ";", "}" ]
Un-escape and return the character at position i in string s.
[ "Un", "-", "escape", "and", "return", "the", "character", "at", "position", "i", "in", "string", "s", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/net/www/ParseUtil.java#L163-L165
Azure/azure-sdk-for-java
common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java
FluxUtil.byteBufStreamFromFile
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel, long offset, long length) { return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); }
java
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel, long offset, long length) { return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); }
[ "public", "static", "Flux", "<", "ByteBuf", ">", "byteBufStreamFromFile", "(", "AsynchronousFileChannel", "fileChannel", ",", "long", "offset", ",", "long", "length", ")", "{", "return", "byteBufStreamFromFile", "(", "fileChannel", ",", "DEFAULT_CHUNK_SIZE", ",", "offset", ",", "length", ")", ";", "}" ]
Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads part of a file. @param fileChannel The file channel. @param offset The offset in the file to begin reading. @param length The number of bytes to read from the file. @return the Flowable.
[ "Creates", "a", "{", "@link", "Flux", "}", "from", "an", "{", "@link", "AsynchronousFileChannel", "}", "which", "reads", "part", "of", "a", "file", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java#L177-L179
oehf/ipf-oht-atna
context/src/main/java/org/openhealthtools/ihe/atna/context/AbstractModuleConfig.java
AbstractModuleConfig.setOption
public synchronized void setOption(String key, String value) { if (key == null || value == null) { return; } config.put(key, value); }
java
public synchronized void setOption(String key, String value) { if (key == null || value == null) { return; } config.put(key, value); }
[ "public", "synchronized", "void", "setOption", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "key", "==", "null", "||", "value", "==", "null", ")", "{", "return", ";", "}", "config", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Set a value to the backed properties in this module config. @param key The key of the property to set @param value The value of the property to set
[ "Set", "a", "value", "to", "the", "backed", "properties", "in", "this", "module", "config", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/context/src/main/java/org/openhealthtools/ihe/atna/context/AbstractModuleConfig.java#L73-L79
softindex/datakernel
core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java
ByteBufQueue.drainTo
public int drainTo(@NotNull ByteBufQueue dest, int maxSize) { int s = maxSize; while (s != 0 && hasRemaining()) { ByteBuf buf = takeAtMost(s); dest.add(buf); s -= buf.readRemaining(); } return maxSize - s; }
java
public int drainTo(@NotNull ByteBufQueue dest, int maxSize) { int s = maxSize; while (s != 0 && hasRemaining()) { ByteBuf buf = takeAtMost(s); dest.add(buf); s -= buf.readRemaining(); } return maxSize - s; }
[ "public", "int", "drainTo", "(", "@", "NotNull", "ByteBufQueue", "dest", ",", "int", "maxSize", ")", "{", "int", "s", "=", "maxSize", ";", "while", "(", "s", "!=", "0", "&&", "hasRemaining", "(", ")", ")", "{", "ByteBuf", "buf", "=", "takeAtMost", "(", "s", ")", ";", "dest", ".", "add", "(", "buf", ")", ";", "s", "-=", "buf", ".", "readRemaining", "(", ")", ";", "}", "return", "maxSize", "-", "s", ";", "}" ]
Adds to ByteBufQueue {@code dest} {@code maxSize} bytes from this queue. If this queue doesn't contain enough bytes, adds all bytes from this queue. @param dest {@code ByteBufQueue} for draining @param maxSize number of bytes for adding @return number of added elements
[ "Adds", "to", "ByteBufQueue", "{", "@code", "dest", "}", "{", "@code", "maxSize", "}", "bytes", "from", "this", "queue", ".", "If", "this", "queue", "doesn", "t", "contain", "enough", "bytes", "adds", "all", "bytes", "from", "this", "queue", "." ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java#L623-L631
SUSE/salt-netapi-client
src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java
WebSocketEventStream.onOpen
@OnOpen public void onOpen(Session session, EndpointConfig config) throws IOException { this.session = session; session.getBasicRemote().sendText("websocket client ready"); }
java
@OnOpen public void onOpen(Session session, EndpointConfig config) throws IOException { this.session = session; session.getBasicRemote().sendText("websocket client ready"); }
[ "@", "OnOpen", "public", "void", "onOpen", "(", "Session", "session", ",", "EndpointConfig", "config", ")", "throws", "IOException", "{", "this", ".", "session", "=", "session", ";", "session", ".", "getBasicRemote", "(", ")", ".", "sendText", "(", "\"websocket client ready\"", ")", ";", "}" ]
On handshake completed, get the WebSocket Session and send a message to ServerEndpoint that WebSocket is ready. http://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#ws @param session The just started WebSocket {@link Session}. @param config The {@link EndpointConfig} containing the handshake informations. @throws IOException if something goes wrong sending message to the remote peer
[ "On", "handshake", "completed", "get", "the", "WebSocket", "Session", "and", "send", "a", "message", "to", "ServerEndpoint", "that", "WebSocket", "is", "ready", ".", "http", ":", "//", "docs", ".", "saltstack", ".", "com", "/", "en", "/", "latest", "/", "ref", "/", "netapi", "/", "all", "/", "salt", ".", "netapi", ".", "rest_cherrypy", ".", "html#ws" ]
train
https://github.com/SUSE/salt-netapi-client/blob/a0bdf643c8e34fa4def4b915366594c1491fdad5/src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java#L144-L148
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperStateHandleStore.java
ZooKeeperStateHandleStore.addAndLock
public RetrievableStateHandle<T> addAndLock( String pathInZooKeeper, T state) throws Exception { checkNotNull(pathInZooKeeper, "Path in ZooKeeper"); checkNotNull(state, "State"); final String path = normalizePath(pathInZooKeeper); RetrievableStateHandle<T> storeHandle = storage.store(state); boolean success = false; try { // Serialize the state handle. This writes the state to the backend. byte[] serializedStoreHandle = InstantiationUtil.serializeObject(storeHandle); // Write state handle (not the actual state) to ZooKeeper. This is expected to be // smaller than the state itself. This level of indirection makes sure that data in // ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but // the state can be larger. // Create the lock node in a transaction with the actual state node. That way we can prevent // race conditions with a concurrent delete operation. client.inTransaction().create().withMode(CreateMode.PERSISTENT).forPath(path, serializedStoreHandle) .and().create().withMode(CreateMode.EPHEMERAL).forPath(getLockPath(path)) .and().commit(); success = true; return storeHandle; } catch (KeeperException.NodeExistsException e) { throw new ConcurrentModificationException("ZooKeeper unexpectedly modified", e); } finally { if (!success) { // Cleanup the state handle if it was not written to ZooKeeper. if (storeHandle != null) { storeHandle.discardState(); } } } }
java
public RetrievableStateHandle<T> addAndLock( String pathInZooKeeper, T state) throws Exception { checkNotNull(pathInZooKeeper, "Path in ZooKeeper"); checkNotNull(state, "State"); final String path = normalizePath(pathInZooKeeper); RetrievableStateHandle<T> storeHandle = storage.store(state); boolean success = false; try { // Serialize the state handle. This writes the state to the backend. byte[] serializedStoreHandle = InstantiationUtil.serializeObject(storeHandle); // Write state handle (not the actual state) to ZooKeeper. This is expected to be // smaller than the state itself. This level of indirection makes sure that data in // ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but // the state can be larger. // Create the lock node in a transaction with the actual state node. That way we can prevent // race conditions with a concurrent delete operation. client.inTransaction().create().withMode(CreateMode.PERSISTENT).forPath(path, serializedStoreHandle) .and().create().withMode(CreateMode.EPHEMERAL).forPath(getLockPath(path)) .and().commit(); success = true; return storeHandle; } catch (KeeperException.NodeExistsException e) { throw new ConcurrentModificationException("ZooKeeper unexpectedly modified", e); } finally { if (!success) { // Cleanup the state handle if it was not written to ZooKeeper. if (storeHandle != null) { storeHandle.discardState(); } } } }
[ "public", "RetrievableStateHandle", "<", "T", ">", "addAndLock", "(", "String", "pathInZooKeeper", ",", "T", "state", ")", "throws", "Exception", "{", "checkNotNull", "(", "pathInZooKeeper", ",", "\"Path in ZooKeeper\"", ")", ";", "checkNotNull", "(", "state", ",", "\"State\"", ")", ";", "final", "String", "path", "=", "normalizePath", "(", "pathInZooKeeper", ")", ";", "RetrievableStateHandle", "<", "T", ">", "storeHandle", "=", "storage", ".", "store", "(", "state", ")", ";", "boolean", "success", "=", "false", ";", "try", "{", "// Serialize the state handle. This writes the state to the backend.", "byte", "[", "]", "serializedStoreHandle", "=", "InstantiationUtil", ".", "serializeObject", "(", "storeHandle", ")", ";", "// Write state handle (not the actual state) to ZooKeeper. This is expected to be", "// smaller than the state itself. This level of indirection makes sure that data in", "// ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but", "// the state can be larger.", "// Create the lock node in a transaction with the actual state node. That way we can prevent", "// race conditions with a concurrent delete operation.", "client", ".", "inTransaction", "(", ")", ".", "create", "(", ")", ".", "withMode", "(", "CreateMode", ".", "PERSISTENT", ")", ".", "forPath", "(", "path", ",", "serializedStoreHandle", ")", ".", "and", "(", ")", ".", "create", "(", ")", ".", "withMode", "(", "CreateMode", ".", "EPHEMERAL", ")", ".", "forPath", "(", "getLockPath", "(", "path", ")", ")", ".", "and", "(", ")", ".", "commit", "(", ")", ";", "success", "=", "true", ";", "return", "storeHandle", ";", "}", "catch", "(", "KeeperException", ".", "NodeExistsException", "e", ")", "{", "throw", "new", "ConcurrentModificationException", "(", "\"ZooKeeper unexpectedly modified\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "!", "success", ")", "{", "// Cleanup the state handle if it was not written to ZooKeeper.", "if", "(", "storeHandle", "!=", "null", ")", "{", "storeHandle", ".", "discardState", "(", ")", ";", "}", "}", "}", "}" ]
Creates a state handle, stores it in ZooKeeper and locks it. A locked node cannot be removed by another {@link ZooKeeperStateHandleStore} instance as long as this instance remains connected to ZooKeeper. <p><strong>Important</strong>: This will <em>not</em> store the actual state in ZooKeeper, but create a state handle and store it in ZooKeeper. This level of indirection makes sure that data in ZooKeeper is small. <p>The operation will fail if there is already an node under the given path @param pathInZooKeeper Destination path in ZooKeeper (expected to *not* exist yet) @param state State to be added @return The Created {@link RetrievableStateHandle}. @throws Exception If a ZooKeeper or state handle operation fails
[ "Creates", "a", "state", "handle", "stores", "it", "in", "ZooKeeper", "and", "locks", "it", ".", "A", "locked", "node", "cannot", "be", "removed", "by", "another", "{", "@link", "ZooKeeperStateHandleStore", "}", "instance", "as", "long", "as", "this", "instance", "remains", "connected", "to", "ZooKeeper", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperStateHandleStore.java#L129-L169
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/persister/impl/OgmEntityPersister.java
OgmEntityPersister.isReadRequired
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) { return valueGeneration != null && valueGeneration.getValueGenerator() == null && timingsMatch( valueGeneration.getGenerationTiming(), matchTiming ); }
java
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) { return valueGeneration != null && valueGeneration.getValueGenerator() == null && timingsMatch( valueGeneration.getGenerationTiming(), matchTiming ); }
[ "private", "boolean", "isReadRequired", "(", "ValueGeneration", "valueGeneration", ",", "GenerationTiming", "matchTiming", ")", "{", "return", "valueGeneration", "!=", "null", "&&", "valueGeneration", ".", "getValueGenerator", "(", ")", "==", "null", "&&", "timingsMatch", "(", "valueGeneration", ".", "getGenerationTiming", "(", ")", ",", "matchTiming", ")", ";", "}" ]
Whether the given value generation strategy requires to read the value from the database or not.
[ "Whether", "the", "given", "value", "generation", "strategy", "requires", "to", "read", "the", "value", "from", "the", "database", "or", "not", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/persister/impl/OgmEntityPersister.java#L1902-L1905
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.debugf
public void debugf(String format, Object param1) { if (isEnabled(Level.DEBUG)) { doLogf(Level.DEBUG, FQCN, format, new Object[] { param1 }, null); } }
java
public void debugf(String format, Object param1) { if (isEnabled(Level.DEBUG)) { doLogf(Level.DEBUG, FQCN, format, new Object[] { param1 }, null); } }
[ "public", "void", "debugf", "(", "String", "format", ",", "Object", "param1", ")", "{", "if", "(", "isEnabled", "(", "Level", ".", "DEBUG", ")", ")", "{", "doLogf", "(", "Level", ".", "DEBUG", ",", "FQCN", ",", "format", ",", "new", "Object", "[", "]", "{", "param1", "}", ",", "null", ")", ";", "}", "}" ]
Issue a formatted log message with a level of DEBUG. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param param1 the sole parameter
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "DEBUG", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L710-L714
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertSame
public static <T> T assertSame(T exp, T was, String message) { assertNotNull(exp, message); assertNotNull(was, message); assertTrue(exp == was, message); return was; }
java
public static <T> T assertSame(T exp, T was, String message) { assertNotNull(exp, message); assertNotNull(was, message); assertTrue(exp == was, message); return was; }
[ "public", "static", "<", "T", ">", "T", "assertSame", "(", "T", "exp", ",", "T", "was", ",", "String", "message", ")", "{", "assertNotNull", "(", "exp", ",", "message", ")", ";", "assertNotNull", "(", "was", ",", "message", ")", ";", "assertTrue", "(", "exp", "==", "was", ",", "message", ")", ";", "return", "was", ";", "}" ]
Throws an IllegalStateException when the given values are not equal.
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "values", "are", "not", "equal", "." ]
train
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L86-L91
amzn/ion-java
src/com/amazon/ion/Timestamp.java
Timestamp.addHour
public final Timestamp addHour(int amount) { long delta = (long) amount * 60 * 60 * 1000; return addMillisForPrecision(delta, Precision.MINUTE, false); }
java
public final Timestamp addHour(int amount) { long delta = (long) amount * 60 * 60 * 1000; return addMillisForPrecision(delta, Precision.MINUTE, false); }
[ "public", "final", "Timestamp", "addHour", "(", "int", "amount", ")", "{", "long", "delta", "=", "(", "long", ")", "amount", "*", "60", "*", "60", "*", "1000", ";", "return", "addMillisForPrecision", "(", "delta", ",", "Precision", ".", "MINUTE", ",", "false", ")", ";", "}" ]
Returns a timestamp relative to this one by the given number of hours. <p> This method always returns a Timestamp with at least MINUTE precision. For example, adding one hour to {@code 2011T} results in {@code 2011-01-01T01:00-00:00}. To receive a Timestamp that always maintains the same precision as the original, use {@link #adjustHour(int)}. @param amount a number of hours.
[ "Returns", "a", "timestamp", "relative", "to", "this", "one", "by", "the", "given", "number", "of", "hours", ".", "<p", ">", "This", "method", "always", "returns", "a", "Timestamp", "with", "at", "least", "MINUTE", "precision", ".", "For", "example", "adding", "one", "hour", "to", "{", "@code", "2011T", "}", "results", "in", "{", "@code", "2011", "-", "01", "-", "01T01", ":", "00", "-", "00", ":", "00", "}", ".", "To", "receive", "a", "Timestamp", "that", "always", "maintains", "the", "same", "precision", "as", "the", "original", "use", "{", "@link", "#adjustHour", "(", "int", ")", "}", "." ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/Timestamp.java#L2415-L2419
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSMessageImpl.java
JSMessageImpl.getAssembledContent
public DataSlice getAssembledContent() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "getAssembledContent"); DataSlice result = null; // lock the message - we don't want someone clearing the contents while we're doing this synchronized (getMessageLockArtefact()) { // If contents isn't null, the message is assembled so we can return something useful if (contents != null) { // We must mark the contents as shared now we're handing them out sharedContents = true; // d348294.1 result = new DataSlice(contents, messageOffset, length); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.exit(this, tc, "getAssembledContent", result); return result; }
java
public DataSlice getAssembledContent() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "getAssembledContent"); DataSlice result = null; // lock the message - we don't want someone clearing the contents while we're doing this synchronized (getMessageLockArtefact()) { // If contents isn't null, the message is assembled so we can return something useful if (contents != null) { // We must mark the contents as shared now we're handing them out sharedContents = true; // d348294.1 result = new DataSlice(contents, messageOffset, length); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.exit(this, tc, "getAssembledContent", result); return result; }
[ "public", "DataSlice", "getAssembledContent", "(", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "JmfTr", ".", "entry", "(", "this", ",", "tc", ",", "\"getAssembledContent\"", ")", ";", "DataSlice", "result", "=", "null", ";", "// lock the message - we don't want someone clearing the contents while we're doing this", "synchronized", "(", "getMessageLockArtefact", "(", ")", ")", "{", "// If contents isn't null, the message is assembled so we can return something useful", "if", "(", "contents", "!=", "null", ")", "{", "// We must mark the contents as shared now we're handing them out", "sharedContents", "=", "true", ";", "// d348294.1", "result", "=", "new", "DataSlice", "(", "contents", ",", "messageOffset", ",", "length", ")", ";", "}", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "JmfTr", ".", "exit", "(", "this", ",", "tc", ",", "\"getAssembledContent\"", ",", "result", ")", ";", "return", "result", ";", "}" ]
Locking: Requires the lock as it relies on, and may change, vital instance variable(s).
[ "Locking", ":", "Requires", "the", "lock", "as", "it", "relies", "on", "and", "may", "change", "vital", "instance", "variable", "(", "s", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSMessageImpl.java#L1564-L1583
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java
ThreadContextClassLoaderBuilder.buildAndSet
public ThreadContextClassLoaderHolder buildAndSet() { // Create the URLClassLoader from the supplied URLs final URL[] allURLs = new URL[urlList.size()]; urlList.toArray(allURLs); final URLClassLoader classLoader = new URLClassLoader(allURLs, originalClassLoader); // Assign the ThreadContext ClassLoader final Thread currentThread = Thread.currentThread(); currentThread.setContextClassLoader(classLoader); // Build the classpath argument StringBuilder builder = new StringBuilder(); try { for (URL current : Collections.list(classLoader.getResources(""))) { final String toAppend = getClassPathElement(current, encoding); if (toAppend != null) { builder.append(toAppend).append(File.pathSeparator); } } } catch (Exception e) { // Restore the original classloader to the active thread before failing. currentThread.setContextClassLoader(originalClassLoader); throw new IllegalStateException("Could not synthesize classpath from original classloader.", e); } final String classPathString = builder.length() > 0 ? builder.toString().substring(0, builder.length() - File.pathSeparator.length()) : ""; // All done. return new DefaultHolder(currentThread, this.originalClassLoader, classPathString); }
java
public ThreadContextClassLoaderHolder buildAndSet() { // Create the URLClassLoader from the supplied URLs final URL[] allURLs = new URL[urlList.size()]; urlList.toArray(allURLs); final URLClassLoader classLoader = new URLClassLoader(allURLs, originalClassLoader); // Assign the ThreadContext ClassLoader final Thread currentThread = Thread.currentThread(); currentThread.setContextClassLoader(classLoader); // Build the classpath argument StringBuilder builder = new StringBuilder(); try { for (URL current : Collections.list(classLoader.getResources(""))) { final String toAppend = getClassPathElement(current, encoding); if (toAppend != null) { builder.append(toAppend).append(File.pathSeparator); } } } catch (Exception e) { // Restore the original classloader to the active thread before failing. currentThread.setContextClassLoader(originalClassLoader); throw new IllegalStateException("Could not synthesize classpath from original classloader.", e); } final String classPathString = builder.length() > 0 ? builder.toString().substring(0, builder.length() - File.pathSeparator.length()) : ""; // All done. return new DefaultHolder(currentThread, this.originalClassLoader, classPathString); }
[ "public", "ThreadContextClassLoaderHolder", "buildAndSet", "(", ")", "{", "// Create the URLClassLoader from the supplied URLs", "final", "URL", "[", "]", "allURLs", "=", "new", "URL", "[", "urlList", ".", "size", "(", ")", "]", ";", "urlList", ".", "toArray", "(", "allURLs", ")", ";", "final", "URLClassLoader", "classLoader", "=", "new", "URLClassLoader", "(", "allURLs", ",", "originalClassLoader", ")", ";", "// Assign the ThreadContext ClassLoader", "final", "Thread", "currentThread", "=", "Thread", ".", "currentThread", "(", ")", ";", "currentThread", ".", "setContextClassLoader", "(", "classLoader", ")", ";", "// Build the classpath argument", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "for", "(", "URL", "current", ":", "Collections", ".", "list", "(", "classLoader", ".", "getResources", "(", "\"\"", ")", ")", ")", "{", "final", "String", "toAppend", "=", "getClassPathElement", "(", "current", ",", "encoding", ")", ";", "if", "(", "toAppend", "!=", "null", ")", "{", "builder", ".", "append", "(", "toAppend", ")", ".", "append", "(", "File", ".", "pathSeparator", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// Restore the original classloader to the active thread before failing.", "currentThread", ".", "setContextClassLoader", "(", "originalClassLoader", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Could not synthesize classpath from original classloader.\"", ",", "e", ")", ";", "}", "final", "String", "classPathString", "=", "builder", ".", "length", "(", ")", ">", "0", "?", "builder", ".", "toString", "(", ")", ".", "substring", "(", "0", ",", "builder", ".", "length", "(", ")", "-", "File", ".", "pathSeparator", ".", "length", "(", ")", ")", ":", "\"\"", ";", "// All done.", "return", "new", "DefaultHolder", "(", "currentThread", ",", "this", ".", "originalClassLoader", ",", "classPathString", ")", ";", "}" ]
<p>This method performs 2 things in order:</p> <ol> <li>Builds a ThreadContext ClassLoader from the URLs supplied to this Builder, and assigns the newly built ClassLoader to the current Thread.</li> <li>Stores the ThreadContextClassLoaderHolder for later restoration.</li> </ol> References to the original ThreadContextClassLoader and the currentThread are stored within the returned ThreadContextClassLoaderHolder, and can be restored by a call to {@code ThreadContextClassLoaderHolder.restoreClassLoaderAndReleaseThread()}. @return A fully set up ThreadContextClassLoaderHolder which is used to set the
[ "<p", ">", "This", "method", "performs", "2", "things", "in", "order", ":", "<", "/", "p", ">", "<ol", ">", "<li", ">", "Builds", "a", "ThreadContext", "ClassLoader", "from", "the", "URLs", "supplied", "to", "this", "Builder", "and", "assigns", "the", "newly", "built", "ClassLoader", "to", "the", "current", "Thread", ".", "<", "/", "li", ">", "<li", ">", "Stores", "the", "ThreadContextClassLoaderHolder", "for", "later", "restoration", ".", "<", "/", "li", ">", "<", "/", "ol", ">", "References", "to", "the", "original", "ThreadContextClassLoader", "and", "the", "currentThread", "are", "stored", "within", "the", "returned", "ThreadContextClassLoaderHolder", "and", "can", "be", "restored", "by", "a", "call", "to", "{", "@code", "ThreadContextClassLoaderHolder", ".", "restoreClassLoaderAndReleaseThread", "()", "}", "." ]
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java#L207-L240
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java
Strs.after
public static Betner after(String target, String separator) { return betn(target).after(separator); }
java
public static Betner after(String target, String separator) { return betn(target).after(separator); }
[ "public", "static", "Betner", "after", "(", "String", "target", ",", "String", "separator", ")", "{", "return", "betn", "(", "target", ")", ".", "after", "(", "separator", ")", ";", "}" ]
Returns a {@code String} between matcher that matches any character in the given left and ending @param target @param separator @return
[ "Returns", "a", "{", "@code", "String", "}", "between", "matcher", "that", "matches", "any", "character", "in", "the", "given", "left", "and", "ending" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java#L466-L468
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getUntaggedImagesWithServiceResponseAsync
public Observable<ServiceResponse<List<Image>>> getUntaggedImagesWithServiceResponseAsync(UUID projectId, GetUntaggedImagesOptionalParameter getUntaggedImagesOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final UUID iterationId = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.iterationId() : null; final String orderBy = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.orderBy() : null; final Integer take = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.take() : null; final Integer skip = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.skip() : null; return getUntaggedImagesWithServiceResponseAsync(projectId, iterationId, orderBy, take, skip); }
java
public Observable<ServiceResponse<List<Image>>> getUntaggedImagesWithServiceResponseAsync(UUID projectId, GetUntaggedImagesOptionalParameter getUntaggedImagesOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final UUID iterationId = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.iterationId() : null; final String orderBy = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.orderBy() : null; final Integer take = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.take() : null; final Integer skip = getUntaggedImagesOptionalParameter != null ? getUntaggedImagesOptionalParameter.skip() : null; return getUntaggedImagesWithServiceResponseAsync(projectId, iterationId, orderBy, take, skip); }
[ "public", "Observable", "<", "ServiceResponse", "<", "List", "<", "Image", ">", ">", ">", "getUntaggedImagesWithServiceResponseAsync", "(", "UUID", "projectId", ",", "GetUntaggedImagesOptionalParameter", "getUntaggedImagesOptionalParameter", ")", "{", "if", "(", "projectId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter projectId is required and cannot be null.\"", ")", ";", "}", "if", "(", "this", ".", "client", ".", "apiKey", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.apiKey() is required and cannot be null.\"", ")", ";", "}", "final", "UUID", "iterationId", "=", "getUntaggedImagesOptionalParameter", "!=", "null", "?", "getUntaggedImagesOptionalParameter", ".", "iterationId", "(", ")", ":", "null", ";", "final", "String", "orderBy", "=", "getUntaggedImagesOptionalParameter", "!=", "null", "?", "getUntaggedImagesOptionalParameter", ".", "orderBy", "(", ")", ":", "null", ";", "final", "Integer", "take", "=", "getUntaggedImagesOptionalParameter", "!=", "null", "?", "getUntaggedImagesOptionalParameter", ".", "take", "(", ")", ":", "null", ";", "final", "Integer", "skip", "=", "getUntaggedImagesOptionalParameter", "!=", "null", "?", "getUntaggedImagesOptionalParameter", ".", "skip", "(", ")", ":", "null", ";", "return", "getUntaggedImagesWithServiceResponseAsync", "(", "projectId", ",", "iterationId", ",", "orderBy", ",", "take", ",", "skip", ")", ";", "}" ]
Get untagged images for a given project iteration. This API supports batching and range selection. By default it will only return first 50 images matching images. Use the {take} and {skip} parameters to control how many images to return in a given batch. @param projectId The project id @param getUntaggedImagesOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;Image&gt; object
[ "Get", "untagged", "images", "for", "a", "given", "project", "iteration", ".", "This", "API", "supports", "batching", "and", "range", "selection", ".", "By", "default", "it", "will", "only", "return", "first", "50", "images", "matching", "images", ".", "Use", "the", "{", "take", "}", "and", "{", "skip", "}", "parameters", "to", "control", "how", "many", "images", "to", "return", "in", "a", "given", "batch", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L4833-L4846
op4j/op4j-jodatime
src/main/java/org/op4j/jodatime/functions/FnInterval.java
FnInterval.strFieldArrayToInterval
public static final Function<String[], Interval> strFieldArrayToInterval(String pattern, DateTimeZone dateTimeZone) { return new StringFieldArrayToInterval(pattern, dateTimeZone); }
java
public static final Function<String[], Interval> strFieldArrayToInterval(String pattern, DateTimeZone dateTimeZone) { return new StringFieldArrayToInterval(pattern, dateTimeZone); }
[ "public", "static", "final", "Function", "<", "String", "[", "]", ",", "Interval", ">", "strFieldArrayToInterval", "(", "String", "pattern", ",", "DateTimeZone", "dateTimeZone", ")", "{", "return", "new", "StringFieldArrayToInterval", "(", "pattern", ",", "dateTimeZone", ")", ";", "}" ]
<p> It converts the input {@link String} elements into an {@link Interval}. The target {@link String} elements represent the start and end of the {@link Interval}. </p> <p> The accepted input String[] are: </p> <ul> <li>year, month, day, year, month, day</li> <li>year, month, day, hour, minute, year, month, day, hour, minute</li> <li>year, month, day, hour, minute, second, year, month, day, hour, minute, second</li> <li>year, month, day, hour, minute, second, millisecond, year, month, day, hour, minute, second, millisecond</li> </ul> @param pattern string with the format of the input String @param dateTimeZone the the time zone ({@link DateTimeZone}) to be used @return the {@link Interval} created from the input and arguments
[ "<p", ">", "It", "converts", "the", "input", "{", "@link", "String", "}", "elements", "into", "an", "{", "@link", "Interval", "}", ".", "The", "target", "{", "@link", "String", "}", "elements", "represent", "the", "start", "and", "end", "of", "the", "{", "@link", "Interval", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j-jodatime/blob/26e5b8cda8553fb3b5a4a64b3109dbbf5df21194/src/main/java/org/op4j/jodatime/functions/FnInterval.java#L376-L378
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyDirectLinearTransform.java
HomographyDirectLinearTransform.addConics
protected int addConics(List<AssociatedPairConic> points , DMatrixRMaj A, int rows ) { if( exhaustiveConics ) { // adds an exhaustive set of linear conics for (int i = 0; i < points.size(); i++) { for (int j = i+1; j < points.size(); j++) { rows = addConicPairConstraints(points.get(i),points.get(j),A,rows); } } } else { // adds pairs and has linear time complexity for (int i = 1; i < points.size(); i++) { rows = addConicPairConstraints(points.get(i-1),points.get(i),A,rows); } int N = points.size(); rows = addConicPairConstraints(points.get(0),points.get(N-1),A,rows); } return rows; }
java
protected int addConics(List<AssociatedPairConic> points , DMatrixRMaj A, int rows ) { if( exhaustiveConics ) { // adds an exhaustive set of linear conics for (int i = 0; i < points.size(); i++) { for (int j = i+1; j < points.size(); j++) { rows = addConicPairConstraints(points.get(i),points.get(j),A,rows); } } } else { // adds pairs and has linear time complexity for (int i = 1; i < points.size(); i++) { rows = addConicPairConstraints(points.get(i-1),points.get(i),A,rows); } int N = points.size(); rows = addConicPairConstraints(points.get(0),points.get(N-1),A,rows); } return rows; }
[ "protected", "int", "addConics", "(", "List", "<", "AssociatedPairConic", ">", "points", ",", "DMatrixRMaj", "A", ",", "int", "rows", ")", "{", "if", "(", "exhaustiveConics", ")", "{", "// adds an exhaustive set of linear conics", "for", "(", "int", "i", "=", "0", ";", "i", "<", "points", ".", "size", "(", ")", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "i", "+", "1", ";", "j", "<", "points", ".", "size", "(", ")", ";", "j", "++", ")", "{", "rows", "=", "addConicPairConstraints", "(", "points", ".", "get", "(", "i", ")", ",", "points", ".", "get", "(", "j", ")", ",", "A", ",", "rows", ")", ";", "}", "}", "}", "else", "{", "// adds pairs and has linear time complexity", "for", "(", "int", "i", "=", "1", ";", "i", "<", "points", ".", "size", "(", ")", ";", "i", "++", ")", "{", "rows", "=", "addConicPairConstraints", "(", "points", ".", "get", "(", "i", "-", "1", ")", ",", "points", ".", "get", "(", "i", ")", ",", "A", ",", "rows", ")", ";", "}", "int", "N", "=", "points", ".", "size", "(", ")", ";", "rows", "=", "addConicPairConstraints", "(", "points", ".", "get", "(", "0", ")", ",", "points", ".", "get", "(", "N", "-", "1", ")", ",", "A", ",", "rows", ")", ";", "}", "return", "rows", ";", "}" ]
<p>Adds the 9x9 matrix constraint for each pair of conics. To avoid O(N^2) growth the default option only adds O(N) pairs. if only conics are used then a minimum of 3 is required. See [2].</p> inv(C[1]')*(C[2]')*H - H*invC[1]*C[2] == 0 Note: x' = H*x. C' is conic from the same view as x' and C from x. It can be shown that C = H^T*C'*H
[ "<p", ">", "Adds", "the", "9x9", "matrix", "constraint", "for", "each", "pair", "of", "conics", ".", "To", "avoid", "O", "(", "N^2", ")", "growth", "the", "default", "option", "only", "adds", "O", "(", "N", ")", "pairs", ".", "if", "only", "conics", "are", "used", "then", "a", "minimum", "of", "3", "is", "required", ".", "See", "[", "2", "]", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyDirectLinearTransform.java#L310-L329
threerings/gwt-utils
src/main/java/com/threerings/gwt/util/ServiceBackedDataModel.java
ServiceBackedDataModel.callFetchService
protected void callFetchService (PagedRequest request, AsyncCallback<R> callback) { callFetchService(request.offset, request.count, request.needCount, callback); }
java
protected void callFetchService (PagedRequest request, AsyncCallback<R> callback) { callFetchService(request.offset, request.count, request.needCount, callback); }
[ "protected", "void", "callFetchService", "(", "PagedRequest", "request", ",", "AsyncCallback", "<", "R", ">", "callback", ")", "{", "callFetchService", "(", "request", ".", "offset", ",", "request", ".", "count", ",", "request", ".", "needCount", ",", "callback", ")", ";", "}" ]
Calls the service to obtain data. Implementations should make a service call using the callback provided. If needCount is set, the implementation should also request the total number of items from the server (this is normally done in the same call that requests a page but may be optional for performance reasons). By default, this calls {@link #callFetchService(int, int, boolean, AsyncCallback)} method with the {@code requests}'s members. NOTE: subclasses must override one of the two callFetchService methods
[ "Calls", "the", "service", "to", "obtain", "data", ".", "Implementations", "should", "make", "a", "service", "call", "using", "the", "callback", "provided", ".", "If", "needCount", "is", "set", "the", "implementation", "should", "also", "request", "the", "total", "number", "of", "items", "from", "the", "server", "(", "this", "is", "normally", "done", "in", "the", "same", "call", "that", "requests", "a", "page", "but", "may", "be", "optional", "for", "performance", "reasons", ")", ".", "By", "default", "this", "calls", "{" ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/util/ServiceBackedDataModel.java#L154-L157
VoltDB/voltdb
third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java
ZooKeeper.getData
public void getData(final String path, Watcher watcher, DataCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); // the watch contains the un-chroot path WatchRegistration wcb = null; if (watcher != null) { wcb = new DataWatchRegistration(watcher, clientPath); } final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.getData); GetDataRequest request = new GetDataRequest(); request.setPath(serverPath); request.setWatch(watcher != null); GetDataResponse response = new GetDataResponse(); cnxn.queuePacket(h, new ReplyHeader(), request, response, cb, clientPath, serverPath, ctx, wcb); }
java
public void getData(final String path, Watcher watcher, DataCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); // the watch contains the un-chroot path WatchRegistration wcb = null; if (watcher != null) { wcb = new DataWatchRegistration(watcher, clientPath); } final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.getData); GetDataRequest request = new GetDataRequest(); request.setPath(serverPath); request.setWatch(watcher != null); GetDataResponse response = new GetDataResponse(); cnxn.queuePacket(h, new ReplyHeader(), request, response, cb, clientPath, serverPath, ctx, wcb); }
[ "public", "void", "getData", "(", "final", "String", "path", ",", "Watcher", "watcher", ",", "DataCallback", "cb", ",", "Object", "ctx", ")", "{", "verbotenThreadCheck", "(", ")", ";", "final", "String", "clientPath", "=", "path", ";", "PathUtils", ".", "validatePath", "(", "clientPath", ")", ";", "// the watch contains the un-chroot path", "WatchRegistration", "wcb", "=", "null", ";", "if", "(", "watcher", "!=", "null", ")", "{", "wcb", "=", "new", "DataWatchRegistration", "(", "watcher", ",", "clientPath", ")", ";", "}", "final", "String", "serverPath", "=", "prependChroot", "(", "clientPath", ")", ";", "RequestHeader", "h", "=", "new", "RequestHeader", "(", ")", ";", "h", ".", "setType", "(", "ZooDefs", ".", "OpCode", ".", "getData", ")", ";", "GetDataRequest", "request", "=", "new", "GetDataRequest", "(", ")", ";", "request", ".", "setPath", "(", "serverPath", ")", ";", "request", ".", "setWatch", "(", "watcher", "!=", "null", ")", ";", "GetDataResponse", "response", "=", "new", "GetDataResponse", "(", ")", ";", "cnxn", ".", "queuePacket", "(", "h", ",", "new", "ReplyHeader", "(", ")", ",", "request", ",", "response", ",", "cb", ",", "clientPath", ",", "serverPath", ",", "ctx", ",", "wcb", ")", ";", "}" ]
The Asynchronous version of getData. The request doesn't actually until the asynchronous callback is called. @see #getData(String, Watcher, Stat)
[ "The", "Asynchronous", "version", "of", "getData", ".", "The", "request", "doesn", "t", "actually", "until", "the", "asynchronous", "callback", "is", "called", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1009-L1031
Netflix/conductor
common/src/main/java/com/netflix/conductor/common/utils/RetryUtil.java
RetryUtil.retryOnException
@SuppressWarnings("Guava") public T retryOnException(Supplier<T> supplierCommand, Predicate<Throwable> throwablePredicate, Predicate<T> resultRetryPredicate, int retryCount, String shortDescription, String operationName) throws RuntimeException { Retryer<T> retryer = RetryerBuilder.<T>newBuilder() .retryIfException(Optional.ofNullable(throwablePredicate).orElse(exception -> true)) .retryIfResult(Optional.ofNullable(resultRetryPredicate).orElse(result -> false)) .withWaitStrategy(WaitStrategies.join( WaitStrategies.exponentialWait(1000, 90, TimeUnit.SECONDS), WaitStrategies.randomWait(100, TimeUnit.MILLISECONDS, 500, TimeUnit.MILLISECONDS) )) .withStopStrategy(StopStrategies.stopAfterAttempt(retryCount)) .withBlockStrategy(BlockStrategies.threadSleepStrategy()) .withRetryListener(new RetryListener() { @Override public <V> void onRetry(Attempt<V> attempt) { logger.debug("Attempt # {}, {} millis since first attempt. Operation: {}, description:{}", attempt.getAttemptNumber(), attempt.getDelaySinceFirstAttempt(), operationName, shortDescription); internalNumberOfRetries.incrementAndGet(); } }) .build(); try { return retryer.call(supplierCommand::get); } catch (ExecutionException executionException) { String errorMessage = String.format("Operation '%s:%s' failed for the %d time in RetryUtil", operationName, shortDescription, internalNumberOfRetries.get()); logger.debug(errorMessage); throw new RuntimeException(errorMessage, executionException.getCause()); } catch (RetryException retryException) { String errorMessage = String.format("Operation '%s:%s' failed after retrying %d times, retry limit %d", operationName, shortDescription, internalNumberOfRetries.get(), 3); logger.debug(errorMessage, retryException.getLastFailedAttempt().getExceptionCause()); throw new RuntimeException(errorMessage, retryException.getLastFailedAttempt().getExceptionCause()); } }
java
@SuppressWarnings("Guava") public T retryOnException(Supplier<T> supplierCommand, Predicate<Throwable> throwablePredicate, Predicate<T> resultRetryPredicate, int retryCount, String shortDescription, String operationName) throws RuntimeException { Retryer<T> retryer = RetryerBuilder.<T>newBuilder() .retryIfException(Optional.ofNullable(throwablePredicate).orElse(exception -> true)) .retryIfResult(Optional.ofNullable(resultRetryPredicate).orElse(result -> false)) .withWaitStrategy(WaitStrategies.join( WaitStrategies.exponentialWait(1000, 90, TimeUnit.SECONDS), WaitStrategies.randomWait(100, TimeUnit.MILLISECONDS, 500, TimeUnit.MILLISECONDS) )) .withStopStrategy(StopStrategies.stopAfterAttempt(retryCount)) .withBlockStrategy(BlockStrategies.threadSleepStrategy()) .withRetryListener(new RetryListener() { @Override public <V> void onRetry(Attempt<V> attempt) { logger.debug("Attempt # {}, {} millis since first attempt. Operation: {}, description:{}", attempt.getAttemptNumber(), attempt.getDelaySinceFirstAttempt(), operationName, shortDescription); internalNumberOfRetries.incrementAndGet(); } }) .build(); try { return retryer.call(supplierCommand::get); } catch (ExecutionException executionException) { String errorMessage = String.format("Operation '%s:%s' failed for the %d time in RetryUtil", operationName, shortDescription, internalNumberOfRetries.get()); logger.debug(errorMessage); throw new RuntimeException(errorMessage, executionException.getCause()); } catch (RetryException retryException) { String errorMessage = String.format("Operation '%s:%s' failed after retrying %d times, retry limit %d", operationName, shortDescription, internalNumberOfRetries.get(), 3); logger.debug(errorMessage, retryException.getLastFailedAttempt().getExceptionCause()); throw new RuntimeException(errorMessage, retryException.getLastFailedAttempt().getExceptionCause()); } }
[ "@", "SuppressWarnings", "(", "\"Guava\"", ")", "public", "T", "retryOnException", "(", "Supplier", "<", "T", ">", "supplierCommand", ",", "Predicate", "<", "Throwable", ">", "throwablePredicate", ",", "Predicate", "<", "T", ">", "resultRetryPredicate", ",", "int", "retryCount", ",", "String", "shortDescription", ",", "String", "operationName", ")", "throws", "RuntimeException", "{", "Retryer", "<", "T", ">", "retryer", "=", "RetryerBuilder", ".", "<", "T", ">", "newBuilder", "(", ")", ".", "retryIfException", "(", "Optional", ".", "ofNullable", "(", "throwablePredicate", ")", ".", "orElse", "(", "exception", "->", "true", ")", ")", ".", "retryIfResult", "(", "Optional", ".", "ofNullable", "(", "resultRetryPredicate", ")", ".", "orElse", "(", "result", "->", "false", ")", ")", ".", "withWaitStrategy", "(", "WaitStrategies", ".", "join", "(", "WaitStrategies", ".", "exponentialWait", "(", "1000", ",", "90", ",", "TimeUnit", ".", "SECONDS", ")", ",", "WaitStrategies", ".", "randomWait", "(", "100", ",", "TimeUnit", ".", "MILLISECONDS", ",", "500", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", ")", ".", "withStopStrategy", "(", "StopStrategies", ".", "stopAfterAttempt", "(", "retryCount", ")", ")", ".", "withBlockStrategy", "(", "BlockStrategies", ".", "threadSleepStrategy", "(", ")", ")", ".", "withRetryListener", "(", "new", "RetryListener", "(", ")", "{", "@", "Override", "public", "<", "V", ">", "void", "onRetry", "(", "Attempt", "<", "V", ">", "attempt", ")", "{", "logger", ".", "debug", "(", "\"Attempt # {}, {} millis since first attempt. Operation: {}, description:{}\"", ",", "attempt", ".", "getAttemptNumber", "(", ")", ",", "attempt", ".", "getDelaySinceFirstAttempt", "(", ")", ",", "operationName", ",", "shortDescription", ")", ";", "internalNumberOfRetries", ".", "incrementAndGet", "(", ")", ";", "}", "}", ")", ".", "build", "(", ")", ";", "try", "{", "return", "retryer", ".", "call", "(", "supplierCommand", "::", "get", ")", ";", "}", "catch", "(", "ExecutionException", "executionException", ")", "{", "String", "errorMessage", "=", "String", ".", "format", "(", "\"Operation '%s:%s' failed for the %d time in RetryUtil\"", ",", "operationName", ",", "shortDescription", ",", "internalNumberOfRetries", ".", "get", "(", ")", ")", ";", "logger", ".", "debug", "(", "errorMessage", ")", ";", "throw", "new", "RuntimeException", "(", "errorMessage", ",", "executionException", ".", "getCause", "(", ")", ")", ";", "}", "catch", "(", "RetryException", "retryException", ")", "{", "String", "errorMessage", "=", "String", ".", "format", "(", "\"Operation '%s:%s' failed after retrying %d times, retry limit %d\"", ",", "operationName", ",", "shortDescription", ",", "internalNumberOfRetries", ".", "get", "(", ")", ",", "3", ")", ";", "logger", ".", "debug", "(", "errorMessage", ",", "retryException", ".", "getLastFailedAttempt", "(", ")", ".", "getExceptionCause", "(", ")", ")", ";", "throw", "new", "RuntimeException", "(", "errorMessage", ",", "retryException", ".", "getLastFailedAttempt", "(", ")", ".", "getExceptionCause", "(", ")", ")", ";", "}", "}" ]
A helper method which has the ability to execute a flaky supplier function and retry in case of failures. @param supplierCommand: Any function that is flaky and needs multiple retries. @param throwablePredicate: A Guava {@link Predicate} housing the exceptional criteria to perform informed filtering before retrying. @param resultRetryPredicate: a predicate to be evaluated for a valid condition of the expected result @param retryCount: Number of times the function is to be retried before failure @param shortDescription: A short description of the function that will be used in logging and error propagation. The intention of this description is to provide context for Operability. @param operationName: The name of the function for traceability in logs @return an instance of return type of the supplierCommand @throws RuntimeException in case of failed attempts to get T, which needs to be returned by the supplierCommand. The instance of the returned exception has: <ul> <li>A message with shortDescription and operationName with the number of retries made</li> <li>And a reference to the original exception generated during the last {@link Attempt} of the retry</li> </ul>
[ "A", "helper", "method", "which", "has", "the", "ability", "to", "execute", "a", "flaky", "supplier", "function", "and", "retry", "in", "case", "of", "failures", "." ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/common/src/main/java/com/netflix/conductor/common/utils/RetryUtil.java#L87-L126
anotheria/moskito
moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java
HttpHelper.areSame
private static boolean areSame(Credentials c1, Credentials c2) { if (c1 == null) { return c2 == null; } else { return StringUtils.equals(c1.getUserPrincipal().getName(), c1.getUserPrincipal().getName()) && StringUtils.equals(c1.getPassword(), c1.getPassword()); } }
java
private static boolean areSame(Credentials c1, Credentials c2) { if (c1 == null) { return c2 == null; } else { return StringUtils.equals(c1.getUserPrincipal().getName(), c1.getUserPrincipal().getName()) && StringUtils.equals(c1.getPassword(), c1.getPassword()); } }
[ "private", "static", "boolean", "areSame", "(", "Credentials", "c1", ",", "Credentials", "c2", ")", "{", "if", "(", "c1", "==", "null", ")", "{", "return", "c2", "==", "null", ";", "}", "else", "{", "return", "StringUtils", ".", "equals", "(", "c1", ".", "getUserPrincipal", "(", ")", ".", "getName", "(", ")", ",", "c1", ".", "getUserPrincipal", "(", ")", ".", "getName", "(", ")", ")", "&&", "StringUtils", ".", "equals", "(", "c1", ".", "getPassword", "(", ")", ",", "c1", ".", "getPassword", "(", ")", ")", ";", "}", "}" ]
Compare two instances of Credentials. @param c1 instance of Credentials @param c2 another instance of Credentials @return comparison result. {@code true} if both are null or contain same user/password pairs, false otherwise.
[ "Compare", "two", "instances", "of", "Credentials", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java#L114-L121
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxFile.java
BoxFile.createFromIdAndName
public static BoxFile createFromIdAndName(String fileId, String name) { JsonObject object = new JsonObject(); object.add(BoxItem.FIELD_ID, fileId); object.add(BoxItem.FIELD_TYPE, BoxFile.TYPE); if (!TextUtils.isEmpty(name)) { object.add(BoxItem.FIELD_NAME, name); } return new BoxFile(object); }
java
public static BoxFile createFromIdAndName(String fileId, String name) { JsonObject object = new JsonObject(); object.add(BoxItem.FIELD_ID, fileId); object.add(BoxItem.FIELD_TYPE, BoxFile.TYPE); if (!TextUtils.isEmpty(name)) { object.add(BoxItem.FIELD_NAME, name); } return new BoxFile(object); }
[ "public", "static", "BoxFile", "createFromIdAndName", "(", "String", "fileId", ",", "String", "name", ")", "{", "JsonObject", "object", "=", "new", "JsonObject", "(", ")", ";", "object", ".", "add", "(", "BoxItem", ".", "FIELD_ID", ",", "fileId", ")", ";", "object", ".", "add", "(", "BoxItem", ".", "FIELD_TYPE", ",", "BoxFile", ".", "TYPE", ")", ";", "if", "(", "!", "TextUtils", ".", "isEmpty", "(", "name", ")", ")", "{", "object", ".", "add", "(", "BoxItem", ".", "FIELD_NAME", ",", "name", ")", ";", "}", "return", "new", "BoxFile", "(", "object", ")", ";", "}" ]
A convenience method to create an empty file with just the id and type fields set. This allows the ability to interact with the content sdk in a more descriptive and type safe manner @param fileId the id of file to create @param name the name of the file to create @return an empty BoxFile object that only contains id and type information
[ "A", "convenience", "method", "to", "create", "an", "empty", "file", "with", "just", "the", "id", "and", "type", "fields", "set", ".", "This", "allows", "the", "ability", "to", "interact", "with", "the", "content", "sdk", "in", "a", "more", "descriptive", "and", "type", "safe", "manner" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxFile.java#L103-L111
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java
ULocale.parseTagString
private static int parseTagString(String localeID, String tags[]) { LocaleIDParser parser = new LocaleIDParser(localeID); String lang = parser.getLanguage(); String script = parser.getScript(); String region = parser.getCountry(); if (isEmptyString(lang)) { tags[0] = UNDEFINED_LANGUAGE; } else { tags[0] = lang; } if (script.equals(UNDEFINED_SCRIPT)) { tags[1] = ""; } else { tags[1] = script; } if (region.equals(UNDEFINED_REGION)) { tags[2] = ""; } else { tags[2] = region; } /* * Search for the variant. If there is one, then return the index of * the preceeding separator. * If there's no variant, search for the keyword delimiter, * and return its index. Otherwise, return the length of the * string. * * $TOTO(dbertoni) we need to take into account that we might * find a part of the language as the variant, since it can * can have a variant portion that is long enough to contain * the same characters as the variant. */ String variant = parser.getVariant(); if (!isEmptyString(variant)){ int index = localeID.indexOf(variant); return index > 0 ? index - 1 : index; } else { int index = localeID.indexOf('@'); return index == -1 ? localeID.length() : index; } }
java
private static int parseTagString(String localeID, String tags[]) { LocaleIDParser parser = new LocaleIDParser(localeID); String lang = parser.getLanguage(); String script = parser.getScript(); String region = parser.getCountry(); if (isEmptyString(lang)) { tags[0] = UNDEFINED_LANGUAGE; } else { tags[0] = lang; } if (script.equals(UNDEFINED_SCRIPT)) { tags[1] = ""; } else { tags[1] = script; } if (region.equals(UNDEFINED_REGION)) { tags[2] = ""; } else { tags[2] = region; } /* * Search for the variant. If there is one, then return the index of * the preceeding separator. * If there's no variant, search for the keyword delimiter, * and return its index. Otherwise, return the length of the * string. * * $TOTO(dbertoni) we need to take into account that we might * find a part of the language as the variant, since it can * can have a variant portion that is long enough to contain * the same characters as the variant. */ String variant = parser.getVariant(); if (!isEmptyString(variant)){ int index = localeID.indexOf(variant); return index > 0 ? index - 1 : index; } else { int index = localeID.indexOf('@'); return index == -1 ? localeID.length() : index; } }
[ "private", "static", "int", "parseTagString", "(", "String", "localeID", ",", "String", "tags", "[", "]", ")", "{", "LocaleIDParser", "parser", "=", "new", "LocaleIDParser", "(", "localeID", ")", ";", "String", "lang", "=", "parser", ".", "getLanguage", "(", ")", ";", "String", "script", "=", "parser", ".", "getScript", "(", ")", ";", "String", "region", "=", "parser", ".", "getCountry", "(", ")", ";", "if", "(", "isEmptyString", "(", "lang", ")", ")", "{", "tags", "[", "0", "]", "=", "UNDEFINED_LANGUAGE", ";", "}", "else", "{", "tags", "[", "0", "]", "=", "lang", ";", "}", "if", "(", "script", ".", "equals", "(", "UNDEFINED_SCRIPT", ")", ")", "{", "tags", "[", "1", "]", "=", "\"\"", ";", "}", "else", "{", "tags", "[", "1", "]", "=", "script", ";", "}", "if", "(", "region", ".", "equals", "(", "UNDEFINED_REGION", ")", ")", "{", "tags", "[", "2", "]", "=", "\"\"", ";", "}", "else", "{", "tags", "[", "2", "]", "=", "region", ";", "}", "/*\n * Search for the variant. If there is one, then return the index of\n * the preceeding separator.\n * If there's no variant, search for the keyword delimiter,\n * and return its index. Otherwise, return the length of the\n * string.\n *\n * $TOTO(dbertoni) we need to take into account that we might\n * find a part of the language as the variant, since it can\n * can have a variant portion that is long enough to contain\n * the same characters as the variant.\n */", "String", "variant", "=", "parser", ".", "getVariant", "(", ")", ";", "if", "(", "!", "isEmptyString", "(", "variant", ")", ")", "{", "int", "index", "=", "localeID", ".", "indexOf", "(", "variant", ")", ";", "return", "index", ">", "0", "?", "index", "-", "1", ":", "index", ";", "}", "else", "{", "int", "index", "=", "localeID", ".", "indexOf", "(", "'", "'", ")", ";", "return", "index", "==", "-", "1", "?", "localeID", ".", "length", "(", ")", ":", "index", ";", "}", "}" ]
Parse the language, script, and region subtags from a tag string, and return the results. This function does not return the canonical strings for the unknown script and region. @param localeID The locale ID to parse. @param tags An array of three String references to return the subtag strings. @return The number of chars of the localeID parameter consumed.
[ "Parse", "the", "language", "script", "and", "region", "subtags", "from", "a", "tag", "string", "and", "return", "the", "results", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L2779-L2833
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamThrottler.java
StreamThrottler.doThrottleInputStream
@Builder(builderMethodName = "throttleInputStream", builderClassName = "InputStreamThrottler") private ThrottledInputStream doThrottleInputStream(InputStream inputStream, URI sourceURI, URI targetURI) { Preconditions.checkNotNull(inputStream, "InputStream cannot be null."); Limiter limiter = new NoopLimiter(); if (sourceURI != null && targetURI != null) { StreamCopierSharedLimiterKey key = new StreamCopierSharedLimiterKey(sourceURI, targetURI); try { limiter = new MultiLimiter(limiter, this.broker.getSharedResource(new SharedLimiterFactory<S>(), key)); } catch (NotConfiguredException nce) { log.warn("Could not create a Limiter for key " + key, nce); } } else { log.info("Not throttling input stream because source or target URIs are not defined."); } Optional<MeteredInputStream> meteredStream = MeteredInputStream.findWrappedMeteredInputStream(inputStream); if (!meteredStream.isPresent()) { meteredStream = Optional.of(MeteredInputStream.builder().in(inputStream).build()); inputStream = meteredStream.get(); } return new ThrottledInputStream(inputStream, limiter, meteredStream.get()); }
java
@Builder(builderMethodName = "throttleInputStream", builderClassName = "InputStreamThrottler") private ThrottledInputStream doThrottleInputStream(InputStream inputStream, URI sourceURI, URI targetURI) { Preconditions.checkNotNull(inputStream, "InputStream cannot be null."); Limiter limiter = new NoopLimiter(); if (sourceURI != null && targetURI != null) { StreamCopierSharedLimiterKey key = new StreamCopierSharedLimiterKey(sourceURI, targetURI); try { limiter = new MultiLimiter(limiter, this.broker.getSharedResource(new SharedLimiterFactory<S>(), key)); } catch (NotConfiguredException nce) { log.warn("Could not create a Limiter for key " + key, nce); } } else { log.info("Not throttling input stream because source or target URIs are not defined."); } Optional<MeteredInputStream> meteredStream = MeteredInputStream.findWrappedMeteredInputStream(inputStream); if (!meteredStream.isPresent()) { meteredStream = Optional.of(MeteredInputStream.builder().in(inputStream).build()); inputStream = meteredStream.get(); } return new ThrottledInputStream(inputStream, limiter, meteredStream.get()); }
[ "@", "Builder", "(", "builderMethodName", "=", "\"throttleInputStream\"", ",", "builderClassName", "=", "\"InputStreamThrottler\"", ")", "private", "ThrottledInputStream", "doThrottleInputStream", "(", "InputStream", "inputStream", ",", "URI", "sourceURI", ",", "URI", "targetURI", ")", "{", "Preconditions", ".", "checkNotNull", "(", "inputStream", ",", "\"InputStream cannot be null.\"", ")", ";", "Limiter", "limiter", "=", "new", "NoopLimiter", "(", ")", ";", "if", "(", "sourceURI", "!=", "null", "&&", "targetURI", "!=", "null", ")", "{", "StreamCopierSharedLimiterKey", "key", "=", "new", "StreamCopierSharedLimiterKey", "(", "sourceURI", ",", "targetURI", ")", ";", "try", "{", "limiter", "=", "new", "MultiLimiter", "(", "limiter", ",", "this", ".", "broker", ".", "getSharedResource", "(", "new", "SharedLimiterFactory", "<", "S", ">", "(", ")", ",", "key", ")", ")", ";", "}", "catch", "(", "NotConfiguredException", "nce", ")", "{", "log", ".", "warn", "(", "\"Could not create a Limiter for key \"", "+", "key", ",", "nce", ")", ";", "}", "}", "else", "{", "log", ".", "info", "(", "\"Not throttling input stream because source or target URIs are not defined.\"", ")", ";", "}", "Optional", "<", "MeteredInputStream", ">", "meteredStream", "=", "MeteredInputStream", ".", "findWrappedMeteredInputStream", "(", "inputStream", ")", ";", "if", "(", "!", "meteredStream", ".", "isPresent", "(", ")", ")", "{", "meteredStream", "=", "Optional", ".", "of", "(", "MeteredInputStream", ".", "builder", "(", ")", ".", "in", "(", "inputStream", ")", ".", "build", "(", ")", ")", ";", "inputStream", "=", "meteredStream", ".", "get", "(", ")", ";", "}", "return", "new", "ThrottledInputStream", "(", "inputStream", ",", "limiter", ",", "meteredStream", ".", "get", "(", ")", ")", ";", "}" ]
Throttles an {@link InputStream} if throttling is configured. @param inputStream {@link InputStream} to throttle. @param sourceURI used for selecting the throttling policy. @param targetURI used for selecting the throttling policy.
[ "Throttles", "an", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamThrottler.java#L84-L108
PawelAdamski/HttpClientMock
src/main/java/com/github/paweladamski/httpclientmock/HttpClientResponseBuilder.java
HttpClientResponseBuilder.withCookie
public HttpClientResponseBuilder withCookie(String cookieName, String cookieValue) { Action lastAction = newRule.getLastAction(); CookieAction cookieAction = new CookieAction(lastAction, cookieName, cookieValue); newRule.overrideLastAction(cookieAction); return this; }
java
public HttpClientResponseBuilder withCookie(String cookieName, String cookieValue) { Action lastAction = newRule.getLastAction(); CookieAction cookieAction = new CookieAction(lastAction, cookieName, cookieValue); newRule.overrideLastAction(cookieAction); return this; }
[ "public", "HttpClientResponseBuilder", "withCookie", "(", "String", "cookieName", ",", "String", "cookieValue", ")", "{", "Action", "lastAction", "=", "newRule", ".", "getLastAction", "(", ")", ";", "CookieAction", "cookieAction", "=", "new", "CookieAction", "(", "lastAction", ",", "cookieName", ",", "cookieValue", ")", ";", "newRule", ".", "overrideLastAction", "(", "cookieAction", ")", ";", "return", "this", ";", "}" ]
Sets response cookie @param cookieName cookie name @param cookieValue cookie value @return response builder
[ "Sets", "response", "cookie" ]
train
https://github.com/PawelAdamski/HttpClientMock/blob/0205498434bbc0c78c187a51181cac9b266a28fb/src/main/java/com/github/paweladamski/httpclientmock/HttpClientResponseBuilder.java#L54-L59
antopen/alipay-sdk-java
src/main/java/com/alipay/api/internal/util/XmlUtils.java
XmlUtils.saveToXml
public static void saveToXml(Node doc, File file) throws AlipayApiException { OutputStream out = null; try { Transformer tf = TransformerFactory.newInstance().newTransformer(); Properties props = tf.getOutputProperties(); props.setProperty(OutputKeys.METHOD, XMLConstants.XML_NS_PREFIX); props.setProperty(OutputKeys.INDENT, LOGIC_YES); tf.setOutputProperties(props); DOMSource dom = new DOMSource(doc); out = getOutputStream(file); Result result = new StreamResult(out); tf.transform(dom, result); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing to do } } } }
java
public static void saveToXml(Node doc, File file) throws AlipayApiException { OutputStream out = null; try { Transformer tf = TransformerFactory.newInstance().newTransformer(); Properties props = tf.getOutputProperties(); props.setProperty(OutputKeys.METHOD, XMLConstants.XML_NS_PREFIX); props.setProperty(OutputKeys.INDENT, LOGIC_YES); tf.setOutputProperties(props); DOMSource dom = new DOMSource(doc); out = getOutputStream(file); Result result = new StreamResult(out); tf.transform(dom, result); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing to do } } } }
[ "public", "static", "void", "saveToXml", "(", "Node", "doc", ",", "File", "file", ")", "throws", "AlipayApiException", "{", "OutputStream", "out", "=", "null", ";", "try", "{", "Transformer", "tf", "=", "TransformerFactory", ".", "newInstance", "(", ")", ".", "newTransformer", "(", ")", ";", "Properties", "props", "=", "tf", ".", "getOutputProperties", "(", ")", ";", "props", ".", "setProperty", "(", "OutputKeys", ".", "METHOD", ",", "XMLConstants", ".", "XML_NS_PREFIX", ")", ";", "props", ".", "setProperty", "(", "OutputKeys", ".", "INDENT", ",", "LOGIC_YES", ")", ";", "tf", ".", "setOutputProperties", "(", "props", ")", ";", "DOMSource", "dom", "=", "new", "DOMSource", "(", "doc", ")", ";", "out", "=", "getOutputStream", "(", "file", ")", ";", "Result", "result", "=", "new", "StreamResult", "(", "out", ")", ";", "tf", ".", "transform", "(", "dom", ",", "result", ")", ";", "}", "catch", "(", "TransformerException", "e", ")", "{", "throw", "new", "AlipayApiException", "(", "\"XML_TRANSFORM_ERROR\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "out", "!=", "null", ")", "{", "try", "{", "out", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// nothing to do", "}", "}", "}", "}" ]
Saves the node/document/element as XML file. @param doc the XML node/document/element to save @param file the XML file to save @throws ApiException problem persisting XML file
[ "Saves", "the", "node", "/", "document", "/", "element", "as", "XML", "file", "." ]
train
https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/XmlUtils.java#L489-L515
elki-project/elki
elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNAndRKNNPreprocessor.java
MaterializeKNNAndRKNNPreprocessor.affectedkNN
protected ArrayDBIDs affectedkNN(List<? extends KNNList> extract, DBIDs remove) { HashSetModifiableDBIDs ids = DBIDUtil.newHashSet(); for(KNNList drps : extract) { for(DBIDIter iter = drps.iter(); iter.valid(); iter.advance()) { ids.add(iter); } } ids.removeDBIDs(remove); // Convert back to array return DBIDUtil.newArray(ids); }
java
protected ArrayDBIDs affectedkNN(List<? extends KNNList> extract, DBIDs remove) { HashSetModifiableDBIDs ids = DBIDUtil.newHashSet(); for(KNNList drps : extract) { for(DBIDIter iter = drps.iter(); iter.valid(); iter.advance()) { ids.add(iter); } } ids.removeDBIDs(remove); // Convert back to array return DBIDUtil.newArray(ids); }
[ "protected", "ArrayDBIDs", "affectedkNN", "(", "List", "<", "?", "extends", "KNNList", ">", "extract", ",", "DBIDs", "remove", ")", "{", "HashSetModifiableDBIDs", "ids", "=", "DBIDUtil", ".", "newHashSet", "(", ")", ";", "for", "(", "KNNList", "drps", ":", "extract", ")", "{", "for", "(", "DBIDIter", "iter", "=", "drps", ".", "iter", "(", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "ids", ".", "add", "(", "iter", ")", ";", "}", "}", "ids", ".", "removeDBIDs", "(", "remove", ")", ";", "// Convert back to array", "return", "DBIDUtil", ".", "newArray", "(", "ids", ")", ";", "}" ]
Extracts and removes the DBIDs in the given collections. @param extract a list of lists of DistanceResultPair to extract @param remove the ids to remove @return the DBIDs in the given collection
[ "Extracts", "and", "removes", "the", "DBIDs", "in", "the", "given", "collections", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNAndRKNNPreprocessor.java#L288-L298
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/ManagedServer.java
ManagedServer.finishTransition
private synchronized void finishTransition(final InternalState current, final InternalState next) { internalSetState(getTransitionTask(next), current, next); transition(); }
java
private synchronized void finishTransition(final InternalState current, final InternalState next) { internalSetState(getTransitionTask(next), current, next); transition(); }
[ "private", "synchronized", "void", "finishTransition", "(", "final", "InternalState", "current", ",", "final", "InternalState", "next", ")", "{", "internalSetState", "(", "getTransitionTask", "(", "next", ")", ",", "current", ",", "next", ")", ";", "transition", "(", ")", ";", "}" ]
Finish a state transition from a notification. @param current @param next
[ "Finish", "a", "state", "transition", "from", "a", "notification", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/ManagedServer.java#L600-L603
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java
Thin.kernelMatch
private boolean kernelMatch( Point p, int[][] pixels, int w, int h, int[] kernel ) { int matched = 0; for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if (kernel[((j + 1) * 3) + (i + 1)] == 2) { ++matched; } else if ((p.x + i >= 0) && (p.x + i < w) && (p.y + j >= 0) && (p.y + j < h) && (((pixels[p.x + i][p.y + j] == BinaryFast.FOREGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 1)) || ((pixels[p.x + i][p.y + j] == BinaryFast.BACKGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 0)))) { ++matched; } } } if (matched == 9) { return true; } else return false; }
java
private boolean kernelMatch( Point p, int[][] pixels, int w, int h, int[] kernel ) { int matched = 0; for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if (kernel[((j + 1) * 3) + (i + 1)] == 2) { ++matched; } else if ((p.x + i >= 0) && (p.x + i < w) && (p.y + j >= 0) && (p.y + j < h) && (((pixels[p.x + i][p.y + j] == BinaryFast.FOREGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 1)) || ((pixels[p.x + i][p.y + j] == BinaryFast.BACKGROUND) && (kernel[((j + 1) * 3) + (i + 1)] == 0)))) { ++matched; } } } if (matched == 9) { return true; } else return false; }
[ "private", "boolean", "kernelMatch", "(", "Point", "p", ",", "int", "[", "]", "[", "]", "pixels", ",", "int", "w", ",", "int", "h", ",", "int", "[", "]", "kernel", ")", "{", "int", "matched", "=", "0", ";", "for", "(", "int", "j", "=", "-", "1", ";", "j", "<", "2", ";", "++", "j", ")", "{", "for", "(", "int", "i", "=", "-", "1", ";", "i", "<", "2", ";", "++", "i", ")", "{", "if", "(", "kernel", "[", "(", "(", "j", "+", "1", ")", "*", "3", ")", "+", "(", "i", "+", "1", ")", "]", "==", "2", ")", "{", "++", "matched", ";", "}", "else", "if", "(", "(", "p", ".", "x", "+", "i", ">=", "0", ")", "&&", "(", "p", ".", "x", "+", "i", "<", "w", ")", "&&", "(", "p", ".", "y", "+", "j", ">=", "0", ")", "&&", "(", "p", ".", "y", "+", "j", "<", "h", ")", "&&", "(", "(", "(", "pixels", "[", "p", ".", "x", "+", "i", "]", "[", "p", ".", "y", "+", "j", "]", "==", "BinaryFast", ".", "FOREGROUND", ")", "&&", "(", "kernel", "[", "(", "(", "j", "+", "1", ")", "*", "3", ")", "+", "(", "i", "+", "1", ")", "]", "==", "1", ")", ")", "||", "(", "(", "pixels", "[", "p", ".", "x", "+", "i", "]", "[", "p", ".", "y", "+", "j", "]", "==", "BinaryFast", ".", "BACKGROUND", ")", "&&", "(", "kernel", "[", "(", "(", "j", "+", "1", ")", "*", "3", ")", "+", "(", "i", "+", "1", ")", "]", "==", "0", ")", ")", ")", ")", "{", "++", "matched", ";", "}", "}", "}", "if", "(", "matched", "==", "9", ")", "{", "return", "true", ";", "}", "else", "return", "false", ";", "}" ]
Returns true if the 8 neighbours of p match the kernel 0 is background 1 is foreground 2 is don't care. @param p the point at the centre of the 9 pixel neighbourhood @param pixels the 2D array of the image @param w the width of the image @param h the height of the image @param kernel the array of the kernel values @return True if the kernel and image match.
[ "Returns", "true", "if", "the", "8", "neighbours", "of", "p", "match", "the", "kernel", "0", "is", "background", "1", "is", "foreground", "2", "is", "don", "t", "care", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/morpher/Thin.java#L137-L157
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java
PublicIPAddressesInner.beginUpdateTagsAsync
public Observable<PublicIPAddressInner> beginUpdateTagsAsync(String resourceGroupName, String publicIpAddressName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() { @Override public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) { return response.body(); } }); }
java
public Observable<PublicIPAddressInner> beginUpdateTagsAsync(String resourceGroupName, String publicIpAddressName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() { @Override public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PublicIPAddressInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "publicIpAddressName", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "publicIpAddressName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "PublicIPAddressInner", ">", ",", "PublicIPAddressInner", ">", "(", ")", "{", "@", "Override", "public", "PublicIPAddressInner", "call", "(", "ServiceResponse", "<", "PublicIPAddressInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates public IP address tags. @param resourceGroupName The name of the resource group. @param publicIpAddressName The name of the public IP address. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PublicIPAddressInner object
[ "Updates", "public", "IP", "address", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java#L799-L806
neo4j/neo4j-java-driver
driver/src/main/java/org/neo4j/driver/internal/DriverFactory.java
DriverFactory.createDriver
protected InternalDriver createDriver( SecurityPlan securityPlan, SessionFactory sessionFactory, MetricsProvider metricsProvider, Config config ) { return new InternalDriver( securityPlan, sessionFactory, metricsProvider, config.logging() ); }
java
protected InternalDriver createDriver( SecurityPlan securityPlan, SessionFactory sessionFactory, MetricsProvider metricsProvider, Config config ) { return new InternalDriver( securityPlan, sessionFactory, metricsProvider, config.logging() ); }
[ "protected", "InternalDriver", "createDriver", "(", "SecurityPlan", "securityPlan", ",", "SessionFactory", "sessionFactory", ",", "MetricsProvider", "metricsProvider", ",", "Config", "config", ")", "{", "return", "new", "InternalDriver", "(", "securityPlan", ",", "sessionFactory", ",", "metricsProvider", ",", "config", ".", "logging", "(", ")", ")", ";", "}" ]
Creates new {@link Driver}. <p> <b>This method is protected only for testing</b>
[ "Creates", "new", "{" ]
train
https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/DriverFactory.java#L193-L196
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/ProtectionContainersInner.java
ProtectionContainersInner.registerAsync
public Observable<ProtectionContainerResourceInner> registerAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, ProtectionContainerResourceInner parameters) { return registerWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName, parameters).map(new Func1<ServiceResponse<ProtectionContainerResourceInner>, ProtectionContainerResourceInner>() { @Override public ProtectionContainerResourceInner call(ServiceResponse<ProtectionContainerResourceInner> response) { return response.body(); } }); }
java
public Observable<ProtectionContainerResourceInner> registerAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, ProtectionContainerResourceInner parameters) { return registerWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName, parameters).map(new Func1<ServiceResponse<ProtectionContainerResourceInner>, ProtectionContainerResourceInner>() { @Override public ProtectionContainerResourceInner call(ServiceResponse<ProtectionContainerResourceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ProtectionContainerResourceInner", ">", "registerAsync", "(", "String", "vaultName", ",", "String", "resourceGroupName", ",", "String", "fabricName", ",", "String", "containerName", ",", "ProtectionContainerResourceInner", "parameters", ")", "{", "return", "registerWithServiceResponseAsync", "(", "vaultName", ",", "resourceGroupName", ",", "fabricName", ",", "containerName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ProtectionContainerResourceInner", ">", ",", "ProtectionContainerResourceInner", ">", "(", ")", "{", "@", "Override", "public", "ProtectionContainerResourceInner", "call", "(", "ServiceResponse", "<", "ProtectionContainerResourceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Registers the container with Recovery Services vault. This is an asynchronous operation. To track the operation status, use location header to call get latest status of the operation. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @param fabricName Fabric name associated with the container. @param containerName Name of the container to be registered. @param parameters Request body for operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ProtectionContainerResourceInner object
[ "Registers", "the", "container", "with", "Recovery", "Services", "vault", ".", "This", "is", "an", "asynchronous", "operation", ".", "To", "track", "the", "operation", "status", "use", "location", "header", "to", "call", "get", "latest", "status", "of", "the", "operation", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/ProtectionContainersInner.java#L228-L235
cache2k/cache2k
cache2k-core/src/main/java/org/cache2k/core/ConcurrentMapWrapper.java
ConcurrentMapWrapper.putIfAbsent
@Override public V putIfAbsent(K key, final V value) { return cache.invoke(key, new EntryProcessor<K, V, V>() { @Override public V process(MutableCacheEntry<K, V> e) { if (!e.exists()) { e.setValue(value); return null; } return e.getValue(); } }); }
java
@Override public V putIfAbsent(K key, final V value) { return cache.invoke(key, new EntryProcessor<K, V, V>() { @Override public V process(MutableCacheEntry<K, V> e) { if (!e.exists()) { e.setValue(value); return null; } return e.getValue(); } }); }
[ "@", "Override", "public", "V", "putIfAbsent", "(", "K", "key", ",", "final", "V", "value", ")", "{", "return", "cache", ".", "invoke", "(", "key", ",", "new", "EntryProcessor", "<", "K", ",", "V", ",", "V", ">", "(", ")", "{", "@", "Override", "public", "V", "process", "(", "MutableCacheEntry", "<", "K", ",", "V", ">", "e", ")", "{", "if", "(", "!", "e", ".", "exists", "(", ")", ")", "{", "e", ".", "setValue", "(", "value", ")", ";", "return", "null", ";", "}", "return", "e", ".", "getValue", "(", ")", ";", "}", "}", ")", ";", "}" ]
We cannot use {@link Cache#putIfAbsent(Object, Object)} since the map returns the value.
[ "We", "cannot", "use", "{" ]
train
https://github.com/cache2k/cache2k/blob/3c9ccff12608c598c387ec50957089784cc4b618/cache2k-core/src/main/java/org/cache2k/core/ConcurrentMapWrapper.java#L59-L71
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java
FileUtilsV2_2.openOutputStream
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canWrite() == false) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); }
java
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canWrite() == false) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); }
[ "public", "static", "FileOutputStream", "openOutputStream", "(", "File", "file", ",", "boolean", "append", ")", "throws", "IOException", "{", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"File '\"", "+", "file", "+", "\"' exists but is a directory\"", ")", ";", "}", "if", "(", "file", ".", "canWrite", "(", ")", "==", "false", ")", "{", "throw", "new", "IOException", "(", "\"File '\"", "+", "file", "+", "\"' cannot be written to\"", ")", ";", "}", "}", "else", "{", "File", "parent", "=", "file", ".", "getParentFile", "(", ")", ";", "if", "(", "parent", "!=", "null", ")", "{", "if", "(", "!", "parent", ".", "mkdirs", "(", ")", "&&", "!", "parent", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Directory '\"", "+", "parent", "+", "\"' could not be created\"", ")", ";", "}", "}", "}", "return", "new", "FileOutputStream", "(", "file", ",", "append", ")", ";", "}" ]
Opens a {@link FileOutputStream} for the specified file, checking and creating the parent directory if it does not exist. <p> At the end of the method either the stream will be successfully opened, or an exception will have been thrown. <p> The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created. @param file the file to open for output, must not be <code>null</code> @param append if <code>true</code>, then bytes will be added to the end of the file rather than overwriting @return a new {@link FileOutputStream} for the specified file @throws IOException if the file object is a directory @throws IOException if the file cannot be written to @throws IOException if a parent directory needs creating but that fails @since 2.1
[ "Opens", "a", "{", "@link", "FileOutputStream", "}", "for", "the", "specified", "file", "checking", "and", "creating", "the", "parent", "directory", "if", "it", "does", "not", "exist", ".", "<p", ">", "At", "the", "end", "of", "the", "method", "either", "the", "stream", "will", "be", "successfully", "opened", "or", "an", "exception", "will", "have", "been", "thrown", ".", "<p", ">", "The", "parent", "directory", "will", "be", "created", "if", "it", "does", "not", "exist", ".", "The", "file", "will", "be", "created", "if", "it", "does", "not", "exist", ".", "An", "exception", "is", "thrown", "if", "the", "file", "object", "exists", "but", "is", "a", "directory", ".", "An", "exception", "is", "thrown", "if", "the", "file", "exists", "but", "cannot", "be", "written", "to", ".", "An", "exception", "is", "thrown", "if", "the", "parent", "directory", "cannot", "be", "created", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java#L195-L212
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/clientlibs/servlet/ClientlibServlet.java
ClientlibServlet.makePath
public static String makePath(String path, Clientlib.Type type, boolean minified, String hash) { StringBuilder builder = new StringBuilder(path); if (minified) builder.append(".min"); if (!path.endsWith("." + type.name()) && type != Clientlib.Type.img && type != Clientlib.Type.link) { builder.append('.').append(type.name()); // relevant for categories } return appendHashSuffix(builder.toString(), hash); }
java
public static String makePath(String path, Clientlib.Type type, boolean minified, String hash) { StringBuilder builder = new StringBuilder(path); if (minified) builder.append(".min"); if (!path.endsWith("." + type.name()) && type != Clientlib.Type.img && type != Clientlib.Type.link) { builder.append('.').append(type.name()); // relevant for categories } return appendHashSuffix(builder.toString(), hash); }
[ "public", "static", "String", "makePath", "(", "String", "path", ",", "Clientlib", ".", "Type", "type", ",", "boolean", "minified", ",", "String", "hash", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "path", ")", ";", "if", "(", "minified", ")", "builder", ".", "append", "(", "\".min\"", ")", ";", "if", "(", "!", "path", ".", "endsWith", "(", "\".\"", "+", "type", ".", "name", "(", ")", ")", "&&", "type", "!=", "Clientlib", ".", "Type", ".", "img", "&&", "type", "!=", "Clientlib", ".", "Type", ".", "link", ")", "{", "builder", ".", "append", "(", "'", "'", ")", ".", "append", "(", "type", ".", "name", "(", ")", ")", ";", "// relevant for categories", "}", "return", "appendHashSuffix", "(", "builder", ".", "toString", "(", ")", ",", "hash", ")", ";", "}" ]
Creates an path that is rendered by this servlet containing the given parameters.
[ "Creates", "an", "path", "that", "is", "rendered", "by", "this", "servlet", "containing", "the", "given", "parameters", "." ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/clientlibs/servlet/ClientlibServlet.java#L64-L71
strator-dev/greenpepper-open
extensions-external/ognl/src/main/java/com/greenpepper/extensions/ognl/OgnlSupport.java
OgnlSupport.getFixture
public Fixture getFixture( String name, String... params ) throws Throwable { return new OgnlFixture( systemUnderDevelopment.getFixture( name, params ) ); }
java
public Fixture getFixture( String name, String... params ) throws Throwable { return new OgnlFixture( systemUnderDevelopment.getFixture( name, params ) ); }
[ "public", "Fixture", "getFixture", "(", "String", "name", ",", "String", "...", "params", ")", "throws", "Throwable", "{", "return", "new", "OgnlFixture", "(", "systemUnderDevelopment", ".", "getFixture", "(", "name", ",", "params", ")", ")", ";", "}" ]
<p>getFixture.</p> @param name a {@link java.lang.String} object. @param params a {@link java.lang.String} object. @return a {@link com.greenpepper.reflect.Fixture} object. @throws java.lang.Throwable if any.
[ "<p", ">", "getFixture", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper-open/blob/71fd244b4989e9cd2d07ae62dd954a1f2a269a92/extensions-external/ognl/src/main/java/com/greenpepper/extensions/ognl/OgnlSupport.java#L50-L53
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/SynchroReader.java
SynchroReader.processTask
private void processTask(ChildTaskContainer parent, MapRow row) throws IOException { Task task = parent.addTask(); task.setName(row.getString("NAME")); task.setGUID(row.getUUID("UUID")); task.setText(1, row.getString("ID")); task.setDuration(row.getDuration("PLANNED_DURATION")); task.setRemainingDuration(row.getDuration("REMAINING_DURATION")); task.setHyperlink(row.getString("URL")); task.setPercentageComplete(row.getDouble("PERCENT_COMPLETE")); task.setNotes(getNotes(row.getRows("COMMENTARY"))); task.setMilestone(task.getDuration().getDuration() == 0); ProjectCalendar calendar = m_calendarMap.get(row.getUUID("CALENDAR_UUID")); if (calendar != m_project.getDefaultCalendar()) { task.setCalendar(calendar); } switch (row.getInteger("STATUS").intValue()) { case 1: // Planned { task.setStart(row.getDate("PLANNED_START")); task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false)); break; } case 2: // Started { task.setActualStart(row.getDate("ACTUAL_START")); task.setStart(task.getActualStart()); task.setFinish(row.getDate("ESTIMATED_FINISH")); if (task.getFinish() == null) { task.setFinish(row.getDate("PLANNED_FINISH")); } break; } case 3: // Finished { task.setActualStart(row.getDate("ACTUAL_START")); task.setActualFinish(row.getDate("ACTUAL_FINISH")); task.setPercentageComplete(Double.valueOf(100.0)); task.setStart(task.getActualStart()); task.setFinish(task.getActualFinish()); break; } } setConstraints(task, row); processChildTasks(task, row); m_taskMap.put(task.getGUID(), task); List<MapRow> predecessors = row.getRows("PREDECESSORS"); if (predecessors != null && !predecessors.isEmpty()) { m_predecessorMap.put(task, predecessors); } List<MapRow> resourceAssignmnets = row.getRows("RESOURCE_ASSIGNMENTS"); if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty()) { processResourceAssignments(task, resourceAssignmnets); } }
java
private void processTask(ChildTaskContainer parent, MapRow row) throws IOException { Task task = parent.addTask(); task.setName(row.getString("NAME")); task.setGUID(row.getUUID("UUID")); task.setText(1, row.getString("ID")); task.setDuration(row.getDuration("PLANNED_DURATION")); task.setRemainingDuration(row.getDuration("REMAINING_DURATION")); task.setHyperlink(row.getString("URL")); task.setPercentageComplete(row.getDouble("PERCENT_COMPLETE")); task.setNotes(getNotes(row.getRows("COMMENTARY"))); task.setMilestone(task.getDuration().getDuration() == 0); ProjectCalendar calendar = m_calendarMap.get(row.getUUID("CALENDAR_UUID")); if (calendar != m_project.getDefaultCalendar()) { task.setCalendar(calendar); } switch (row.getInteger("STATUS").intValue()) { case 1: // Planned { task.setStart(row.getDate("PLANNED_START")); task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false)); break; } case 2: // Started { task.setActualStart(row.getDate("ACTUAL_START")); task.setStart(task.getActualStart()); task.setFinish(row.getDate("ESTIMATED_FINISH")); if (task.getFinish() == null) { task.setFinish(row.getDate("PLANNED_FINISH")); } break; } case 3: // Finished { task.setActualStart(row.getDate("ACTUAL_START")); task.setActualFinish(row.getDate("ACTUAL_FINISH")); task.setPercentageComplete(Double.valueOf(100.0)); task.setStart(task.getActualStart()); task.setFinish(task.getActualFinish()); break; } } setConstraints(task, row); processChildTasks(task, row); m_taskMap.put(task.getGUID(), task); List<MapRow> predecessors = row.getRows("PREDECESSORS"); if (predecessors != null && !predecessors.isEmpty()) { m_predecessorMap.put(task, predecessors); } List<MapRow> resourceAssignmnets = row.getRows("RESOURCE_ASSIGNMENTS"); if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty()) { processResourceAssignments(task, resourceAssignmnets); } }
[ "private", "void", "processTask", "(", "ChildTaskContainer", "parent", ",", "MapRow", "row", ")", "throws", "IOException", "{", "Task", "task", "=", "parent", ".", "addTask", "(", ")", ";", "task", ".", "setName", "(", "row", ".", "getString", "(", "\"NAME\"", ")", ")", ";", "task", ".", "setGUID", "(", "row", ".", "getUUID", "(", "\"UUID\"", ")", ")", ";", "task", ".", "setText", "(", "1", ",", "row", ".", "getString", "(", "\"ID\"", ")", ")", ";", "task", ".", "setDuration", "(", "row", ".", "getDuration", "(", "\"PLANNED_DURATION\"", ")", ")", ";", "task", ".", "setRemainingDuration", "(", "row", ".", "getDuration", "(", "\"REMAINING_DURATION\"", ")", ")", ";", "task", ".", "setHyperlink", "(", "row", ".", "getString", "(", "\"URL\"", ")", ")", ";", "task", ".", "setPercentageComplete", "(", "row", ".", "getDouble", "(", "\"PERCENT_COMPLETE\"", ")", ")", ";", "task", ".", "setNotes", "(", "getNotes", "(", "row", ".", "getRows", "(", "\"COMMENTARY\"", ")", ")", ")", ";", "task", ".", "setMilestone", "(", "task", ".", "getDuration", "(", ")", ".", "getDuration", "(", ")", "==", "0", ")", ";", "ProjectCalendar", "calendar", "=", "m_calendarMap", ".", "get", "(", "row", ".", "getUUID", "(", "\"CALENDAR_UUID\"", ")", ")", ";", "if", "(", "calendar", "!=", "m_project", ".", "getDefaultCalendar", "(", ")", ")", "{", "task", ".", "setCalendar", "(", "calendar", ")", ";", "}", "switch", "(", "row", ".", "getInteger", "(", "\"STATUS\"", ")", ".", "intValue", "(", ")", ")", "{", "case", "1", ":", "// Planned", "{", "task", ".", "setStart", "(", "row", ".", "getDate", "(", "\"PLANNED_START\"", ")", ")", ";", "task", ".", "setFinish", "(", "task", ".", "getEffectiveCalendar", "(", ")", ".", "getDate", "(", "task", ".", "getStart", "(", ")", ",", "task", ".", "getDuration", "(", ")", ",", "false", ")", ")", ";", "break", ";", "}", "case", "2", ":", "// Started", "{", "task", ".", "setActualStart", "(", "row", ".", "getDate", "(", "\"ACTUAL_START\"", ")", ")", ";", "task", ".", "setStart", "(", "task", ".", "getActualStart", "(", ")", ")", ";", "task", ".", "setFinish", "(", "row", ".", "getDate", "(", "\"ESTIMATED_FINISH\"", ")", ")", ";", "if", "(", "task", ".", "getFinish", "(", ")", "==", "null", ")", "{", "task", ".", "setFinish", "(", "row", ".", "getDate", "(", "\"PLANNED_FINISH\"", ")", ")", ";", "}", "break", ";", "}", "case", "3", ":", "// Finished", "{", "task", ".", "setActualStart", "(", "row", ".", "getDate", "(", "\"ACTUAL_START\"", ")", ")", ";", "task", ".", "setActualFinish", "(", "row", ".", "getDate", "(", "\"ACTUAL_FINISH\"", ")", ")", ";", "task", ".", "setPercentageComplete", "(", "Double", ".", "valueOf", "(", "100.0", ")", ")", ";", "task", ".", "setStart", "(", "task", ".", "getActualStart", "(", ")", ")", ";", "task", ".", "setFinish", "(", "task", ".", "getActualFinish", "(", ")", ")", ";", "break", ";", "}", "}", "setConstraints", "(", "task", ",", "row", ")", ";", "processChildTasks", "(", "task", ",", "row", ")", ";", "m_taskMap", ".", "put", "(", "task", ".", "getGUID", "(", ")", ",", "task", ")", ";", "List", "<", "MapRow", ">", "predecessors", "=", "row", ".", "getRows", "(", "\"PREDECESSORS\"", ")", ";", "if", "(", "predecessors", "!=", "null", "&&", "!", "predecessors", ".", "isEmpty", "(", ")", ")", "{", "m_predecessorMap", ".", "put", "(", "task", ",", "predecessors", ")", ";", "}", "List", "<", "MapRow", ">", "resourceAssignmnets", "=", "row", ".", "getRows", "(", "\"RESOURCE_ASSIGNMENTS\"", ")", ";", "if", "(", "resourceAssignmnets", "!=", "null", "&&", "!", "resourceAssignmnets", ".", "isEmpty", "(", ")", ")", "{", "processResourceAssignments", "(", "task", ",", "resourceAssignmnets", ")", ";", "}", "}" ]
Extract data for a single task. @param parent task parent @param row Synchro task data
[ "Extract", "data", "for", "a", "single", "task", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/SynchroReader.java#L286-L354
cdk/cdk
legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
CDKMCS.getIsomorphAtomsMap
public static List<CDKRMap> getIsomorphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { if (sourceGraph instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } List<CDKRMap> list = checkSingleAtomCases(sourceGraph, targetGraph); if (list == null) { return makeAtomsMapOfBondsMap(CDKMCS.getIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds), sourceGraph, targetGraph); } else if (list.isEmpty()) { return null; } else { return list; } }
java
public static List<CDKRMap> getIsomorphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { if (sourceGraph instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } List<CDKRMap> list = checkSingleAtomCases(sourceGraph, targetGraph); if (list == null) { return makeAtomsMapOfBondsMap(CDKMCS.getIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds), sourceGraph, targetGraph); } else if (list.isEmpty()) { return null; } else { return list; } }
[ "public", "static", "List", "<", "CDKRMap", ">", "getIsomorphAtomsMap", "(", "IAtomContainer", "sourceGraph", ",", "IAtomContainer", "targetGraph", ",", "boolean", "shouldMatchBonds", ")", "throws", "CDKException", "{", "if", "(", "sourceGraph", "instanceof", "IQueryAtomContainer", ")", "{", "throw", "new", "CDKException", "(", "\"The first IAtomContainer must not be an IQueryAtomContainer\"", ")", ";", "}", "List", "<", "CDKRMap", ">", "list", "=", "checkSingleAtomCases", "(", "sourceGraph", ",", "targetGraph", ")", ";", "if", "(", "list", "==", "null", ")", "{", "return", "makeAtomsMapOfBondsMap", "(", "CDKMCS", ".", "getIsomorphMap", "(", "sourceGraph", ",", "targetGraph", ",", "shouldMatchBonds", ")", ",", "sourceGraph", ",", "targetGraph", ")", ";", "}", "else", "if", "(", "list", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "list", ";", "}", "}" ]
Returns the first isomorph 'atom mapping' found for targetGraph in sourceGraph. @param sourceGraph first molecule. Must not be an IQueryAtomContainer. @param targetGraph second molecule. May be an IQueryAtomContainer. @param shouldMatchBonds @return the first isomorph atom mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching atoms. @throws org.openscience.cdk.exception.CDKException if the first molecules is not an instance of {@link org.openscience.cdk.isomorphism.matchers.IQueryAtomContainer}
[ "Returns", "the", "first", "isomorph", "atom", "mapping", "found", "for", "targetGraph", "in", "sourceGraph", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java#L221-L236
ontop/ontop
engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java
OneShotSQLGeneratorEngine.getTypeColumnForSELECT
private String getTypeColumnForSELECT(Term ht, AliasIndex index, Optional<TermType> optionalTermType) { if (ht instanceof Variable) { // Such variable does not hold this information, so we have to look // at the database metadata. return index.getTypeColumn((Variable) ht) .map(QualifiedAttributeID::getSQLRendering) // By default, we assume that the variable is an IRI. .orElseGet(() -> String.valueOf(OBJECT.getQuestCode())); } else { COL_TYPE colType = optionalTermType .flatMap(this::extractColType) // By default, we apply the "most" general COL_TYPE .orElse(STRING); return String.valueOf(colType.getQuestCode()); } }
java
private String getTypeColumnForSELECT(Term ht, AliasIndex index, Optional<TermType> optionalTermType) { if (ht instanceof Variable) { // Such variable does not hold this information, so we have to look // at the database metadata. return index.getTypeColumn((Variable) ht) .map(QualifiedAttributeID::getSQLRendering) // By default, we assume that the variable is an IRI. .orElseGet(() -> String.valueOf(OBJECT.getQuestCode())); } else { COL_TYPE colType = optionalTermType .flatMap(this::extractColType) // By default, we apply the "most" general COL_TYPE .orElse(STRING); return String.valueOf(colType.getQuestCode()); } }
[ "private", "String", "getTypeColumnForSELECT", "(", "Term", "ht", ",", "AliasIndex", "index", ",", "Optional", "<", "TermType", ">", "optionalTermType", ")", "{", "if", "(", "ht", "instanceof", "Variable", ")", "{", "// Such variable does not hold this information, so we have to look", "// at the database metadata.", "return", "index", ".", "getTypeColumn", "(", "(", "Variable", ")", "ht", ")", ".", "map", "(", "QualifiedAttributeID", "::", "getSQLRendering", ")", "// By default, we assume that the variable is an IRI.", ".", "orElseGet", "(", "(", ")", "->", "String", ".", "valueOf", "(", "OBJECT", ".", "getQuestCode", "(", ")", ")", ")", ";", "}", "else", "{", "COL_TYPE", "colType", "=", "optionalTermType", ".", "flatMap", "(", "this", "::", "extractColType", ")", "// By default, we apply the \"most\" general COL_TYPE", ".", "orElse", "(", "STRING", ")", ";", "return", "String", ".", "valueOf", "(", "colType", ".", "getQuestCode", "(", ")", ")", ";", "}", "}" ]
Infers the type of a projected term. Note this type may differ from the one used for casting the main column (in some special cases). This type will appear as the RDF datatype. @param ht @param index Used when the term correspond to a column name @param optionalTermType
[ "Infers", "the", "type", "of", "a", "projected", "term", "." ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java#L1038-L1056
UrielCh/ovh-java-sdk
ovh-java-sdk-newAccount/src/main/java/net/minidev/ovh/api/ApiOvhNewAccount.java
ApiOvhNewAccount.creationRules_GET
public OvhCreationRules creationRules_GET(OvhCountryEnum country, OvhLegalFormEnum legalform, OvhOvhCompanyEnum ovhCompany, OvhOvhSubsidiaryEnum ovhSubsidiary) throws IOException { String qPath = "/newAccount/creationRules"; StringBuilder sb = path(qPath); query(sb, "country", country); query(sb, "legalform", legalform); query(sb, "ovhCompany", ovhCompany); query(sb, "ovhSubsidiary", ovhSubsidiary); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCreationRules.class); }
java
public OvhCreationRules creationRules_GET(OvhCountryEnum country, OvhLegalFormEnum legalform, OvhOvhCompanyEnum ovhCompany, OvhOvhSubsidiaryEnum ovhSubsidiary) throws IOException { String qPath = "/newAccount/creationRules"; StringBuilder sb = path(qPath); query(sb, "country", country); query(sb, "legalform", legalform); query(sb, "ovhCompany", ovhCompany); query(sb, "ovhSubsidiary", ovhSubsidiary); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCreationRules.class); }
[ "public", "OvhCreationRules", "creationRules_GET", "(", "OvhCountryEnum", "country", ",", "OvhLegalFormEnum", "legalform", ",", "OvhOvhCompanyEnum", "ovhCompany", ",", "OvhOvhSubsidiaryEnum", "ovhSubsidiary", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/newAccount/creationRules\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", ",", "\"country\"", ",", "country", ")", ";", "query", "(", "sb", ",", "\"legalform\"", ",", "legalform", ")", ";", "query", "(", "sb", ",", "\"ovhCompany\"", ",", "ovhCompany", ")", ";", "query", "(", "sb", ",", "\"ovhSubsidiary\"", ",", "ovhSubsidiary", ")", ";", "String", "resp", "=", "execN", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhCreationRules", ".", "class", ")", ";", "}" ]
Give all the rules to follow in order to create an OVH identifier REST: GET /newAccount/creationRules @param legalform [required] @param ovhCompany [required] @param ovhSubsidiary [required] @param country [required]
[ "Give", "all", "the", "rules", "to", "follow", "in", "order", "to", "create", "an", "OVH", "identifier" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-newAccount/src/main/java/net/minidev/ovh/api/ApiOvhNewAccount.java#L167-L176
apache/incubator-atlas
repository/src/main/java/org/apache/atlas/repository/typestore/GraphBackedTypeStore.java
GraphBackedTypeStore.createVertices
private List<AtlasVertex> createVertices(List<TypeVertexInfo> infoList) throws AtlasException { List<AtlasVertex> result = new ArrayList<>(infoList.size()); List<String> typeNames = Lists.transform(infoList, new Function<TypeVertexInfo,String>() { @Override public String apply(TypeVertexInfo input) { return input.getTypeName(); } }); Map<String, AtlasVertex> vertices = findVertices(typeNames); for(TypeVertexInfo info : infoList) { AtlasVertex vertex = vertices.get(info.getTypeName()); if (! GraphHelper.elementExists(vertex)) { LOG.debug("Adding vertex {}{}", PROPERTY_PREFIX, info.getTypeName()); vertex = graph.addVertex(); setProperty(vertex, Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE); // Mark as type AtlasVertex setProperty(vertex, Constants.TYPE_CATEGORY_PROPERTY_KEY, info.getCategory()); setProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, info.getTypeName()); } String newDescription = info.getTypeDescription(); if (newDescription != null) { String oldDescription = getPropertyKey(Constants.TYPEDESCRIPTION_PROPERTY_KEY); if (!newDescription.equals(oldDescription)) { setProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, newDescription); } } else { LOG.debug(" type description is null "); } result.add(vertex); } return result; }
java
private List<AtlasVertex> createVertices(List<TypeVertexInfo> infoList) throws AtlasException { List<AtlasVertex> result = new ArrayList<>(infoList.size()); List<String> typeNames = Lists.transform(infoList, new Function<TypeVertexInfo,String>() { @Override public String apply(TypeVertexInfo input) { return input.getTypeName(); } }); Map<String, AtlasVertex> vertices = findVertices(typeNames); for(TypeVertexInfo info : infoList) { AtlasVertex vertex = vertices.get(info.getTypeName()); if (! GraphHelper.elementExists(vertex)) { LOG.debug("Adding vertex {}{}", PROPERTY_PREFIX, info.getTypeName()); vertex = graph.addVertex(); setProperty(vertex, Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE); // Mark as type AtlasVertex setProperty(vertex, Constants.TYPE_CATEGORY_PROPERTY_KEY, info.getCategory()); setProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, info.getTypeName()); } String newDescription = info.getTypeDescription(); if (newDescription != null) { String oldDescription = getPropertyKey(Constants.TYPEDESCRIPTION_PROPERTY_KEY); if (!newDescription.equals(oldDescription)) { setProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, newDescription); } } else { LOG.debug(" type description is null "); } result.add(vertex); } return result; }
[ "private", "List", "<", "AtlasVertex", ">", "createVertices", "(", "List", "<", "TypeVertexInfo", ">", "infoList", ")", "throws", "AtlasException", "{", "List", "<", "AtlasVertex", ">", "result", "=", "new", "ArrayList", "<>", "(", "infoList", ".", "size", "(", ")", ")", ";", "List", "<", "String", ">", "typeNames", "=", "Lists", ".", "transform", "(", "infoList", ",", "new", "Function", "<", "TypeVertexInfo", ",", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "apply", "(", "TypeVertexInfo", "input", ")", "{", "return", "input", ".", "getTypeName", "(", ")", ";", "}", "}", ")", ";", "Map", "<", "String", ",", "AtlasVertex", ">", "vertices", "=", "findVertices", "(", "typeNames", ")", ";", "for", "(", "TypeVertexInfo", "info", ":", "infoList", ")", "{", "AtlasVertex", "vertex", "=", "vertices", ".", "get", "(", "info", ".", "getTypeName", "(", ")", ")", ";", "if", "(", "!", "GraphHelper", ".", "elementExists", "(", "vertex", ")", ")", "{", "LOG", ".", "debug", "(", "\"Adding vertex {}{}\"", ",", "PROPERTY_PREFIX", ",", "info", ".", "getTypeName", "(", ")", ")", ";", "vertex", "=", "graph", ".", "addVertex", "(", ")", ";", "setProperty", "(", "vertex", ",", "Constants", ".", "VERTEX_TYPE_PROPERTY_KEY", ",", "VERTEX_TYPE", ")", ";", "// Mark as type AtlasVertex", "setProperty", "(", "vertex", ",", "Constants", ".", "TYPE_CATEGORY_PROPERTY_KEY", ",", "info", ".", "getCategory", "(", ")", ")", ";", "setProperty", "(", "vertex", ",", "Constants", ".", "TYPENAME_PROPERTY_KEY", ",", "info", ".", "getTypeName", "(", ")", ")", ";", "}", "String", "newDescription", "=", "info", ".", "getTypeDescription", "(", ")", ";", "if", "(", "newDescription", "!=", "null", ")", "{", "String", "oldDescription", "=", "getPropertyKey", "(", "Constants", ".", "TYPEDESCRIPTION_PROPERTY_KEY", ")", ";", "if", "(", "!", "newDescription", ".", "equals", "(", "oldDescription", ")", ")", "{", "setProperty", "(", "vertex", ",", "Constants", ".", "TYPEDESCRIPTION_PROPERTY_KEY", ",", "newDescription", ")", ";", "}", "}", "else", "{", "LOG", ".", "debug", "(", "\" type description is null \"", ")", ";", "}", "result", ".", "add", "(", "vertex", ")", ";", "}", "return", "result", ";", "}" ]
Finds or creates type vertices with the information specified. @param infoList @return list with the vertices corresponding to the types in the list. @throws AtlasException
[ "Finds", "or", "creates", "type", "vertices", "with", "the", "information", "specified", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/typestore/GraphBackedTypeStore.java#L361-L393
xwiki/xwiki-rendering
xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/macro/DefaultMacroContentParser.java
DefaultMacroContentParser.getSyntaxParser
private Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException("Failed to find source parser for syntax [" + syntax + "]", e); } }
java
private Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException("Failed to find source parser for syntax [" + syntax + "]", e); } }
[ "private", "Parser", "getSyntaxParser", "(", "Syntax", "syntax", ")", "throws", "MacroExecutionException", "{", "try", "{", "return", "this", ".", "componentManager", ".", "getInstance", "(", "Parser", ".", "class", ",", "syntax", ".", "toIdString", "(", ")", ")", ";", "}", "catch", "(", "ComponentLookupException", "e", ")", "{", "throw", "new", "MacroExecutionException", "(", "\"Failed to find source parser for syntax [\"", "+", "syntax", "+", "\"]\"", ",", "e", ")", ";", "}", "}" ]
Get the parser for the current syntax. @param syntax the current syntax of the title content @return the parser for the current syntax @throws org.xwiki.rendering.macro.MacroExecutionException Failed to find source parser.
[ "Get", "the", "parser", "for", "the", "current", "syntax", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/macro/DefaultMacroContentParser.java#L183-L190
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java
DataGridStateFactory.attachDataGridState
public final void attachDataGridState(String name, DataGridState state) { DataGridStateCodec codec = lookupCodec(name, DEFAULT_DATA_GRID_CONFIG); codec.setDataGridState(state); }
java
public final void attachDataGridState(String name, DataGridState state) { DataGridStateCodec codec = lookupCodec(name, DEFAULT_DATA_GRID_CONFIG); codec.setDataGridState(state); }
[ "public", "final", "void", "attachDataGridState", "(", "String", "name", ",", "DataGridState", "state", ")", "{", "DataGridStateCodec", "codec", "=", "lookupCodec", "(", "name", ",", "DEFAULT_DATA_GRID_CONFIG", ")", ";", "codec", ".", "setDataGridState", "(", "state", ")", ";", "}" ]
<p> Convenience method that allows a {@link DataGridState} object from a client to be attached to the factory. This allows subsequent calls to retrieve this same {@link DataGridState} instance. </p> @param name the name of the data grid @param state the {@link DataGridState} object to attach
[ "<p", ">", "Convenience", "method", "that", "allows", "a", "{", "@link", "DataGridState", "}", "object", "from", "a", "client", "to", "be", "attached", "to", "the", "factory", ".", "This", "allows", "subsequent", "calls", "to", "retrieve", "this", "same", "{", "@link", "DataGridState", "}", "instance", ".", "<", "/", "p", ">" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java#L172-L175
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/ToStream.java
ToStream.startPrefixMapping
public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { // the "true" causes the flush of any open tags startPrefixMapping(prefix, uri, true); }
java
public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { // the "true" causes the flush of any open tags startPrefixMapping(prefix, uri, true); }
[ "public", "void", "startPrefixMapping", "(", "String", "prefix", ",", "String", "uri", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "// the \"true\" causes the flush of any open tags", "startPrefixMapping", "(", "prefix", ",", "uri", ",", "true", ")", ";", "}" ]
Begin the scope of a prefix-URI Namespace mapping just before another element is about to start. This call will close any open tags so that the prefix mapping will not apply to the current element, but the up comming child. @see org.xml.sax.ContentHandler#startPrefixMapping @param prefix The Namespace prefix being declared. @param uri The Namespace URI the prefix is mapped to. @throws org.xml.sax.SAXException The client may throw an exception during processing.
[ "Begin", "the", "scope", "of", "a", "prefix", "-", "URI", "Namespace", "mapping", "just", "before", "another", "element", "is", "about", "to", "start", ".", "This", "call", "will", "close", "any", "open", "tags", "so", "that", "the", "prefix", "mapping", "will", "not", "apply", "to", "the", "current", "element", "but", "the", "up", "comming", "child", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/ToStream.java#L2295-L2300
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java
KeyVaultClientCustomImpl.listKeyVersions
public PagedList<KeyItem> listKeyVersions(final String vaultBaseUrl, final String keyName) { return getKeyVersions(vaultBaseUrl, keyName); }
java
public PagedList<KeyItem> listKeyVersions(final String vaultBaseUrl, final String keyName) { return getKeyVersions(vaultBaseUrl, keyName); }
[ "public", "PagedList", "<", "KeyItem", ">", "listKeyVersions", "(", "final", "String", "vaultBaseUrl", ",", "final", "String", "keyName", ")", "{", "return", "getKeyVersions", "(", "vaultBaseUrl", ",", "keyName", ")", ";", "}" ]
Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. Authorization: Requires the keys/list permission. @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net @param keyName The name of the key @return the PagedList&lt;KeyItem&gt; if successful.
[ "Retrieves", "a", "list", "of", "individual", "key", "versions", "with", "the", "same", "key", "name", ".", "The", "full", "key", "identifier", "attributes", "and", "tags", "are", "provided", "in", "the", "response", ".", "Authorization", ":", "Requires", "the", "keys", "/", "list", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L687-L689
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java
Text.getRelativeParent
public static String getRelativeParent(String path, int level, boolean ignoreTrailingSlash) { if (ignoreTrailingSlash && path.endsWith("/") && path.length() > 1) { path = path.substring(0, path.length() - 1); } return getRelativeParent(path, level); }
java
public static String getRelativeParent(String path, int level, boolean ignoreTrailingSlash) { if (ignoreTrailingSlash && path.endsWith("/") && path.length() > 1) { path = path.substring(0, path.length() - 1); } return getRelativeParent(path, level); }
[ "public", "static", "String", "getRelativeParent", "(", "String", "path", ",", "int", "level", ",", "boolean", "ignoreTrailingSlash", ")", "{", "if", "(", "ignoreTrailingSlash", "&&", "path", ".", "endsWith", "(", "\"/\"", ")", "&&", "path", ".", "length", "(", ")", ">", "1", ")", "{", "path", "=", "path", ".", "substring", "(", "0", ",", "path", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "getRelativeParent", "(", "path", ",", "level", ")", ";", "}" ]
Same as {@link #getRelativeParent(String, int)} but adding the possibility to pass paths that end with a trailing '/'. @see #getRelativeParent(String, int) @param path path @param level level @param ignoreTrailingSlash ignore trailing slash @return String relative parent
[ "Same", "as", "{", "@link", "#getRelativeParent", "(", "String", "int", ")", "}", "but", "adding", "the", "possibility", "to", "pass", "paths", "that", "end", "with", "a", "trailing", "/", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java#L788-L795
elki-project/elki
elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/OutputStreamLogger.java
OutputStreamLogger.tailingNonNewline
private int tailingNonNewline(char[] cbuf, int off, int len) { for(int cnt = 0; cnt < len; cnt++) { final int pos = off + (len - 1) - cnt; if(cbuf[pos] == UNIX_NEWLINE) { return cnt; } if(cbuf[pos] == CARRIAGE_RETURN) { return cnt; } // TODO: need to compare to NEWLINEC, too? } return len; }
java
private int tailingNonNewline(char[] cbuf, int off, int len) { for(int cnt = 0; cnt < len; cnt++) { final int pos = off + (len - 1) - cnt; if(cbuf[pos] == UNIX_NEWLINE) { return cnt; } if(cbuf[pos] == CARRIAGE_RETURN) { return cnt; } // TODO: need to compare to NEWLINEC, too? } return len; }
[ "private", "int", "tailingNonNewline", "(", "char", "[", "]", "cbuf", ",", "int", "off", ",", "int", "len", ")", "{", "for", "(", "int", "cnt", "=", "0", ";", "cnt", "<", "len", ";", "cnt", "++", ")", "{", "final", "int", "pos", "=", "off", "+", "(", "len", "-", "1", ")", "-", "cnt", ";", "if", "(", "cbuf", "[", "pos", "]", "==", "UNIX_NEWLINE", ")", "{", "return", "cnt", ";", "}", "if", "(", "cbuf", "[", "pos", "]", "==", "CARRIAGE_RETURN", ")", "{", "return", "cnt", ";", "}", "// TODO: need to compare to NEWLINEC, too?", "}", "return", "len", ";", "}" ]
Count the tailing non-newline characters. @param cbuf Character buffer @param off Offset @param len Range @return number of tailing non-newline character
[ "Count", "the", "tailing", "non", "-", "newline", "characters", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/OutputStreamLogger.java#L126-L138
jhunters/jprotobuf
src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java
MiniTemplatorParser.skipBlanks
private static int skipBlanks(String s, int p) { while (p < s.length() && Character.isWhitespace(s.charAt(p))) p++; return p; }
java
private static int skipBlanks(String s, int p) { while (p < s.length() && Character.isWhitespace(s.charAt(p))) p++; return p; }
[ "private", "static", "int", "skipBlanks", "(", "String", "s", ",", "int", "p", ")", "{", "while", "(", "p", "<", "s", ".", "length", "(", ")", "&&", "Character", ".", "isWhitespace", "(", "s", ".", "charAt", "(", "p", ")", ")", ")", "p", "++", ";", "return", "p", ";", "}" ]
Skips blanks (white space) in string s starting at position p.
[ "Skips", "blanks", "(", "white", "space", ")", "in", "string", "s", "starting", "at", "position", "p", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java#L1561-L1565
alkacon/opencms-core
src/org/opencms/ui/dataview/CmsColumnValueConverter.java
CmsColumnValueConverter.getColumnValue
public static Object getColumnValue(Object value, CmsDataViewColumn.Type type) { if (type == Type.imageType) { Image image = new Image("", new ExternalResource((String)value)); image.addStyleName("o-table-image"); return image; } else { return value; } }
java
public static Object getColumnValue(Object value, CmsDataViewColumn.Type type) { if (type == Type.imageType) { Image image = new Image("", new ExternalResource((String)value)); image.addStyleName("o-table-image"); return image; } else { return value; } }
[ "public", "static", "Object", "getColumnValue", "(", "Object", "value", ",", "CmsDataViewColumn", ".", "Type", "type", ")", "{", "if", "(", "type", "==", "Type", ".", "imageType", ")", "{", "Image", "image", "=", "new", "Image", "(", "\"\"", ",", "new", "ExternalResource", "(", "(", "String", ")", "value", ")", ")", ";", "image", ".", "addStyleName", "(", "\"o-table-image\"", ")", ";", "return", "image", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
Gets the actual column value for the given data value.<p> @param value the data value @param type the column type enum @return the actual column value to use
[ "Gets", "the", "actual", "column", "value", "for", "the", "given", "data", "value", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dataview/CmsColumnValueConverter.java#L72-L81
OpenLiberty/open-liberty
dev/com.ibm.ws.crypto.passwordutil/src/com/ibm/ws/crypto/util/custom/CustomManifest.java
CustomManifest.getFeatureId
protected static String getFeatureId(File featureManifest) throws IOException { String rootDir = CustomUtils.getCanonicalPath(featureManifest.getParentFile().getParentFile().getParentFile()); // go up two directories. String output = null; // check with user feature dir. if (rootDir.equals(CustomUtils.getCanonicalPath(new File(CustomUtils.getInstallRoot(), CustomUtils.USER_FEATURE_DIR)))) { output = "usr"; } else { for (ProductExtensionInfo info : ProductExtension.getProductExtensions()) { File extensionDir = new File(info.getLocation()); if (!CustomUtils.isAbsolute(extensionDir)) { File parentDir = new File(CustomUtils.getInstallRoot()).getParentFile(); extensionDir = new File(parentDir, info.getLocation()); } if (rootDir.equals(CustomUtils.getCanonicalPath(extensionDir))) { output = info.getProductID(); break; } } } return output; }
java
protected static String getFeatureId(File featureManifest) throws IOException { String rootDir = CustomUtils.getCanonicalPath(featureManifest.getParentFile().getParentFile().getParentFile()); // go up two directories. String output = null; // check with user feature dir. if (rootDir.equals(CustomUtils.getCanonicalPath(new File(CustomUtils.getInstallRoot(), CustomUtils.USER_FEATURE_DIR)))) { output = "usr"; } else { for (ProductExtensionInfo info : ProductExtension.getProductExtensions()) { File extensionDir = new File(info.getLocation()); if (!CustomUtils.isAbsolute(extensionDir)) { File parentDir = new File(CustomUtils.getInstallRoot()).getParentFile(); extensionDir = new File(parentDir, info.getLocation()); } if (rootDir.equals(CustomUtils.getCanonicalPath(extensionDir))) { output = info.getProductID(); break; } } } return output; }
[ "protected", "static", "String", "getFeatureId", "(", "File", "featureManifest", ")", "throws", "IOException", "{", "String", "rootDir", "=", "CustomUtils", ".", "getCanonicalPath", "(", "featureManifest", ".", "getParentFile", "(", ")", ".", "getParentFile", "(", ")", ".", "getParentFile", "(", ")", ")", ";", "// go up two directories.", "String", "output", "=", "null", ";", "// check with user feature dir.", "if", "(", "rootDir", ".", "equals", "(", "CustomUtils", ".", "getCanonicalPath", "(", "new", "File", "(", "CustomUtils", ".", "getInstallRoot", "(", ")", ",", "CustomUtils", ".", "USER_FEATURE_DIR", ")", ")", ")", ")", "{", "output", "=", "\"usr\"", ";", "}", "else", "{", "for", "(", "ProductExtensionInfo", "info", ":", "ProductExtension", ".", "getProductExtensions", "(", ")", ")", "{", "File", "extensionDir", "=", "new", "File", "(", "info", ".", "getLocation", "(", ")", ")", ";", "if", "(", "!", "CustomUtils", ".", "isAbsolute", "(", "extensionDir", ")", ")", "{", "File", "parentDir", "=", "new", "File", "(", "CustomUtils", ".", "getInstallRoot", "(", ")", ")", ".", "getParentFile", "(", ")", ";", "extensionDir", "=", "new", "File", "(", "parentDir", ",", "info", ".", "getLocation", "(", ")", ")", ";", "}", "if", "(", "rootDir", ".", "equals", "(", "CustomUtils", ".", "getCanonicalPath", "(", "extensionDir", ")", ")", ")", "{", "output", "=", "info", ".", "getProductID", "(", ")", ";", "break", ";", "}", "}", "}", "return", "output", ";", "}" ]
Find corresponding feature id (i.e., user or myExt1 from the location of feature manifest file. The logic is that since the location of the feature manifest file is .../lib/features/<feature manifest> find the parent of lib directory, and compare the location information of the ProductionExtension objects, and if they match, get the corresponding feature id from the ProductExtension object and return it. If there is no matching id, return null. @throws IOException
[ "Find", "corresponding", "feature", "id", "(", "i", ".", "e", ".", "user", "or", "myExt1", "from", "the", "location", "of", "feature", "manifest", "file", ".", "The", "logic", "is", "that", "since", "the", "location", "of", "the", "feature", "manifest", "file", "is", "...", "/", "lib", "/", "features", "/", "<feature", "manifest", ">", "find", "the", "parent", "of", "lib", "directory", "and", "compare", "the", "location", "information", "of", "the", "ProductionExtension", "objects", "and", "if", "they", "match", "get", "the", "corresponding", "feature", "id", "from", "the", "ProductExtension", "object", "and", "return", "it", ".", "If", "there", "is", "no", "matching", "id", "return", "null", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.crypto.passwordutil/src/com/ibm/ws/crypto/util/custom/CustomManifest.java#L288-L308
alkacon/opencms-core
src/org/opencms/ui/components/CmsResourceIcon.java
CmsResourceIcon.getIconInnerHTML
private static String getIconInnerHTML( CmsResourceUtil resUtil, CmsResourceState state, boolean showLocks, boolean showDetailIcon) { Resource iconResource = resUtil.getBigIconResource(); return getIconInnerHTML(resUtil, iconResource, state, showLocks, showDetailIcon); }
java
private static String getIconInnerHTML( CmsResourceUtil resUtil, CmsResourceState state, boolean showLocks, boolean showDetailIcon) { Resource iconResource = resUtil.getBigIconResource(); return getIconInnerHTML(resUtil, iconResource, state, showLocks, showDetailIcon); }
[ "private", "static", "String", "getIconInnerHTML", "(", "CmsResourceUtil", "resUtil", ",", "CmsResourceState", "state", ",", "boolean", "showLocks", ",", "boolean", "showDetailIcon", ")", "{", "Resource", "iconResource", "=", "resUtil", ".", "getBigIconResource", "(", ")", ";", "return", "getIconInnerHTML", "(", "resUtil", ",", "iconResource", ",", "state", ",", "showLocks", ",", "showDetailIcon", ")", ";", "}" ]
Returns the icon inner HTML.<p> @param resUtil the resource util for the resource @param state the resource state @param showLocks <code>true</code> to show lock state overlay @param showDetailIcon <code>true</code> to show the detail icon overlay @return the icon inner HTML
[ "Returns", "the", "icon", "inner", "HTML", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsResourceIcon.java#L302-L311
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MbeanImplCodeGen.java
MbeanImplCodeGen.writeImport
@Override public void writeImport(Definition def, Writer out) throws IOException { out.write("package " + def.getRaPackage() + ".mbean;\n\n"); out.write("import javax.management.MBeanServer;\n"); out.write("import javax.management.ObjectName;\n"); out.write("import javax.naming.InitialContext;\n\n"); out.write("import " + def.getRaPackage() + "." + def.getMcfDefs().get(0).getConnInterfaceClass() + ";\n"); out.write("import " + def.getRaPackage() + "." + def.getMcfDefs().get(0).getCfInterfaceClass() + ";\n\n"); }
java
@Override public void writeImport(Definition def, Writer out) throws IOException { out.write("package " + def.getRaPackage() + ".mbean;\n\n"); out.write("import javax.management.MBeanServer;\n"); out.write("import javax.management.ObjectName;\n"); out.write("import javax.naming.InitialContext;\n\n"); out.write("import " + def.getRaPackage() + "." + def.getMcfDefs().get(0).getConnInterfaceClass() + ";\n"); out.write("import " + def.getRaPackage() + "." + def.getMcfDefs().get(0).getCfInterfaceClass() + ";\n\n"); }
[ "@", "Override", "public", "void", "writeImport", "(", "Definition", "def", ",", "Writer", "out", ")", "throws", "IOException", "{", "out", ".", "write", "(", "\"package \"", "+", "def", ".", "getRaPackage", "(", ")", "+", "\".mbean;\\n\\n\"", ")", ";", "out", ".", "write", "(", "\"import javax.management.MBeanServer;\\n\"", ")", ";", "out", ".", "write", "(", "\"import javax.management.ObjectName;\\n\"", ")", ";", "out", ".", "write", "(", "\"import javax.naming.InitialContext;\\n\\n\"", ")", ";", "out", ".", "write", "(", "\"import \"", "+", "def", ".", "getRaPackage", "(", ")", "+", "\".\"", "+", "def", ".", "getMcfDefs", "(", ")", ".", "get", "(", "0", ")", ".", "getConnInterfaceClass", "(", ")", "+", "\";\\n\"", ")", ";", "out", ".", "write", "(", "\"import \"", "+", "def", ".", "getRaPackage", "(", ")", "+", "\".\"", "+", "def", ".", "getMcfDefs", "(", ")", ".", "get", "(", "0", ")", ".", "getCfInterfaceClass", "(", ")", "+", "\";\\n\\n\"", ")", ";", "}" ]
Output class import @param def definition @param out Writer @throws IOException ioException
[ "Output", "class", "import" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MbeanImplCodeGen.java#L92-L102
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/component/ComponentStateHelper.java
ComponentStateHelper.saveState
public Object saveState(FacesContext context) { if (context == null) { throw new NullPointerException(); } if(component.initialStateMarked()) { return saveMap(context, deltaMap); } else { return saveMap(context, defaultMap); } }
java
public Object saveState(FacesContext context) { if (context == null) { throw new NullPointerException(); } if(component.initialStateMarked()) { return saveMap(context, deltaMap); } else { return saveMap(context, defaultMap); } }
[ "public", "Object", "saveState", "(", "FacesContext", "context", ")", "{", "if", "(", "context", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "if", "(", "component", ".", "initialStateMarked", "(", ")", ")", "{", "return", "saveMap", "(", "context", ",", "deltaMap", ")", ";", "}", "else", "{", "return", "saveMap", "(", "context", ",", "defaultMap", ")", ";", "}", "}" ]
One and only implementation of save-state - makes all other implementations unnecessary. @param context @return the saved state
[ "One", "and", "only", "implementation", "of", "save", "-", "state", "-", "makes", "all", "other", "implementations", "unnecessary", "." ]
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/ComponentStateHelper.java#L251-L261
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WRowRenderer.java
WRowRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WRow row = (WRow) component; XmlStringBuilder xml = renderContext.getWriter(); int cols = row.getChildCount(); Size gap = row.getSpace(); String gapString = gap != null ? gap.toString() : null; if (cols > 0) { xml.appendTagOpen("ui:row"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("gap", gapString); xml.appendClose(); // Render margin MarginRendererUtil.renderMargin(row, renderContext); paintChildren(row, renderContext); xml.appendEndTag("ui:row"); } }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WRow row = (WRow) component; XmlStringBuilder xml = renderContext.getWriter(); int cols = row.getChildCount(); Size gap = row.getSpace(); String gapString = gap != null ? gap.toString() : null; if (cols > 0) { xml.appendTagOpen("ui:row"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("gap", gapString); xml.appendClose(); // Render margin MarginRendererUtil.renderMargin(row, renderContext); paintChildren(row, renderContext); xml.appendEndTag("ui:row"); } }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WRow", "row", "=", "(", "WRow", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "int", "cols", "=", "row", ".", "getChildCount", "(", ")", ";", "Size", "gap", "=", "row", ".", "getSpace", "(", ")", ";", "String", "gapString", "=", "gap", "!=", "null", "?", "gap", ".", "toString", "(", ")", ":", "null", ";", "if", "(", "cols", ">", "0", ")", "{", "xml", ".", "appendTagOpen", "(", "\"ui:row\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"id\"", ",", "component", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"class\"", ",", "component", ".", "getHtmlClass", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"track\"", ",", "component", ".", "isTracking", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"gap\"", ",", "gapString", ")", ";", "xml", ".", "appendClose", "(", ")", ";", "// Render margin", "MarginRendererUtil", ".", "renderMargin", "(", "row", ",", "renderContext", ")", ";", "paintChildren", "(", "row", ",", "renderContext", ")", ";", "xml", ".", "appendEndTag", "(", "\"ui:row\"", ")", ";", "}", "}" ]
Paints the given WButton. @param component the WRow to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WButton", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WRowRenderer.java#L25-L48
JOML-CI/JOML
src/org/joml/Matrix4x3d.java
Matrix4x3d.translationRotateMul
public Matrix4x3d translationRotateMul(double tx, double ty, double tz, Quaternionfc quat, Matrix4x3dc mat) { return translationRotateMul(tx, ty, tz, quat.x(), quat.y(), quat.z(), quat.w(), mat); }
java
public Matrix4x3d translationRotateMul(double tx, double ty, double tz, Quaternionfc quat, Matrix4x3dc mat) { return translationRotateMul(tx, ty, tz, quat.x(), quat.y(), quat.z(), quat.w(), mat); }
[ "public", "Matrix4x3d", "translationRotateMul", "(", "double", "tx", ",", "double", "ty", ",", "double", "tz", ",", "Quaternionfc", "quat", ",", "Matrix4x3dc", "mat", ")", "{", "return", "translationRotateMul", "(", "tx", ",", "ty", ",", "tz", ",", "quat", ".", "x", "(", ")", ",", "quat", ".", "y", "(", ")", ",", "quat", ".", "z", "(", ")", ",", "quat", ".", "w", "(", ")", ",", "mat", ")", ";", "}" ]
Set <code>this</code> matrix to <code>T * R * M</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code>, <code>R</code> is a rotation - and possibly scaling - transformation specified by the given quaternion and <code>M</code> is the given matrix <code>mat</code>. <p> When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and at last the translation. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat).mul(mat)</code> @see #translation(double, double, double) @see #rotate(Quaternionfc) @see #mul(Matrix4x3dc) @param tx the number of units by which to translate the x-component @param ty the number of units by which to translate the y-component @param tz the number of units by which to translate the z-component @param quat the quaternion representing a rotation @param mat the matrix to multiply with @return this
[ "Set", "<code", ">", "this<", "/", "code", ">", "matrix", "to", "<code", ">", "T", "*", "R", "*", "M<", "/", "code", ">", "where", "<code", ">", "T<", "/", "code", ">", "is", "a", "translation", "by", "the", "given", "<code", ">", "(", "tx", "ty", "tz", ")", "<", "/", "code", ">", "<code", ">", "R<", "/", "code", ">", "is", "a", "rotation", "-", "and", "possibly", "scaling", "-", "transformation", "specified", "by", "the", "given", "quaternion", "and", "<code", ">", "M<", "/", "code", ">", "is", "the", "given", "matrix", "<code", ">", "mat<", "/", "code", ">", ".", "<p", ">", "When", "transforming", "a", "vector", "by", "the", "resulting", "matrix", "the", "transformation", "described", "by", "<code", ">", "M<", "/", "code", ">", "will", "be", "applied", "first", "then", "the", "scaling", "then", "rotation", "and", "at", "last", "the", "translation", ".", "<p", ">", "When", "used", "with", "a", "right", "-", "handed", "coordinate", "system", "the", "produced", "rotation", "will", "rotate", "a", "vector", "counter", "-", "clockwise", "around", "the", "rotation", "axis", "when", "viewing", "along", "the", "negative", "axis", "direction", "towards", "the", "origin", ".", "When", "used", "with", "a", "left", "-", "handed", "coordinate", "system", "the", "rotation", "is", "clockwise", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", ":", "<code", ">", "translation", "(", "tx", "ty", "tz", ")", ".", "rotate", "(", "quat", ")", ".", "mul", "(", "mat", ")", "<", "/", "code", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L5140-L5142
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/generalize/ST_PrecisionReducer.java
ST_PrecisionReducer.precisionReducer
public static Geometry precisionReducer(Geometry geometry, int nbDec) throws SQLException { if(geometry == null){ return null; } if (nbDec < 0) { throw new SQLException("Decimal_places has to be >= 0."); } PrecisionModel pm = new PrecisionModel(scaleFactorForDecimalPlaces(nbDec)); GeometryPrecisionReducer geometryPrecisionReducer = new GeometryPrecisionReducer(pm); return geometryPrecisionReducer.reduce(geometry); }
java
public static Geometry precisionReducer(Geometry geometry, int nbDec) throws SQLException { if(geometry == null){ return null; } if (nbDec < 0) { throw new SQLException("Decimal_places has to be >= 0."); } PrecisionModel pm = new PrecisionModel(scaleFactorForDecimalPlaces(nbDec)); GeometryPrecisionReducer geometryPrecisionReducer = new GeometryPrecisionReducer(pm); return geometryPrecisionReducer.reduce(geometry); }
[ "public", "static", "Geometry", "precisionReducer", "(", "Geometry", "geometry", ",", "int", "nbDec", ")", "throws", "SQLException", "{", "if", "(", "geometry", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "nbDec", "<", "0", ")", "{", "throw", "new", "SQLException", "(", "\"Decimal_places has to be >= 0.\"", ")", ";", "}", "PrecisionModel", "pm", "=", "new", "PrecisionModel", "(", "scaleFactorForDecimalPlaces", "(", "nbDec", ")", ")", ";", "GeometryPrecisionReducer", "geometryPrecisionReducer", "=", "new", "GeometryPrecisionReducer", "(", "pm", ")", ";", "return", "geometryPrecisionReducer", ".", "reduce", "(", "geometry", ")", ";", "}" ]
Reduce the geometry precision. Decimal_Place is the number of decimals to keep. @param geometry @param nbDec @return @throws SQLException
[ "Reduce", "the", "geometry", "precision", ".", "Decimal_Place", "is", "the", "number", "of", "decimals", "to", "keep", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/generalize/ST_PrecisionReducer.java#L54-L64
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java
SpellingCheckRule.ignoreWord
protected boolean ignoreWord(List<String> words, int idx) throws IOException { return ignoreWord(words.get(idx)); }
java
protected boolean ignoreWord(List<String> words, int idx) throws IOException { return ignoreWord(words.get(idx)); }
[ "protected", "boolean", "ignoreWord", "(", "List", "<", "String", ">", "words", ",", "int", "idx", ")", "throws", "IOException", "{", "return", "ignoreWord", "(", "words", ".", "get", "(", "idx", ")", ")", ";", "}" ]
Returns true iff the word at the given position should be ignored by the spell checker. If possible, use {@link #ignoreToken(AnalyzedTokenReadings[], int)} instead. @since 2.6
[ "Returns", "true", "iff", "the", "word", "at", "the", "given", "position", "should", "be", "ignored", "by", "the", "spell", "checker", ".", "If", "possible", "use", "{" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java#L291-L293
thorntail/thorntail
core/container/src/main/java/org/wildfly/swarm/internal/wildfly/SelfContainedContainer.java
SelfContainedContainer.start
public ServiceContainer start(final List<ModelNode> containerDefinition, Collection<ServiceActivator> additionalActivators) throws ExecutionException, InterruptedException, ModuleLoadException { final long startTime = System.currentTimeMillis(); if (java.util.logging.LogManager.getLogManager().getClass().getName().equals("org.jboss.logmanager.LogManager")) { try { Class.forName(org.jboss.logmanager.handlers.ConsoleHandler.class.getName(), true, org.jboss.logmanager.handlers.ConsoleHandler.class.getClassLoader()); // Install JBoss Stdio to avoid any nasty crosstalk, after command line arguments are processed. StdioContext.install(); final StdioContext context = StdioContext.create( new NullInputStream(), new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stdout"), org.jboss.logmanager.Level.INFO), new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stderr"), org.jboss.logmanager.Level.ERROR) ); StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context)); } catch (Throwable ignored) { } } Module.registerURLStreamHandlerFactoryModule(Module.getBootModuleLoader().loadModule("org.jboss.vfs")); ServerEnvironment serverEnvironment = determineEnvironment(WildFlySecurityManager.getSystemPropertiesPrivileged(), WildFlySecurityManager.getSystemEnvironmentPrivileged(), ServerEnvironment.LaunchType.SELF_CONTAINED, startTime); final Bootstrap bootstrap = Bootstrap.Factory.newInstance(); final Bootstrap.Configuration configuration = new Bootstrap.Configuration(serverEnvironment); configuration.setConfigurationPersisterFactory( new Bootstrap.ConfigurationPersisterFactory() { @Override public ExtensibleConfigurationPersister createConfigurationPersister(ServerEnvironment serverEnvironment, ExecutorService executorService) { ExtensibleConfigurationPersister delegate; delegate = persisterFactory.createConfigurationPersister(serverEnvironment, executorService); configuration.getExtensionRegistry().setWriterRegistry(delegate); return delegate; } }); configuration.setModuleLoader(Module.getBootModuleLoader()); List<ServiceActivator> activators = new ArrayList<>(); //activators.add(new ContentProviderServiceActivator(contentProvider)); activators.addAll(additionalActivators); serviceContainer = bootstrap.startup(configuration, activators).get(); return serviceContainer; }
java
public ServiceContainer start(final List<ModelNode> containerDefinition, Collection<ServiceActivator> additionalActivators) throws ExecutionException, InterruptedException, ModuleLoadException { final long startTime = System.currentTimeMillis(); if (java.util.logging.LogManager.getLogManager().getClass().getName().equals("org.jboss.logmanager.LogManager")) { try { Class.forName(org.jboss.logmanager.handlers.ConsoleHandler.class.getName(), true, org.jboss.logmanager.handlers.ConsoleHandler.class.getClassLoader()); // Install JBoss Stdio to avoid any nasty crosstalk, after command line arguments are processed. StdioContext.install(); final StdioContext context = StdioContext.create( new NullInputStream(), new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stdout"), org.jboss.logmanager.Level.INFO), new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stderr"), org.jboss.logmanager.Level.ERROR) ); StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context)); } catch (Throwable ignored) { } } Module.registerURLStreamHandlerFactoryModule(Module.getBootModuleLoader().loadModule("org.jboss.vfs")); ServerEnvironment serverEnvironment = determineEnvironment(WildFlySecurityManager.getSystemPropertiesPrivileged(), WildFlySecurityManager.getSystemEnvironmentPrivileged(), ServerEnvironment.LaunchType.SELF_CONTAINED, startTime); final Bootstrap bootstrap = Bootstrap.Factory.newInstance(); final Bootstrap.Configuration configuration = new Bootstrap.Configuration(serverEnvironment); configuration.setConfigurationPersisterFactory( new Bootstrap.ConfigurationPersisterFactory() { @Override public ExtensibleConfigurationPersister createConfigurationPersister(ServerEnvironment serverEnvironment, ExecutorService executorService) { ExtensibleConfigurationPersister delegate; delegate = persisterFactory.createConfigurationPersister(serverEnvironment, executorService); configuration.getExtensionRegistry().setWriterRegistry(delegate); return delegate; } }); configuration.setModuleLoader(Module.getBootModuleLoader()); List<ServiceActivator> activators = new ArrayList<>(); //activators.add(new ContentProviderServiceActivator(contentProvider)); activators.addAll(additionalActivators); serviceContainer = bootstrap.startup(configuration, activators).get(); return serviceContainer; }
[ "public", "ServiceContainer", "start", "(", "final", "List", "<", "ModelNode", ">", "containerDefinition", ",", "Collection", "<", "ServiceActivator", ">", "additionalActivators", ")", "throws", "ExecutionException", ",", "InterruptedException", ",", "ModuleLoadException", "{", "final", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "java", ".", "util", ".", "logging", ".", "LogManager", ".", "getLogManager", "(", ")", ".", "getClass", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "\"org.jboss.logmanager.LogManager\"", ")", ")", "{", "try", "{", "Class", ".", "forName", "(", "org", ".", "jboss", ".", "logmanager", ".", "handlers", ".", "ConsoleHandler", ".", "class", ".", "getName", "(", ")", ",", "true", ",", "org", ".", "jboss", ".", "logmanager", ".", "handlers", ".", "ConsoleHandler", ".", "class", ".", "getClassLoader", "(", ")", ")", ";", "// Install JBoss Stdio to avoid any nasty crosstalk, after command line arguments are processed.", "StdioContext", ".", "install", "(", ")", ";", "final", "StdioContext", "context", "=", "StdioContext", ".", "create", "(", "new", "NullInputStream", "(", ")", ",", "new", "LoggingOutputStream", "(", "org", ".", "jboss", ".", "logmanager", ".", "Logger", ".", "getLogger", "(", "\"stdout\"", ")", ",", "org", ".", "jboss", ".", "logmanager", ".", "Level", ".", "INFO", ")", ",", "new", "LoggingOutputStream", "(", "org", ".", "jboss", ".", "logmanager", ".", "Logger", ".", "getLogger", "(", "\"stderr\"", ")", ",", "org", ".", "jboss", ".", "logmanager", ".", "Level", ".", "ERROR", ")", ")", ";", "StdioContext", ".", "setStdioContextSelector", "(", "new", "SimpleStdioContextSelector", "(", "context", ")", ")", ";", "}", "catch", "(", "Throwable", "ignored", ")", "{", "}", "}", "Module", ".", "registerURLStreamHandlerFactoryModule", "(", "Module", ".", "getBootModuleLoader", "(", ")", ".", "loadModule", "(", "\"org.jboss.vfs\"", ")", ")", ";", "ServerEnvironment", "serverEnvironment", "=", "determineEnvironment", "(", "WildFlySecurityManager", ".", "getSystemPropertiesPrivileged", "(", ")", ",", "WildFlySecurityManager", ".", "getSystemEnvironmentPrivileged", "(", ")", ",", "ServerEnvironment", ".", "LaunchType", ".", "SELF_CONTAINED", ",", "startTime", ")", ";", "final", "Bootstrap", "bootstrap", "=", "Bootstrap", ".", "Factory", ".", "newInstance", "(", ")", ";", "final", "Bootstrap", ".", "Configuration", "configuration", "=", "new", "Bootstrap", ".", "Configuration", "(", "serverEnvironment", ")", ";", "configuration", ".", "setConfigurationPersisterFactory", "(", "new", "Bootstrap", ".", "ConfigurationPersisterFactory", "(", ")", "{", "@", "Override", "public", "ExtensibleConfigurationPersister", "createConfigurationPersister", "(", "ServerEnvironment", "serverEnvironment", ",", "ExecutorService", "executorService", ")", "{", "ExtensibleConfigurationPersister", "delegate", ";", "delegate", "=", "persisterFactory", ".", "createConfigurationPersister", "(", "serverEnvironment", ",", "executorService", ")", ";", "configuration", ".", "getExtensionRegistry", "(", ")", ".", "setWriterRegistry", "(", "delegate", ")", ";", "return", "delegate", ";", "}", "}", ")", ";", "configuration", ".", "setModuleLoader", "(", "Module", ".", "getBootModuleLoader", "(", ")", ")", ";", "List", "<", "ServiceActivator", ">", "activators", "=", "new", "ArrayList", "<>", "(", ")", ";", "//activators.add(new ContentProviderServiceActivator(contentProvider));", "activators", ".", "addAll", "(", "additionalActivators", ")", ";", "serviceContainer", "=", "bootstrap", ".", "startup", "(", "configuration", ",", "activators", ")", ".", "get", "(", ")", ";", "return", "serviceContainer", ";", "}" ]
The main method. @param containerDefinition The container definition.
[ "The", "main", "method", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/internal/wildfly/SelfContainedContainer.java#L95-L145
alkacon/opencms-core
src/org/opencms/main/CmsSystemInfo.java
CmsSystemInfo.initVersion
private void initVersion() { // initialize version information with static defaults m_versionNumber = DEFAULT_VERSION_NUMBER; m_versionId = DEFAULT_VERSION_ID; m_version = "OpenCms/" + m_versionNumber; m_buildInfo = Collections.emptyMap(); // read the version-informations from properties Properties props = new Properties(); try { props.load(this.getClass().getClassLoader().getResourceAsStream("org/opencms/main/version.properties")); } catch (Throwable t) { // no properties found - we just use the defaults return; } // initialize OpenCms version information from the property values m_versionNumber = props.getProperty("version.number", DEFAULT_VERSION_NUMBER); m_versionId = props.getProperty("version.id", DEFAULT_VERSION_ID); m_version = "OpenCms/" + m_versionNumber; m_buildInfo = new TreeMap<String, BuildInfoItem>(); // iterate the properties and generate the build information from the entries for (String key : props.stringPropertyNames()) { if (!"version.number".equals(key) && !"version.id".equals(key) && !key.startsWith("nicename")) { String value = props.getProperty(key); String nicename = props.getProperty("nicename." + key, key); m_buildInfo.put(key, new BuildInfoItem(value, nicename, key)); } } // make the map unmodifiable m_buildInfo = Collections.unmodifiableMap(m_buildInfo); }
java
private void initVersion() { // initialize version information with static defaults m_versionNumber = DEFAULT_VERSION_NUMBER; m_versionId = DEFAULT_VERSION_ID; m_version = "OpenCms/" + m_versionNumber; m_buildInfo = Collections.emptyMap(); // read the version-informations from properties Properties props = new Properties(); try { props.load(this.getClass().getClassLoader().getResourceAsStream("org/opencms/main/version.properties")); } catch (Throwable t) { // no properties found - we just use the defaults return; } // initialize OpenCms version information from the property values m_versionNumber = props.getProperty("version.number", DEFAULT_VERSION_NUMBER); m_versionId = props.getProperty("version.id", DEFAULT_VERSION_ID); m_version = "OpenCms/" + m_versionNumber; m_buildInfo = new TreeMap<String, BuildInfoItem>(); // iterate the properties and generate the build information from the entries for (String key : props.stringPropertyNames()) { if (!"version.number".equals(key) && !"version.id".equals(key) && !key.startsWith("nicename")) { String value = props.getProperty(key); String nicename = props.getProperty("nicename." + key, key); m_buildInfo.put(key, new BuildInfoItem(value, nicename, key)); } } // make the map unmodifiable m_buildInfo = Collections.unmodifiableMap(m_buildInfo); }
[ "private", "void", "initVersion", "(", ")", "{", "// initialize version information with static defaults", "m_versionNumber", "=", "DEFAULT_VERSION_NUMBER", ";", "m_versionId", "=", "DEFAULT_VERSION_ID", ";", "m_version", "=", "\"OpenCms/\"", "+", "m_versionNumber", ";", "m_buildInfo", "=", "Collections", ".", "emptyMap", "(", ")", ";", "// read the version-informations from properties", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "try", "{", "props", ".", "load", "(", "this", ".", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "\"org/opencms/main/version.properties\"", ")", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "// no properties found - we just use the defaults", "return", ";", "}", "// initialize OpenCms version information from the property values", "m_versionNumber", "=", "props", ".", "getProperty", "(", "\"version.number\"", ",", "DEFAULT_VERSION_NUMBER", ")", ";", "m_versionId", "=", "props", ".", "getProperty", "(", "\"version.id\"", ",", "DEFAULT_VERSION_ID", ")", ";", "m_version", "=", "\"OpenCms/\"", "+", "m_versionNumber", ";", "m_buildInfo", "=", "new", "TreeMap", "<", "String", ",", "BuildInfoItem", ">", "(", ")", ";", "// iterate the properties and generate the build information from the entries", "for", "(", "String", "key", ":", "props", ".", "stringPropertyNames", "(", ")", ")", "{", "if", "(", "!", "\"version.number\"", ".", "equals", "(", "key", ")", "&&", "!", "\"version.id\"", ".", "equals", "(", "key", ")", "&&", "!", "key", ".", "startsWith", "(", "\"nicename\"", ")", ")", "{", "String", "value", "=", "props", ".", "getProperty", "(", "key", ")", ";", "String", "nicename", "=", "props", ".", "getProperty", "(", "\"nicename.\"", "+", "key", ",", "key", ")", ";", "m_buildInfo", ".", "put", "(", "key", ",", "new", "BuildInfoItem", "(", "value", ",", "nicename", ",", "key", ")", ")", ";", "}", "}", "// make the map unmodifiable", "m_buildInfo", "=", "Collections", ".", "unmodifiableMap", "(", "m_buildInfo", ")", ";", "}" ]
Initializes the version for this OpenCms, will be called by {@link OpenCmsServlet} or {@link CmsShell} upon system startup.<p>
[ "Initializes", "the", "version", "for", "this", "OpenCms", "will", "be", "called", "by", "{" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsSystemInfo.java#L850-L881
DDTH/ddth-redis
src/main/java/com/github/ddth/redis/RedisClientFactory.java
RedisClientFactory.getRedisClient
public IRedisClient getRedisClient(String host) { return getRedisClient(host, IRedisClient.DEFAULT_REDIS_PORT, null, null); }
java
public IRedisClient getRedisClient(String host) { return getRedisClient(host, IRedisClient.DEFAULT_REDIS_PORT, null, null); }
[ "public", "IRedisClient", "getRedisClient", "(", "String", "host", ")", "{", "return", "getRedisClient", "(", "host", ",", "IRedisClient", ".", "DEFAULT_REDIS_PORT", ",", "null", ",", "null", ")", ";", "}" ]
Gets or Creates a {@link IRedisClient} object. @param host @return
[ "Gets", "or", "Creates", "a", "{", "@link", "IRedisClient", "}", "object", "." ]
train
https://github.com/DDTH/ddth-redis/blob/7e6abc3e43c9efe7e9c293d421c94227253ded87/src/main/java/com/github/ddth/redis/RedisClientFactory.java#L151-L153
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.deleteDataLakeStoreAccountAsync
public Observable<Void> deleteDataLakeStoreAccountAsync(String resourceGroupName, String accountName, String dataLakeStoreAccountName) { return deleteDataLakeStoreAccountWithServiceResponseAsync(resourceGroupName, accountName, dataLakeStoreAccountName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> deleteDataLakeStoreAccountAsync(String resourceGroupName, String accountName, String dataLakeStoreAccountName) { return deleteDataLakeStoreAccountWithServiceResponseAsync(resourceGroupName, accountName, dataLakeStoreAccountName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "deleteDataLakeStoreAccountAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "dataLakeStoreAccountName", ")", "{", "return", "deleteDataLakeStoreAccountWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "dataLakeStoreAccountName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates the Data Lake Analytics account specified to remove the specified Data Lake Store account. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param accountName The name of the Data Lake Analytics account from which to remove the Data Lake Store account. @param dataLakeStoreAccountName The name of the Data Lake Store account to remove @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Updates", "the", "Data", "Lake", "Analytics", "account", "specified", "to", "remove", "the", "specified", "Data", "Lake", "Store", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L1066-L1073
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.isAllowedTo
public boolean isAllowedTo(String subjectid, String resourcePath, String httpMethod) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || StringUtils.isBlank(httpMethod)) { return false; } resourcePath = Utils.urlEncode(resourcePath); String url = Utils.formatMessage("_permissions/{0}/{1}/{2}", subjectid, resourcePath, httpMethod); Boolean result = getEntity(invokeGet(url, null), Boolean.class); return result != null && result; }
java
public boolean isAllowedTo(String subjectid, String resourcePath, String httpMethod) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || StringUtils.isBlank(httpMethod)) { return false; } resourcePath = Utils.urlEncode(resourcePath); String url = Utils.formatMessage("_permissions/{0}/{1}/{2}", subjectid, resourcePath, httpMethod); Boolean result = getEntity(invokeGet(url, null), Boolean.class); return result != null && result; }
[ "public", "boolean", "isAllowedTo", "(", "String", "subjectid", ",", "String", "resourcePath", ",", "String", "httpMethod", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "subjectid", ")", "||", "StringUtils", ".", "isBlank", "(", "resourcePath", ")", "||", "StringUtils", ".", "isBlank", "(", "httpMethod", ")", ")", "{", "return", "false", ";", "}", "resourcePath", "=", "Utils", ".", "urlEncode", "(", "resourcePath", ")", ";", "String", "url", "=", "Utils", ".", "formatMessage", "(", "\"_permissions/{0}/{1}/{2}\"", ",", "subjectid", ",", "resourcePath", ",", "httpMethod", ")", ";", "Boolean", "result", "=", "getEntity", "(", "invokeGet", "(", "url", ",", "null", ")", ",", "Boolean", ".", "class", ")", ";", "return", "result", "!=", "null", "&&", "result", ";", "}" ]
Checks if a subject is allowed to call method X on resource Y. @param subjectid subject id @param resourcePath resource path or object type @param httpMethod HTTP method name @return true if allowed
[ "Checks", "if", "a", "subject", "is", "allowed", "to", "call", "method", "X", "on", "resource", "Y", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1491-L1499
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/parsing/ParserUtil.java
ParserUtil.parseHeaders
public static String parseHeaders(String commandLine, final CommandLineParser.CallbackHandler handler, CommandContext ctx) throws CommandFormatException { if (commandLine == null) { return null; } SubstitutedLine sl = parseHeadersLine(commandLine, handler, ctx); return sl == null ? null : sl.getSubstitued(); }
java
public static String parseHeaders(String commandLine, final CommandLineParser.CallbackHandler handler, CommandContext ctx) throws CommandFormatException { if (commandLine == null) { return null; } SubstitutedLine sl = parseHeadersLine(commandLine, handler, ctx); return sl == null ? null : sl.getSubstitued(); }
[ "public", "static", "String", "parseHeaders", "(", "String", "commandLine", ",", "final", "CommandLineParser", ".", "CallbackHandler", "handler", ",", "CommandContext", "ctx", ")", "throws", "CommandFormatException", "{", "if", "(", "commandLine", "==", "null", ")", "{", "return", "null", ";", "}", "SubstitutedLine", "sl", "=", "parseHeadersLine", "(", "commandLine", ",", "handler", ",", "ctx", ")", ";", "return", "sl", "==", "null", "?", "null", ":", "sl", ".", "getSubstitued", "(", ")", ";", "}" ]
Returns the string which was actually parsed with all the substitutions performed
[ "Returns", "the", "string", "which", "was", "actually", "parsed", "with", "all", "the", "substitutions", "performed" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/parsing/ParserUtil.java#L147-L153
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java
DefaultCookie.validateValue
@Deprecated protected String validateValue(String name, String value) { return validateAttributeValue(name, value); }
java
@Deprecated protected String validateValue(String name, String value) { return validateAttributeValue(name, value); }
[ "@", "Deprecated", "protected", "String", "validateValue", "(", "String", "name", ",", "String", "value", ")", "{", "return", "validateAttributeValue", "(", "name", ",", "value", ")", ";", "}" ]
Validate a cookie attribute value, throws a {@link IllegalArgumentException} otherwise. Only intended to be used by {@link io.netty.handler.codec.http.DefaultCookie}. @param name attribute name @param value attribute value @return the trimmed, validated attribute value @deprecated CookieUtil is package private, will be removed once old Cookie API is dropped
[ "Validate", "a", "cookie", "attribute", "value", "throws", "a", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java#L205-L208
kaazing/gateway
util/src/main/java/org/kaazing/gateway/util/scheduler/SchedulerProvider.java
SchedulerProvider.getScheduler
public synchronized ScheduledExecutorService getScheduler(final String purpose, boolean needDedicatedThread) { return needDedicatedThread ? new ManagedScheduledExecutorService(1, purpose, false) : sharedScheduler; }
java
public synchronized ScheduledExecutorService getScheduler(final String purpose, boolean needDedicatedThread) { return needDedicatedThread ? new ManagedScheduledExecutorService(1, purpose, false) : sharedScheduler; }
[ "public", "synchronized", "ScheduledExecutorService", "getScheduler", "(", "final", "String", "purpose", ",", "boolean", "needDedicatedThread", ")", "{", "return", "needDedicatedThread", "?", "new", "ManagedScheduledExecutorService", "(", "1", ",", "purpose", ",", "false", ")", ":", "sharedScheduler", ";", "}" ]
/* @param owner Object which will be using the scheduler (and shutting it down when the object is disposed) @param purpose short description of the purpose of the scheduler, will be set as the thread name if a dedicated thread is used @param needDedicatedThread set this to true to guarantee the scheduler will have its own dedicated thread. This is appropriate if the tasks that will be scheduled may take significant time, e.g. sending periodic keep alive messages to all sessions @return
[ "/", "*", "@param", "owner", "Object", "which", "will", "be", "using", "the", "scheduler", "(", "and", "shutting", "it", "down", "when", "the", "object", "is", "disposed", ")" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/scheduler/SchedulerProvider.java#L54-L56
samskivert/samskivert
src/main/java/com/samskivert/util/Invoker.java
Invoker.didInvokeUnit
protected void didInvokeUnit (Unit unit, long start) { // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); recordMetrics(key, duration); // report long runners long thresh = unit.getLongThreshold(); if (thresh == 0) { thresh = _longThreshold; } if (duration > thresh) { StringBuilder msg = new StringBuilder(); msg.append((duration >= 10*thresh) ? "Really long" : "Long"); msg.append(" invoker unit [unit=").append(unit); msg.append(" (").append(key).append("), time=").append(duration).append("ms"); if (unit.getDetail() != null) { msg.append(", detail=").append(unit.getDetail()); } log.warning(msg.append("].").toString()); } } }
java
protected void didInvokeUnit (Unit unit, long start) { // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); recordMetrics(key, duration); // report long runners long thresh = unit.getLongThreshold(); if (thresh == 0) { thresh = _longThreshold; } if (duration > thresh) { StringBuilder msg = new StringBuilder(); msg.append((duration >= 10*thresh) ? "Really long" : "Long"); msg.append(" invoker unit [unit=").append(unit); msg.append(" (").append(key).append("), time=").append(duration).append("ms"); if (unit.getDetail() != null) { msg.append(", detail=").append(unit.getDetail()); } log.warning(msg.append("].").toString()); } } }
[ "protected", "void", "didInvokeUnit", "(", "Unit", "unit", ",", "long", "start", ")", "{", "// track some performance metrics", "if", "(", "PERF_TRACK", ")", "{", "long", "duration", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "Object", "key", "=", "unit", ".", "getClass", "(", ")", ";", "recordMetrics", "(", "key", ",", "duration", ")", ";", "// report long runners", "long", "thresh", "=", "unit", ".", "getLongThreshold", "(", ")", ";", "if", "(", "thresh", "==", "0", ")", "{", "thresh", "=", "_longThreshold", ";", "}", "if", "(", "duration", ">", "thresh", ")", "{", "StringBuilder", "msg", "=", "new", "StringBuilder", "(", ")", ";", "msg", ".", "append", "(", "(", "duration", ">=", "10", "*", "thresh", ")", "?", "\"Really long\"", ":", "\"Long\"", ")", ";", "msg", ".", "append", "(", "\" invoker unit [unit=\"", ")", ".", "append", "(", "unit", ")", ";", "msg", ".", "append", "(", "\" (\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"), time=\"", ")", ".", "append", "(", "duration", ")", ".", "append", "(", "\"ms\"", ")", ";", "if", "(", "unit", ".", "getDetail", "(", ")", "!=", "null", ")", "{", "msg", ".", "append", "(", "\", detail=\"", ")", ".", "append", "(", "unit", ".", "getDetail", "(", ")", ")", ";", "}", "log", ".", "warning", "(", "msg", ".", "append", "(", "\"].\"", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Called before we process an invoker unit. @param unit the unit about to be invoked. @param start a timestamp recorded immediately before invocation if {@link #PERF_TRACK} is enabled, 0L otherwise.
[ "Called", "before", "we", "process", "an", "invoker", "unit", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/Invoker.java#L276-L300
orbisgis/h2gis
h2gis-utilities/src/main/java/org/h2gis/utilities/jts_utils/CoordinateUtils.java
CoordinateUtils.vectorIntersection
public static Coordinate vectorIntersection(Coordinate p1, Vector3D v1, Coordinate p2, Vector3D v2) { double delta; Coordinate i = null; // Cramer's rule for compute intersection of two planes delta = v1.getX() * (-v2.getY()) - (-v1.getY()) * v2.getX(); if (delta != 0) { double k = ((p2.x - p1.x) * (-v2.getY()) - (p2.y - p1.y) * (-v2.getX())) / delta; // Fix precision problem with big decimal i = new Coordinate(p1.x + k * v1.getX(), p1.y + k * v1.getY(), p1.z + k * v1.getZ()); if(new LineSegment(p1, new Coordinate(p1.x + v1.getX(), p1.y + v1.getY())).projectionFactor(i) < 0 || new LineSegment(p2, new Coordinate(p2.x + v2.getX(), p2.y + v2.getY())).projectionFactor(i) < 0) { return null; } } return i; }
java
public static Coordinate vectorIntersection(Coordinate p1, Vector3D v1, Coordinate p2, Vector3D v2) { double delta; Coordinate i = null; // Cramer's rule for compute intersection of two planes delta = v1.getX() * (-v2.getY()) - (-v1.getY()) * v2.getX(); if (delta != 0) { double k = ((p2.x - p1.x) * (-v2.getY()) - (p2.y - p1.y) * (-v2.getX())) / delta; // Fix precision problem with big decimal i = new Coordinate(p1.x + k * v1.getX(), p1.y + k * v1.getY(), p1.z + k * v1.getZ()); if(new LineSegment(p1, new Coordinate(p1.x + v1.getX(), p1.y + v1.getY())).projectionFactor(i) < 0 || new LineSegment(p2, new Coordinate(p2.x + v2.getX(), p2.y + v2.getY())).projectionFactor(i) < 0) { return null; } } return i; }
[ "public", "static", "Coordinate", "vectorIntersection", "(", "Coordinate", "p1", ",", "Vector3D", "v1", ",", "Coordinate", "p2", ",", "Vector3D", "v2", ")", "{", "double", "delta", ";", "Coordinate", "i", "=", "null", ";", "// Cramer's rule for compute intersection of two planes", "delta", "=", "v1", ".", "getX", "(", ")", "*", "(", "-", "v2", ".", "getY", "(", ")", ")", "-", "(", "-", "v1", ".", "getY", "(", ")", ")", "*", "v2", ".", "getX", "(", ")", ";", "if", "(", "delta", "!=", "0", ")", "{", "double", "k", "=", "(", "(", "p2", ".", "x", "-", "p1", ".", "x", ")", "*", "(", "-", "v2", ".", "getY", "(", ")", ")", "-", "(", "p2", ".", "y", "-", "p1", ".", "y", ")", "*", "(", "-", "v2", ".", "getX", "(", ")", ")", ")", "/", "delta", ";", "// Fix precision problem with big decimal", "i", "=", "new", "Coordinate", "(", "p1", ".", "x", "+", "k", "*", "v1", ".", "getX", "(", ")", ",", "p1", ".", "y", "+", "k", "*", "v1", ".", "getY", "(", ")", ",", "p1", ".", "z", "+", "k", "*", "v1", ".", "getZ", "(", ")", ")", ";", "if", "(", "new", "LineSegment", "(", "p1", ",", "new", "Coordinate", "(", "p1", ".", "x", "+", "v1", ".", "getX", "(", ")", ",", "p1", ".", "y", "+", "v1", ".", "getY", "(", ")", ")", ")", ".", "projectionFactor", "(", "i", ")", "<", "0", "||", "new", "LineSegment", "(", "p2", ",", "new", "Coordinate", "(", "p2", ".", "x", "+", "v2", ".", "getX", "(", ")", ",", "p2", ".", "y", "+", "v2", ".", "getY", "(", ")", ")", ")", ".", "projectionFactor", "(", "i", ")", "<", "0", ")", "{", "return", "null", ";", "}", "}", "return", "i", ";", "}" ]
Compute intersection point of two vectors @param p1 Origin point @param v1 Direction from p1 @param p2 Origin point 2 @param v2 Direction of p2 @return Null if vectors are collinear or if intersection is done behind one of origin point
[ "Compute", "intersection", "point", "of", "two", "vectors" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-utilities/src/main/java/org/h2gis/utilities/jts_utils/CoordinateUtils.java#L124-L139
thombergs/docx-stamper
src/main/java/org/wickedsource/docxstamper/DocxStamperConfiguration.java
DocxStamperConfiguration.exposeInterfaceToExpressionLanguage
public DocxStamperConfiguration exposeInterfaceToExpressionLanguage(Class<?> interfaceClass, Object implementation) { this.expressionFunctions.put(interfaceClass, implementation); return this; }
java
public DocxStamperConfiguration exposeInterfaceToExpressionLanguage(Class<?> interfaceClass, Object implementation) { this.expressionFunctions.put(interfaceClass, implementation); return this; }
[ "public", "DocxStamperConfiguration", "exposeInterfaceToExpressionLanguage", "(", "Class", "<", "?", ">", "interfaceClass", ",", "Object", "implementation", ")", "{", "this", ".", "expressionFunctions", ".", "put", "(", "interfaceClass", ",", "implementation", ")", ";", "return", "this", ";", "}" ]
Exposes all methods of a given interface to the expression language. @param interfaceClass the interface whose methods should be exposed in the expression language. @param implementation the implementation that should be called to evaluate invocations of the interface methods within the expression language. Must implement the interface above.
[ "Exposes", "all", "methods", "of", "a", "given", "interface", "to", "the", "expression", "language", "." ]
train
https://github.com/thombergs/docx-stamper/blob/f1a7e3e92a59abaffac299532fe49450c3b041eb/src/main/java/org/wickedsource/docxstamper/DocxStamperConfiguration.java#L106-L109
GII/broccoli
broccoli-owls/src/main/java/com/hi3project/broccoli/bsdf/impl/owl/OWLValueObject.java
OWLValueObject.buildFromCollection
public static OWLValueObject buildFromCollection(OWLModel model, Collection col) throws NotYetImplementedException, OWLTranslationException { if (col.isEmpty()) { return null; } return buildFromClasAndCollection(model, OWLURIClass.from(col.iterator().next()), col); }
java
public static OWLValueObject buildFromCollection(OWLModel model, Collection col) throws NotYetImplementedException, OWLTranslationException { if (col.isEmpty()) { return null; } return buildFromClasAndCollection(model, OWLURIClass.from(col.iterator().next()), col); }
[ "public", "static", "OWLValueObject", "buildFromCollection", "(", "OWLModel", "model", ",", "Collection", "col", ")", "throws", "NotYetImplementedException", ",", "OWLTranslationException", "{", "if", "(", "col", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "buildFromClasAndCollection", "(", "model", ",", "OWLURIClass", ".", "from", "(", "col", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ",", "col", ")", ";", "}" ]
Builds an instance, from a given collection @param model @param col @return @throws NotYetImplementedException @throws OWLTranslationException
[ "Builds", "an", "instance", "from", "a", "given", "collection" ]
train
https://github.com/GII/broccoli/blob/a3033a90322cbcee4dc0f1719143b84b822bc4ba/broccoli-owls/src/main/java/com/hi3project/broccoli/bsdf/impl/owl/OWLValueObject.java#L159-L164
baratine/baratine
framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java
InHamp.readStreamCancel
private void readStreamCancel(InH3 hIn, HeadersAmp headers) throws IOException { ServiceRefAmp serviceRef = readToAddress(hIn); GatewayReply from = readFromAddress(hIn); long qid = hIn.readLong(); if (log.isLoggable(_logLevel)) { log.log(_logLevel, "stream-cancel-r " + from + "," + qid + " (in " + this + ")" + "\n {id:" + qid + ", to:" + serviceRef + "," + headers + "}"); } from.streamCancel(qid); }
java
private void readStreamCancel(InH3 hIn, HeadersAmp headers) throws IOException { ServiceRefAmp serviceRef = readToAddress(hIn); GatewayReply from = readFromAddress(hIn); long qid = hIn.readLong(); if (log.isLoggable(_logLevel)) { log.log(_logLevel, "stream-cancel-r " + from + "," + qid + " (in " + this + ")" + "\n {id:" + qid + ", to:" + serviceRef + "," + headers + "}"); } from.streamCancel(qid); }
[ "private", "void", "readStreamCancel", "(", "InH3", "hIn", ",", "HeadersAmp", "headers", ")", "throws", "IOException", "{", "ServiceRefAmp", "serviceRef", "=", "readToAddress", "(", "hIn", ")", ";", "GatewayReply", "from", "=", "readFromAddress", "(", "hIn", ")", ";", "long", "qid", "=", "hIn", ".", "readLong", "(", ")", ";", "if", "(", "log", ".", "isLoggable", "(", "_logLevel", ")", ")", "{", "log", ".", "log", "(", "_logLevel", ",", "\"stream-cancel-r \"", "+", "from", "+", "\",\"", "+", "qid", "+", "\" (in \"", "+", "this", "+", "\")\"", "+", "\"\\n {id:\"", "+", "qid", "+", "\", to:\"", "+", "serviceRef", "+", "\",\"", "+", "headers", "+", "\"}\"", ")", ";", "}", "from", ".", "streamCancel", "(", "qid", ")", ";", "}" ]
The stream result message is a partial or final result from the target's stream.
[ "The", "stream", "result", "message", "is", "a", "partial", "or", "final", "result", "from", "the", "target", "s", "stream", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java#L750-L765
mlhartme/jasmin
src/main/java/net/oneandone/jasmin/model/Repository.java
Repository.loadLibrary
public void loadLibrary(Resolver resolver, Node base, Node descriptor, Node properties) throws IOException { Source source; Module module; Library library; File file; addReload(descriptor); source = Source.load(properties, base); library = (Library) Library.TYPE.loadXml(descriptor).get(); autoFiles(resolver, library, source); for (net.oneandone.jasmin.descriptor.Module descriptorModule : library.modules()) { module = new Module(descriptorModule.getName(), source); notLinked.put(module, descriptorModule.dependencies()); for (Resource resource : descriptorModule.resources()) { file = resolver.resolve(source.classpathBase, resource); addReload(file); resolver.resolve(source.classpathBase, resource); module.files().add(file); } add(module); } }
java
public void loadLibrary(Resolver resolver, Node base, Node descriptor, Node properties) throws IOException { Source source; Module module; Library library; File file; addReload(descriptor); source = Source.load(properties, base); library = (Library) Library.TYPE.loadXml(descriptor).get(); autoFiles(resolver, library, source); for (net.oneandone.jasmin.descriptor.Module descriptorModule : library.modules()) { module = new Module(descriptorModule.getName(), source); notLinked.put(module, descriptorModule.dependencies()); for (Resource resource : descriptorModule.resources()) { file = resolver.resolve(source.classpathBase, resource); addReload(file); resolver.resolve(source.classpathBase, resource); module.files().add(file); } add(module); } }
[ "public", "void", "loadLibrary", "(", "Resolver", "resolver", ",", "Node", "base", ",", "Node", "descriptor", ",", "Node", "properties", ")", "throws", "IOException", "{", "Source", "source", ";", "Module", "module", ";", "Library", "library", ";", "File", "file", ";", "addReload", "(", "descriptor", ")", ";", "source", "=", "Source", ".", "load", "(", "properties", ",", "base", ")", ";", "library", "=", "(", "Library", ")", "Library", ".", "TYPE", ".", "loadXml", "(", "descriptor", ")", ".", "get", "(", ")", ";", "autoFiles", "(", "resolver", ",", "library", ",", "source", ")", ";", "for", "(", "net", ".", "oneandone", ".", "jasmin", ".", "descriptor", ".", "Module", "descriptorModule", ":", "library", ".", "modules", "(", ")", ")", "{", "module", "=", "new", "Module", "(", "descriptorModule", ".", "getName", "(", ")", ",", "source", ")", ";", "notLinked", ".", "put", "(", "module", ",", "descriptorModule", ".", "dependencies", "(", ")", ")", ";", "for", "(", "Resource", "resource", ":", "descriptorModule", ".", "resources", "(", ")", ")", "{", "file", "=", "resolver", ".", "resolve", "(", "source", ".", "classpathBase", ",", "resource", ")", ";", "addReload", "(", "file", ")", ";", "resolver", ".", "resolve", "(", "source", ".", "classpathBase", ",", "resource", ")", ";", "module", ".", "files", "(", ")", ".", "add", "(", "file", ")", ";", "}", "add", "(", "module", ")", ";", "}", "}" ]
Core method for loading. A library is a module or an application @param base jar file for module, docroot for application
[ "Core", "method", "for", "loading", ".", "A", "library", "is", "a", "module", "or", "an", "application" ]
train
https://github.com/mlhartme/jasmin/blob/1c44339a2555ae7ffb7d40fd3a7d80d81c3fc39d/src/main/java/net/oneandone/jasmin/model/Repository.java#L279-L300
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/geom/Circle.java
Circle.contains
public boolean contains(float x, float y) { float xDelta = x - getCenterX(), yDelta = y - getCenterY(); return xDelta * xDelta + yDelta * yDelta < getRadius() * getRadius(); }
java
public boolean contains(float x, float y) { float xDelta = x - getCenterX(), yDelta = y - getCenterY(); return xDelta * xDelta + yDelta * yDelta < getRadius() * getRadius(); }
[ "public", "boolean", "contains", "(", "float", "x", ",", "float", "y", ")", "{", "float", "xDelta", "=", "x", "-", "getCenterX", "(", ")", ",", "yDelta", "=", "y", "-", "getCenterY", "(", ")", ";", "return", "xDelta", "*", "xDelta", "+", "yDelta", "*", "yDelta", "<", "getRadius", "(", ")", "*", "getRadius", "(", ")", ";", "}" ]
Check if a point is contained by this circle @param x The x coordinate of the point to check @param y The y coorindate of the point to check @return True if the point is contained by this circle
[ "Check", "if", "a", "point", "is", "contained", "by", "this", "circle" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/geom/Circle.java#L129-L133
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelJsonFormatter.java
HpelJsonFormatter.addToJSON
static boolean addToJSON(StringBuilder sb, String name, String value, boolean jsonEscapeName, boolean jsonEscapeValue, boolean trim, boolean isFirstField) { // if name or value is null just return if (name == null || value == null) return false; // add comma if isFirstField == false if (!isFirstField) sb.append(","); // trim value if requested if (trim) value = value.trim(); // escape value if requested if (jsonEscapeValue) value = jsonEscape2(value); // escape name if requested if (jsonEscapeName) name = jsonEscape2(name); // append name : value to sb sb.append("\"" + name + "\":\"").append(value).append("\""); return true; }
java
static boolean addToJSON(StringBuilder sb, String name, String value, boolean jsonEscapeName, boolean jsonEscapeValue, boolean trim, boolean isFirstField) { // if name or value is null just return if (name == null || value == null) return false; // add comma if isFirstField == false if (!isFirstField) sb.append(","); // trim value if requested if (trim) value = value.trim(); // escape value if requested if (jsonEscapeValue) value = jsonEscape2(value); // escape name if requested if (jsonEscapeName) name = jsonEscape2(name); // append name : value to sb sb.append("\"" + name + "\":\"").append(value).append("\""); return true; }
[ "static", "boolean", "addToJSON", "(", "StringBuilder", "sb", ",", "String", "name", ",", "String", "value", ",", "boolean", "jsonEscapeName", ",", "boolean", "jsonEscapeValue", ",", "boolean", "trim", ",", "boolean", "isFirstField", ")", "{", "// if name or value is null just return", "if", "(", "name", "==", "null", "||", "value", "==", "null", ")", "return", "false", ";", "// add comma if isFirstField == false", "if", "(", "!", "isFirstField", ")", "sb", ".", "append", "(", "\",\"", ")", ";", "// trim value if requested", "if", "(", "trim", ")", "value", "=", "value", ".", "trim", "(", ")", ";", "// escape value if requested", "if", "(", "jsonEscapeValue", ")", "value", "=", "jsonEscape2", "(", "value", ")", ";", "// escape name if requested", "if", "(", "jsonEscapeName", ")", "name", "=", "jsonEscape2", "(", "name", ")", ";", "// append name : value to sb", "sb", ".", "append", "(", "\"\\\"\"", "+", "name", "+", "\"\\\":\\\"\"", ")", ".", "append", "(", "value", ")", ".", "append", "(", "\"\\\"\"", ")", ";", "return", "true", ";", "}" ]
/* returns true if name value pair was added to the string buffer
[ "/", "*", "returns", "true", "if", "name", "value", "pair", "was", "added", "to", "the", "string", "buffer" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelJsonFormatter.java#L123-L143
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java
AttributeDefinition.addResourceAttributeDescription
public ModelNode addResourceAttributeDescription(final ResourceBundle bundle, final String prefix, final ModelNode resourceDescription) { final ModelNode attr = getNoTextDescription(false); attr.get(ModelDescriptionConstants.DESCRIPTION).set(getAttributeTextDescription(bundle, prefix)); final ModelNode result = resourceDescription.get(ModelDescriptionConstants.ATTRIBUTES, getName()).set(attr); ModelNode deprecated = addDeprecatedInfo(result); if (deprecated != null) { deprecated.get(ModelDescriptionConstants.REASON).set(getAttributeDeprecatedDescription(bundle, prefix)); } addAccessConstraints(result, bundle.getLocale()); return result; }
java
public ModelNode addResourceAttributeDescription(final ResourceBundle bundle, final String prefix, final ModelNode resourceDescription) { final ModelNode attr = getNoTextDescription(false); attr.get(ModelDescriptionConstants.DESCRIPTION).set(getAttributeTextDescription(bundle, prefix)); final ModelNode result = resourceDescription.get(ModelDescriptionConstants.ATTRIBUTES, getName()).set(attr); ModelNode deprecated = addDeprecatedInfo(result); if (deprecated != null) { deprecated.get(ModelDescriptionConstants.REASON).set(getAttributeDeprecatedDescription(bundle, prefix)); } addAccessConstraints(result, bundle.getLocale()); return result; }
[ "public", "ModelNode", "addResourceAttributeDescription", "(", "final", "ResourceBundle", "bundle", ",", "final", "String", "prefix", ",", "final", "ModelNode", "resourceDescription", ")", "{", "final", "ModelNode", "attr", "=", "getNoTextDescription", "(", "false", ")", ";", "attr", ".", "get", "(", "ModelDescriptionConstants", ".", "DESCRIPTION", ")", ".", "set", "(", "getAttributeTextDescription", "(", "bundle", ",", "prefix", ")", ")", ";", "final", "ModelNode", "result", "=", "resourceDescription", ".", "get", "(", "ModelDescriptionConstants", ".", "ATTRIBUTES", ",", "getName", "(", ")", ")", ".", "set", "(", "attr", ")", ";", "ModelNode", "deprecated", "=", "addDeprecatedInfo", "(", "result", ")", ";", "if", "(", "deprecated", "!=", "null", ")", "{", "deprecated", ".", "get", "(", "ModelDescriptionConstants", ".", "REASON", ")", ".", "set", "(", "getAttributeDeprecatedDescription", "(", "bundle", ",", "prefix", ")", ")", ";", "}", "addAccessConstraints", "(", "result", ",", "bundle", ".", "getLocale", "(", ")", ")", ";", "return", "result", ";", "}" ]
Creates a returns a basic model node describing the attribute, after attaching it to the given overall resource description model node. The node describing the attribute is returned to make it easy to perform further modification. @param bundle resource bundle to use for text descriptions @param prefix prefix to prepend to the attribute name key when looking up descriptions @param resourceDescription the overall resource description @return the attribute description node
[ "Creates", "a", "returns", "a", "basic", "model", "node", "describing", "the", "attribute", "after", "attaching", "it", "to", "the", "given", "overall", "resource", "description", "model", "node", ".", "The", "node", "describing", "the", "attribute", "is", "returned", "to", "make", "it", "easy", "to", "perform", "further", "modification", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java#L774-L784
alkacon/opencms-core
src/org/opencms/ade/publish/CmsPublishListHelper.java
CmsPublishListHelper.adjustCmsObject
public static CmsObject adjustCmsObject(CmsObject cms, boolean online) throws CmsException { CmsObject result = OpenCms.initCmsObject(cms); if (online) { CmsProject onlineProject = cms.readProject(CmsProject.ONLINE_PROJECT_ID); result.getRequestContext().setCurrentProject(onlineProject); } result.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE); return result; }
java
public static CmsObject adjustCmsObject(CmsObject cms, boolean online) throws CmsException { CmsObject result = OpenCms.initCmsObject(cms); if (online) { CmsProject onlineProject = cms.readProject(CmsProject.ONLINE_PROJECT_ID); result.getRequestContext().setCurrentProject(onlineProject); } result.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE); return result; }
[ "public", "static", "CmsObject", "adjustCmsObject", "(", "CmsObject", "cms", ",", "boolean", "online", ")", "throws", "CmsException", "{", "CmsObject", "result", "=", "OpenCms", ".", "initCmsObject", "(", "cms", ")", ";", "if", "(", "online", ")", "{", "CmsProject", "onlineProject", "=", "cms", ".", "readProject", "(", "CmsProject", ".", "ONLINE_PROJECT_ID", ")", ";", "result", ".", "getRequestContext", "(", ")", ".", "setCurrentProject", "(", "onlineProject", ")", ";", "}", "result", ".", "getRequestContext", "(", ")", ".", "setRequestTime", "(", "CmsResource", ".", "DATE_RELEASED_EXPIRED_IGNORE", ")", ";", "return", "result", ";", "}" ]
Initializes a CmsObject based on the given one, but with adjusted project information and configured, such that release and expiration date are ignored.<p> @param cms the original CmsObject. @param online true if a CmsObject for the Online project should be returned @return the initialized CmsObject @throws CmsException if something goes wrong
[ "Initializes", "a", "CmsObject", "based", "on", "the", "given", "one", "but", "with", "adjusted", "project", "information", "and", "configured", "such", "that", "release", "and", "expiration", "date", "are", "ignored", ".", "<p", ">", "@param", "cms", "the", "original", "CmsObject", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/publish/CmsPublishListHelper.java#L56-L65
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/RequestClientOptions.java
RequestClientOptions.createUserAgentMarkerString
private String createUserAgentMarkerString(final String marker, String userAgent) { return marker.contains(userAgent) ? marker : marker + " " + userAgent; }
java
private String createUserAgentMarkerString(final String marker, String userAgent) { return marker.contains(userAgent) ? marker : marker + " " + userAgent; }
[ "private", "String", "createUserAgentMarkerString", "(", "final", "String", "marker", ",", "String", "userAgent", ")", "{", "return", "marker", ".", "contains", "(", "userAgent", ")", "?", "marker", ":", "marker", "+", "\" \"", "+", "userAgent", ";", "}" ]
Appends the given client marker string to the existing one and returns it.
[ "Appends", "the", "given", "client", "marker", "string", "to", "the", "existing", "one", "and", "returns", "it", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/RequestClientOptions.java#L97-L99
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceEncryptionProtectorsInner.java
ManagedInstanceEncryptionProtectorsInner.createOrUpdate
public ManagedInstanceEncryptionProtectorInner createOrUpdate(String resourceGroupName, String managedInstanceName, ManagedInstanceEncryptionProtectorInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).toBlocking().last().body(); }
java
public ManagedInstanceEncryptionProtectorInner createOrUpdate(String resourceGroupName, String managedInstanceName, ManagedInstanceEncryptionProtectorInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).toBlocking().last().body(); }
[ "public", "ManagedInstanceEncryptionProtectorInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "ManagedInstanceEncryptionProtectorInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates an existing encryption protector. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param parameters The requested encryption protector resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ManagedInstanceEncryptionProtectorInner object if successful.
[ "Updates", "an", "existing", "encryption", "protector", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceEncryptionProtectorsInner.java#L306-L308
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/instance/SimpleSlot.java
SimpleSlot.tryAssignPayload
@Override public boolean tryAssignPayload(Payload payload) { Preconditions.checkNotNull(payload); // check that we can actually run in this slot if (isCanceled()) { return false; } // atomically assign the vertex if (!PAYLOAD_UPDATER.compareAndSet(this, null, payload)) { return false; } // we need to do a double check that we were not cancelled in the meantime if (isCanceled()) { this.payload = null; return false; } return true; }
java
@Override public boolean tryAssignPayload(Payload payload) { Preconditions.checkNotNull(payload); // check that we can actually run in this slot if (isCanceled()) { return false; } // atomically assign the vertex if (!PAYLOAD_UPDATER.compareAndSet(this, null, payload)) { return false; } // we need to do a double check that we were not cancelled in the meantime if (isCanceled()) { this.payload = null; return false; } return true; }
[ "@", "Override", "public", "boolean", "tryAssignPayload", "(", "Payload", "payload", ")", "{", "Preconditions", ".", "checkNotNull", "(", "payload", ")", ";", "// check that we can actually run in this slot", "if", "(", "isCanceled", "(", ")", ")", "{", "return", "false", ";", "}", "// atomically assign the vertex", "if", "(", "!", "PAYLOAD_UPDATER", ".", "compareAndSet", "(", "this", ",", "null", ",", "payload", ")", ")", "{", "return", "false", ";", "}", "// we need to do a double check that we were not cancelled in the meantime", "if", "(", "isCanceled", "(", ")", ")", "{", "this", ".", "payload", "=", "null", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Atomically sets the executed vertex, if no vertex has been assigned to this slot so far. @param payload The vertex to assign to this slot. @return True, if the vertex was assigned, false, otherwise.
[ "Atomically", "sets", "the", "executed", "vertex", "if", "no", "vertex", "has", "been", "assigned", "to", "this", "slot", "so", "far", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/instance/SimpleSlot.java#L171-L192
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Partition.java
Partition.createListSubPartition
private static Partition createListSubPartition(SqlgGraph sqlgGraph, Partition parentPartition, String name, String in) { Preconditions.checkArgument(!parentPartition.getAbstractLabel().getSchema().isSqlgSchema(), "createPartition may not be called for \"%s\"", Topology.SQLG_SCHEMA); Partition partition = new Partition(sqlgGraph, parentPartition, name, in, PartitionType.NONE, null); partition.createListPartitionOnDb(); TopologyManager.addSubPartition(sqlgGraph, partition); partition.committed = false; return partition; }
java
private static Partition createListSubPartition(SqlgGraph sqlgGraph, Partition parentPartition, String name, String in) { Preconditions.checkArgument(!parentPartition.getAbstractLabel().getSchema().isSqlgSchema(), "createPartition may not be called for \"%s\"", Topology.SQLG_SCHEMA); Partition partition = new Partition(sqlgGraph, parentPartition, name, in, PartitionType.NONE, null); partition.createListPartitionOnDb(); TopologyManager.addSubPartition(sqlgGraph, partition); partition.committed = false; return partition; }
[ "private", "static", "Partition", "createListSubPartition", "(", "SqlgGraph", "sqlgGraph", ",", "Partition", "parentPartition", ",", "String", "name", ",", "String", "in", ")", "{", "Preconditions", ".", "checkArgument", "(", "!", "parentPartition", ".", "getAbstractLabel", "(", ")", ".", "getSchema", "(", ")", ".", "isSqlgSchema", "(", ")", ",", "\"createPartition may not be called for \\\"%s\\\"\"", ",", "Topology", ".", "SQLG_SCHEMA", ")", ";", "Partition", "partition", "=", "new", "Partition", "(", "sqlgGraph", ",", "parentPartition", ",", "name", ",", "in", ",", "PartitionType", ".", "NONE", ",", "null", ")", ";", "partition", ".", "createListPartitionOnDb", "(", ")", ";", "TopologyManager", ".", "addSubPartition", "(", "sqlgGraph", ",", "partition", ")", ";", "partition", ".", "committed", "=", "false", ";", "return", "partition", ";", "}" ]
Create a list partition on an existing {@link Partition} @param sqlgGraph @param parentPartition @param name @param in @return
[ "Create", "a", "list", "partition", "on", "an", "existing", "{", "@link", "Partition", "}" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Partition.java#L395-L402
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/expression/CustomFunctions.java
CustomFunctions.join
@SuppressWarnings({"rawtypes", "unchecked"}) public static String join(final Collection<?> collection, final String delimiter, final TextPrinter printer) { Objects.requireNonNull(printer); if(collection == null || collection.isEmpty()) { return ""; } String value = collection.stream() .map(v -> printer.print(v)) .collect(Collectors.joining(defaultString(delimiter))); return value; }
java
@SuppressWarnings({"rawtypes", "unchecked"}) public static String join(final Collection<?> collection, final String delimiter, final TextPrinter printer) { Objects.requireNonNull(printer); if(collection == null || collection.isEmpty()) { return ""; } String value = collection.stream() .map(v -> printer.print(v)) .collect(Collectors.joining(defaultString(delimiter))); return value; }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "static", "String", "join", "(", "final", "Collection", "<", "?", ">", "collection", ",", "final", "String", "delimiter", ",", "final", "TextPrinter", "printer", ")", "{", "Objects", ".", "requireNonNull", "(", "printer", ")", ";", "if", "(", "collection", "==", "null", "||", "collection", ".", "isEmpty", "(", ")", ")", "{", "return", "\"\"", ";", "}", "String", "value", "=", "collection", ".", "stream", "(", ")", ".", "map", "(", "v", "->", "printer", ".", "print", "(", "v", ")", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", "defaultString", "(", "delimiter", ")", ")", ")", ";", "return", "value", ";", "}" ]
コレクションの値を結合する。 @param collection 結合対象のコレクション @param delimiter 区切り文字 @param printer コレクションの要素の値のフォーマッタ @return 結合した文字列を返す。結合の対象のコレクションがnulの場合、空文字を返す。 @throws NullPointerException {@literal printer is null.}
[ "コレクションの値を結合する。" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/expression/CustomFunctions.java#L128-L142