repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/Sphere3d.java
Sphere3d.set
@Override public void set(Point3D center, double radius1) { """ Change the frame of the sphere. @param center @param radius1 """ this.cxProperty.set(center.getX()); this.cyProperty.set(center.getY()); this.czProperty.set(center.getZ()); this.radiusProperty.set(Math.abs(radius1)); }
java
@Override public void set(Point3D center, double radius1) { this.cxProperty.set(center.getX()); this.cyProperty.set(center.getY()); this.czProperty.set(center.getZ()); this.radiusProperty.set(Math.abs(radius1)); }
[ "@", "Override", "public", "void", "set", "(", "Point3D", "center", ",", "double", "radius1", ")", "{", "this", ".", "cxProperty", ".", "set", "(", "center", ".", "getX", "(", ")", ")", ";", "this", ".", "cyProperty", ".", "set", "(", "center", ".", "getY", "(", ")", ")", ";", "this", ".", "czProperty", ".", "set", "(", "center", ".", "getZ", "(", ")", ")", ";", "this", ".", "radiusProperty", ".", "set", "(", "Math", ".", "abs", "(", "radius1", ")", ")", ";", "}" ]
Change the frame of the sphere. @param center @param radius1
[ "Change", "the", "frame", "of", "the", "sphere", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Sphere3d.java#L132-L138
bwkimmel/java-util
src/main/java/ca/eandb/util/io/FileUtil.java
FileUtil.preOrderTraversal
public static boolean preOrderTraversal(File root, FileVisitor visitor) throws Exception { """ Walks a directory tree using pre-order traversal. The contents of a directory are visited after the directory itself is visited. @param root The <code>File</code> indicating the file or directory to walk. @param visitor The <code>FileVisitor</code> to use to visit files and directories while walking the tree. @return A value indicating whether the tree walk was completed without {@link FileVisitor#visit(File)} ever returning false. @throws Exception If {@link FileVisitor#visit(File)} threw an exception. @see FileVisitor#visit(File) """ if (!visitor.visit(root)) { return false; } if (root.isDirectory()) { for (File child : root.listFiles()) { if (!preOrderTraversal(child, visitor)) { return false; } } } return true; }
java
public static boolean preOrderTraversal(File root, FileVisitor visitor) throws Exception { if (!visitor.visit(root)) { return false; } if (root.isDirectory()) { for (File child : root.listFiles()) { if (!preOrderTraversal(child, visitor)) { return false; } } } return true; }
[ "public", "static", "boolean", "preOrderTraversal", "(", "File", "root", ",", "FileVisitor", "visitor", ")", "throws", "Exception", "{", "if", "(", "!", "visitor", ".", "visit", "(", "root", ")", ")", "{", "return", "false", ";", "}", "if", "(", "root", ".", "isDirectory", "(", ")", ")", "{", "for", "(", "File", "child", ":", "root", ".", "listFiles", "(", ")", ")", "{", "if", "(", "!", "preOrderTraversal", "(", "child", ",", "visitor", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Walks a directory tree using pre-order traversal. The contents of a directory are visited after the directory itself is visited. @param root The <code>File</code> indicating the file or directory to walk. @param visitor The <code>FileVisitor</code> to use to visit files and directories while walking the tree. @return A value indicating whether the tree walk was completed without {@link FileVisitor#visit(File)} ever returning false. @throws Exception If {@link FileVisitor#visit(File)} threw an exception. @see FileVisitor#visit(File)
[ "Walks", "a", "directory", "tree", "using", "pre", "-", "order", "traversal", ".", "The", "contents", "of", "a", "directory", "are", "visited", "after", "the", "directory", "itself", "is", "visited", "." ]
train
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/io/FileUtil.java#L253-L265
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.tracev
public void tracev(String format, Object param1) { """ Issue a log message with a level of TRACE using {@link java.text.MessageFormat}-style formatting. @param format the message format string @param param1 the sole parameter """ if (isEnabled(Level.TRACE)) { doLog(Level.TRACE, FQCN, format, new Object[] { param1 }, null); } }
java
public void tracev(String format, Object param1) { if (isEnabled(Level.TRACE)) { doLog(Level.TRACE, FQCN, format, new Object[] { param1 }, null); } }
[ "public", "void", "tracev", "(", "String", "format", ",", "Object", "param1", ")", "{", "if", "(", "isEnabled", "(", "Level", ".", "TRACE", ")", ")", "{", "doLog", "(", "Level", ".", "TRACE", ",", "FQCN", ",", "format", ",", "new", "Object", "[", "]", "{", "param1", "}", ",", "null", ")", ";", "}", "}" ]
Issue a log message with a level of TRACE using {@link java.text.MessageFormat}-style formatting. @param format the message format string @param param1 the sole parameter
[ "Issue", "a", "log", "message", "with", "a", "level", "of", "TRACE", "using", "{", "@link", "java", ".", "text", ".", "MessageFormat", "}", "-", "style", "formatting", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L184-L188
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/FlexibleLOF.java
FlexibleLOF.computeLOFs
protected void computeLOFs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore lrds, WritableDoubleDataStore lofs, DoubleMinMax lofminmax) { """ Computes the Local outlier factor (LOF) of the specified objects. @param knnq the precomputed neighborhood of the objects w.r.t. the reference distance @param ids IDs to process @param lrds Local reachability distances @param lofs Local outlier factor storage @param lofminmax Score minimum/maximum tracker """ FiniteProgress progressLOFs = LOG.isVerbose() ? new FiniteProgress("LOF_SCORE for objects", ids.size(), LOG) : null; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final double lof; final double lrdp = lrds.doubleValue(iter); final KNNList neighbors = knnq.getKNNForDBID(iter, krefer); if(!Double.isInfinite(lrdp)) { double sum = 0.; int count = 0; for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) { // skip the point itself if(DBIDUtil.equal(neighbor, iter)) { continue; } final double val = lrds.doubleValue(neighbor); sum += val; count++; if(Double.isInfinite(val)) { break; } } lof = sum / (lrdp * count); } else { lof = 1.0; } lofs.putDouble(iter, lof); // update minimum and maximum lofminmax.put(lof); LOG.incrementProcessed(progressLOFs); } LOG.ensureCompleted(progressLOFs); }
java
protected void computeLOFs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore lrds, WritableDoubleDataStore lofs, DoubleMinMax lofminmax) { FiniteProgress progressLOFs = LOG.isVerbose() ? new FiniteProgress("LOF_SCORE for objects", ids.size(), LOG) : null; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final double lof; final double lrdp = lrds.doubleValue(iter); final KNNList neighbors = knnq.getKNNForDBID(iter, krefer); if(!Double.isInfinite(lrdp)) { double sum = 0.; int count = 0; for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) { // skip the point itself if(DBIDUtil.equal(neighbor, iter)) { continue; } final double val = lrds.doubleValue(neighbor); sum += val; count++; if(Double.isInfinite(val)) { break; } } lof = sum / (lrdp * count); } else { lof = 1.0; } lofs.putDouble(iter, lof); // update minimum and maximum lofminmax.put(lof); LOG.incrementProcessed(progressLOFs); } LOG.ensureCompleted(progressLOFs); }
[ "protected", "void", "computeLOFs", "(", "KNNQuery", "<", "O", ">", "knnq", ",", "DBIDs", "ids", ",", "DoubleDataStore", "lrds", ",", "WritableDoubleDataStore", "lofs", ",", "DoubleMinMax", "lofminmax", ")", "{", "FiniteProgress", "progressLOFs", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "\"LOF_SCORE for objects\"", ",", "ids", ".", "size", "(", ")", ",", "LOG", ")", ":", "null", ";", "for", "(", "DBIDIter", "iter", "=", "ids", ".", "iter", "(", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "final", "double", "lof", ";", "final", "double", "lrdp", "=", "lrds", ".", "doubleValue", "(", "iter", ")", ";", "final", "KNNList", "neighbors", "=", "knnq", ".", "getKNNForDBID", "(", "iter", ",", "krefer", ")", ";", "if", "(", "!", "Double", ".", "isInfinite", "(", "lrdp", ")", ")", "{", "double", "sum", "=", "0.", ";", "int", "count", "=", "0", ";", "for", "(", "DBIDIter", "neighbor", "=", "neighbors", ".", "iter", "(", ")", ";", "neighbor", ".", "valid", "(", ")", ";", "neighbor", ".", "advance", "(", ")", ")", "{", "// skip the point itself", "if", "(", "DBIDUtil", ".", "equal", "(", "neighbor", ",", "iter", ")", ")", "{", "continue", ";", "}", "final", "double", "val", "=", "lrds", ".", "doubleValue", "(", "neighbor", ")", ";", "sum", "+=", "val", ";", "count", "++", ";", "if", "(", "Double", ".", "isInfinite", "(", "val", ")", ")", "{", "break", ";", "}", "}", "lof", "=", "sum", "/", "(", "lrdp", "*", "count", ")", ";", "}", "else", "{", "lof", "=", "1.0", ";", "}", "lofs", ".", "putDouble", "(", "iter", ",", "lof", ")", ";", "// update minimum and maximum", "lofminmax", ".", "put", "(", "lof", ")", ";", "LOG", ".", "incrementProcessed", "(", "progressLOFs", ")", ";", "}", "LOG", ".", "ensureCompleted", "(", "progressLOFs", ")", ";", "}" ]
Computes the Local outlier factor (LOF) of the specified objects. @param knnq the precomputed neighborhood of the objects w.r.t. the reference distance @param ids IDs to process @param lrds Local reachability distances @param lofs Local outlier factor storage @param lofminmax Score minimum/maximum tracker
[ "Computes", "the", "Local", "outlier", "factor", "(", "LOF", ")", "of", "the", "specified", "objects", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/FlexibleLOF.java#L282-L315
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java
DefaultAsyncSearchQueryResult.fromHttp400
@Deprecated public static AsyncSearchQueryResult fromHttp400(String payload) { """ A utility method to convert an HTTP 400 response from the search service into a proper {@link AsyncSearchQueryResult}. HTTP 400 indicates the request was malformed and couldn't be parsed on the server. As of Couchbase Server 4.5 such a response is a text/plain body that describes the parsing error. The whole body is emitted/thrown, wrapped in a {@link FtsMalformedRequestException}. @param payload the HTTP 400 response body describing the parsing failure. @return an {@link AsyncSearchQueryResult} that will emit a {@link FtsMalformedRequestException} when calling its {@link AsyncSearchQueryResult#hits() hits()} method. @deprecated FTS is still in BETA so the response format is likely to change in a future version, and be unified with the HTTP 200 response format. """ //dummy default values SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsMalformedRequestException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
java
@Deprecated public static AsyncSearchQueryResult fromHttp400(String payload) { //dummy default values SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsMalformedRequestException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
[ "@", "Deprecated", "public", "static", "AsyncSearchQueryResult", "fromHttp400", "(", "String", "payload", ")", "{", "//dummy default values", "SearchStatus", "status", "=", "new", "DefaultSearchStatus", "(", "1L", ",", "1L", ",", "0L", ")", ";", "SearchMetrics", "metrics", "=", "new", "DefaultSearchMetrics", "(", "0L", ",", "0L", ",", "0d", ")", ";", "return", "new", "DefaultAsyncSearchQueryResult", "(", "status", ",", "Observable", ".", "<", "SearchQueryRow", ">", "error", "(", "new", "FtsMalformedRequestException", "(", "payload", ")", ")", ",", "Observable", ".", "<", "FacetResult", ">", "empty", "(", ")", ",", "Observable", ".", "just", "(", "metrics", ")", ")", ";", "}" ]
A utility method to convert an HTTP 400 response from the search service into a proper {@link AsyncSearchQueryResult}. HTTP 400 indicates the request was malformed and couldn't be parsed on the server. As of Couchbase Server 4.5 such a response is a text/plain body that describes the parsing error. The whole body is emitted/thrown, wrapped in a {@link FtsMalformedRequestException}. @param payload the HTTP 400 response body describing the parsing failure. @return an {@link AsyncSearchQueryResult} that will emit a {@link FtsMalformedRequestException} when calling its {@link AsyncSearchQueryResult#hits() hits()} method. @deprecated FTS is still in BETA so the response format is likely to change in a future version, and be unified with the HTTP 200 response format.
[ "A", "utility", "method", "to", "convert", "an", "HTTP", "400", "response", "from", "the", "search", "service", "into", "a", "proper", "{", "@link", "AsyncSearchQueryResult", "}", ".", "HTTP", "400", "indicates", "the", "request", "was", "malformed", "and", "couldn", "t", "be", "parsed", "on", "the", "server", ".", "As", "of", "Couchbase", "Server", "4", ".", "5", "such", "a", "response", "is", "a", "text", "/", "plain", "body", "that", "describes", "the", "parsing", "error", ".", "The", "whole", "body", "is", "emitted", "/", "thrown", "wrapped", "in", "a", "{", "@link", "FtsMalformedRequestException", "}", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java#L262-L275
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java
GroupService.getGroupMember
public static IGroupMember getGroupMember(String key, Class<?> type) throws GroupsException { """ Returns an <code> IGroupMember </code> representing either a group or a portal entity. If the parm <code> type </code> is the group type, the <code> IGroupMember </code> is an <code> IEntityGroup </code> else it is an <code> IEntity </code> . """ /* * WARNING: The 'type' parameter is not the leafType; you're obligated * to say whether you want a group or a non-group (i.e. some type of * entity). In fact, the underlying implementation blindly instantiates * whatever you tell it to. */ LOGGER.trace("Invoking getEntity for key='{}', type='{}'", key, type); return instance().igetGroupMember(key, type); }
java
public static IGroupMember getGroupMember(String key, Class<?> type) throws GroupsException { /* * WARNING: The 'type' parameter is not the leafType; you're obligated * to say whether you want a group or a non-group (i.e. some type of * entity). In fact, the underlying implementation blindly instantiates * whatever you tell it to. */ LOGGER.trace("Invoking getEntity for key='{}', type='{}'", key, type); return instance().igetGroupMember(key, type); }
[ "public", "static", "IGroupMember", "getGroupMember", "(", "String", "key", ",", "Class", "<", "?", ">", "type", ")", "throws", "GroupsException", "{", "/*\n * WARNING: The 'type' parameter is not the leafType; you're obligated\n * to say whether you want a group or a non-group (i.e. some type of\n * entity). In fact, the underlying implementation blindly instantiates\n * whatever you tell it to.\n */", "LOGGER", ".", "trace", "(", "\"Invoking getEntity for key='{}', type='{}'\"", ",", "key", ",", "type", ")", ";", "return", "instance", "(", ")", ".", "igetGroupMember", "(", "key", ",", "type", ")", ";", "}" ]
Returns an <code> IGroupMember </code> representing either a group or a portal entity. If the parm <code> type </code> is the group type, the <code> IGroupMember </code> is an <code> IEntityGroup </code> else it is an <code> IEntity </code> .
[ "Returns", "an", "<code", ">", "IGroupMember", "<", "/", "code", ">", "representing", "either", "a", "group", "or", "a", "portal", "entity", ".", "If", "the", "parm", "<code", ">", "type", "<", "/", "code", ">", "is", "the", "group", "type", "the", "<code", ">", "IGroupMember", "<", "/", "code", ">", "is", "an", "<code", ">", "IEntityGroup", "<", "/", "code", ">", "else", "it", "is", "an", "<code", ">", "IEntity", "<", "/", "code", ">", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java#L171-L181
GwtMaterialDesign/gwt-material-addins
src/main/java/gwt/material/design/addins/client/scrollfire/MaterialScrollfire.java
MaterialScrollfire.apply
public static void apply(Element element, int offset, Functions.Func callback) { """ Executes callback method depending on how far into the page you've scrolled @param element Target element that is being tracked @param offset If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. @param callback The method to be called when the scrollfire is applied """ MaterialScrollfire scrollfire = new MaterialScrollfire(); scrollfire.setElement(element); scrollfire.setCallback(callback); scrollfire.setOffset(offset); scrollfire.apply(); }
java
public static void apply(Element element, int offset, Functions.Func callback) { MaterialScrollfire scrollfire = new MaterialScrollfire(); scrollfire.setElement(element); scrollfire.setCallback(callback); scrollfire.setOffset(offset); scrollfire.apply(); }
[ "public", "static", "void", "apply", "(", "Element", "element", ",", "int", "offset", ",", "Functions", ".", "Func", "callback", ")", "{", "MaterialScrollfire", "scrollfire", "=", "new", "MaterialScrollfire", "(", ")", ";", "scrollfire", ".", "setElement", "(", "element", ")", ";", "scrollfire", ".", "setCallback", "(", "callback", ")", ";", "scrollfire", ".", "setOffset", "(", "offset", ")", ";", "scrollfire", ".", "apply", "(", ")", ";", "}" ]
Executes callback method depending on how far into the page you've scrolled @param element Target element that is being tracked @param offset If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. @param callback The method to be called when the scrollfire is applied
[ "Executes", "callback", "method", "depending", "on", "how", "far", "into", "the", "page", "you", "ve", "scrolled" ]
train
https://github.com/GwtMaterialDesign/gwt-material-addins/blob/11aec9d92918225f70f936285d0ae94f2178c36e/src/main/java/gwt/material/design/addins/client/scrollfire/MaterialScrollfire.java#L108-L114
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/Environment.java
Environment.doGet
public void doGet(String url, HttpResponse response, Map<String, Object> headers, boolean followRedirect) { """ GETs content from URL. @param url url to get from. @param response response to store url and response value in. @param headers http headers to add. """ response.setRequest(url); httpClient.get(url, response, headers, followRedirect); }
java
public void doGet(String url, HttpResponse response, Map<String, Object> headers, boolean followRedirect) { response.setRequest(url); httpClient.get(url, response, headers, followRedirect); }
[ "public", "void", "doGet", "(", "String", "url", ",", "HttpResponse", "response", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "boolean", "followRedirect", ")", "{", "response", ".", "setRequest", "(", "url", ")", ";", "httpClient", ".", "get", "(", "url", ",", "response", ",", "headers", ",", "followRedirect", ")", ";", "}" ]
GETs content from URL. @param url url to get from. @param response response to store url and response value in. @param headers http headers to add.
[ "GETs", "content", "from", "URL", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L378-L381
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/wrapper/json/PJsonArray.java
PJsonArray.getString
@Override public final String getString(final int i) { """ Get the element at the index as a string. @param i the index of the element to access """ String val = this.array.optString(i, null); if (val == null) { throw new ObjectMissingException(this, "[" + i + "]"); } return val; }
java
@Override public final String getString(final int i) { String val = this.array.optString(i, null); if (val == null) { throw new ObjectMissingException(this, "[" + i + "]"); } return val; }
[ "@", "Override", "public", "final", "String", "getString", "(", "final", "int", "i", ")", "{", "String", "val", "=", "this", ".", "array", ".", "optString", "(", "i", ",", "null", ")", ";", "if", "(", "val", "==", "null", ")", "{", "throw", "new", "ObjectMissingException", "(", "this", ",", "\"[\"", "+", "i", "+", "\"]\"", ")", ";", "}", "return", "val", ";", "}" ]
Get the element at the index as a string. @param i the index of the element to access
[ "Get", "the", "element", "at", "the", "index", "as", "a", "string", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/wrapper/json/PJsonArray.java#L141-L148
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/workspace/VoiceApi.java
VoiceApi.redirectCall
public void redirectCall(String connId, String destination) throws WorkspaceApiException { """ Redirect a call to the specified destination. @param connId The connection ID of the call to redirect. @param destination The number where Workspace should redirect the call. """ this.redirectCall(connId, destination, null, null); }
java
public void redirectCall(String connId, String destination) throws WorkspaceApiException { this.redirectCall(connId, destination, null, null); }
[ "public", "void", "redirectCall", "(", "String", "connId", ",", "String", "destination", ")", "throws", "WorkspaceApiException", "{", "this", ".", "redirectCall", "(", "connId", ",", "destination", ",", "null", ",", "null", ")", ";", "}" ]
Redirect a call to the specified destination. @param connId The connection ID of the call to redirect. @param destination The number where Workspace should redirect the call.
[ "Redirect", "a", "call", "to", "the", "specified", "destination", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L1204-L1206
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsCreateModeSelectionDialog.java
CmsCreateModeSelectionDialog.showDialog
public static void showDialog(final CmsUUID referenceId, final AsyncCallback<String> createModeCallback) { """ Shows the dialog for the given collector list entry.<p> @param referenceId the structure id of the collector list entry @param createModeCallback the callback which should be called with the selected create mode """ CmsRpcAction<CmsListInfoBean> action = new CmsRpcAction<CmsListInfoBean>() { @Override public void execute() { start(0, true); CmsCoreProvider.getVfsService().getPageInfo(referenceId, this); } @Override protected void onResponse(CmsListInfoBean result) { stop(false); Boolean isFolder = result.getIsFolder(); if ((isFolder != null) && isFolder.booleanValue()) { createModeCallback.onSuccess(null); } else { (new CmsCreateModeSelectionDialog(result, createModeCallback)).center(); } } }; action.execute(); }
java
public static void showDialog(final CmsUUID referenceId, final AsyncCallback<String> createModeCallback) { CmsRpcAction<CmsListInfoBean> action = new CmsRpcAction<CmsListInfoBean>() { @Override public void execute() { start(0, true); CmsCoreProvider.getVfsService().getPageInfo(referenceId, this); } @Override protected void onResponse(CmsListInfoBean result) { stop(false); Boolean isFolder = result.getIsFolder(); if ((isFolder != null) && isFolder.booleanValue()) { createModeCallback.onSuccess(null); } else { (new CmsCreateModeSelectionDialog(result, createModeCallback)).center(); } } }; action.execute(); }
[ "public", "static", "void", "showDialog", "(", "final", "CmsUUID", "referenceId", ",", "final", "AsyncCallback", "<", "String", ">", "createModeCallback", ")", "{", "CmsRpcAction", "<", "CmsListInfoBean", ">", "action", "=", "new", "CmsRpcAction", "<", "CmsListInfoBean", ">", "(", ")", "{", "@", "Override", "public", "void", "execute", "(", ")", "{", "start", "(", "0", ",", "true", ")", ";", "CmsCoreProvider", ".", "getVfsService", "(", ")", ".", "getPageInfo", "(", "referenceId", ",", "this", ")", ";", "}", "@", "Override", "protected", "void", "onResponse", "(", "CmsListInfoBean", "result", ")", "{", "stop", "(", "false", ")", ";", "Boolean", "isFolder", "=", "result", ".", "getIsFolder", "(", ")", ";", "if", "(", "(", "isFolder", "!=", "null", ")", "&&", "isFolder", ".", "booleanValue", "(", ")", ")", "{", "createModeCallback", ".", "onSuccess", "(", "null", ")", ";", "}", "else", "{", "(", "new", "CmsCreateModeSelectionDialog", "(", "result", ",", "createModeCallback", ")", ")", ".", "center", "(", ")", ";", "}", "}", "}", ";", "action", ".", "execute", "(", ")", ";", "}" ]
Shows the dialog for the given collector list entry.<p> @param referenceId the structure id of the collector list entry @param createModeCallback the callback which should be called with the selected create mode
[ "Shows", "the", "dialog", "for", "the", "given", "collector", "list", "entry", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsCreateModeSelectionDialog.java#L88-L115
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.generateVpnProfile
public String generateVpnProfile(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { """ Generates VPN profile for P2S client of the virtual network gateway in the specified resource group. Used for IKEV2 and radius based authentication. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @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 String object if successful. """ return generateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().last().body(); }
java
public String generateVpnProfile(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return generateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().last().body(); }
[ "public", "String", "generateVpnProfile", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientParameters", "parameters", ")", "{", "return", "generateVpnProfileWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Generates VPN profile for P2S client of the virtual network gateway in the specified resource group. Used for IKEV2 and radius based authentication. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @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 String object if successful.
[ "Generates", "VPN", "profile", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", ".", "Used", "for", "IKEV2", "and", "radius", "based", "authentication", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L1632-L1634
jenkinsci/jenkins
core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java
UrlValidator.isValidPath
protected boolean isValidPath(String path) { """ Returns true if the path is valid. A <code>null</code> value is considered invalid. @param path Path value to validate. @return true if path is valid. """ if (path == null) { return false; } if (!PATH_PATTERN.matcher(path).matches()) { return false; } try { URI uri = new URI(null,null,path,null); String norm = uri.normalize().getPath(); if (norm.startsWith("/../") // Trying to go via the parent dir || norm.equals("/..")) { // Trying to go to the parent dir return false; } } catch (URISyntaxException e) { return false; } int slash2Count = countToken("//", path); if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) { return false; } return true; }
java
protected boolean isValidPath(String path) { if (path == null) { return false; } if (!PATH_PATTERN.matcher(path).matches()) { return false; } try { URI uri = new URI(null,null,path,null); String norm = uri.normalize().getPath(); if (norm.startsWith("/../") // Trying to go via the parent dir || norm.equals("/..")) { // Trying to go to the parent dir return false; } } catch (URISyntaxException e) { return false; } int slash2Count = countToken("//", path); if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) { return false; } return true; }
[ "protected", "boolean", "isValidPath", "(", "String", "path", ")", "{", "if", "(", "path", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "PATH_PATTERN", ".", "matcher", "(", "path", ")", ".", "matches", "(", ")", ")", "{", "return", "false", ";", "}", "try", "{", "URI", "uri", "=", "new", "URI", "(", "null", ",", "null", ",", "path", ",", "null", ")", ";", "String", "norm", "=", "uri", ".", "normalize", "(", ")", ".", "getPath", "(", ")", ";", "if", "(", "norm", ".", "startsWith", "(", "\"/../\"", ")", "// Trying to go via the parent dir ", "||", "norm", ".", "equals", "(", "\"/..\"", ")", ")", "{", "// Trying to go to the parent dir", "return", "false", ";", "}", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "return", "false", ";", "}", "int", "slash2Count", "=", "countToken", "(", "\"//\"", ",", "path", ")", ";", "if", "(", "isOff", "(", "ALLOW_2_SLASHES", ")", "&&", "(", "slash2Count", ">", "0", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if the path is valid. A <code>null</code> value is considered invalid. @param path Path value to validate. @return true if path is valid.
[ "Returns", "true", "if", "the", "path", "is", "valid", ".", "A", "<code", ">", "null<", "/", "code", ">", "value", "is", "considered", "invalid", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java#L450-L476
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqlchar
public static void sqlchar(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { """ char to chr translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens """ singleArgumentFunctionCall(buf, "chr(", "char", parsedArgs); }
java
public static void sqlchar(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "chr(", "char", parsedArgs); }
[ "public", "static", "void", "sqlchar", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"chr(\"", ",", "\"char\"", ",", "parsedArgs", ")", ";", "}" ]
char to chr translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "char", "to", "chr", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L144-L146
headius/invokebinder
src/main/java/com/headius/invokebinder/Binder.java
Binder.invokeSpecial
public MethodHandle invokeSpecial(MethodHandles.Lookup lookup, String name, Class<?> caller) throws NoSuchMethodException, IllegalAccessException { """ Apply the chain of transforms and bind them to a special method specified using the end signature plus the given class and name. The method will be retrieved using the given Lookup and must match the end signature exactly. If the final handle's type does not exactly match the initial type for this Binder, an additional cast will be attempted. @param lookup the MethodHandles.Lookup to use to look up the method @param name the name of the method to invoke @param caller the calling class @return the full handle chain, bound to the given method @throws java.lang.NoSuchMethodException if the method does not exist @throws java.lang.IllegalAccessException if the method is not accessible """ return invoke(lookup.findSpecial(type().parameterType(0), name, type().dropParameterTypes(0, 1), caller)); }
java
public MethodHandle invokeSpecial(MethodHandles.Lookup lookup, String name, Class<?> caller) throws NoSuchMethodException, IllegalAccessException { return invoke(lookup.findSpecial(type().parameterType(0), name, type().dropParameterTypes(0, 1), caller)); }
[ "public", "MethodHandle", "invokeSpecial", "(", "MethodHandles", ".", "Lookup", "lookup", ",", "String", "name", ",", "Class", "<", "?", ">", "caller", ")", "throws", "NoSuchMethodException", ",", "IllegalAccessException", "{", "return", "invoke", "(", "lookup", ".", "findSpecial", "(", "type", "(", ")", ".", "parameterType", "(", "0", ")", ",", "name", ",", "type", "(", ")", ".", "dropParameterTypes", "(", "0", ",", "1", ")", ",", "caller", ")", ")", ";", "}" ]
Apply the chain of transforms and bind them to a special method specified using the end signature plus the given class and name. The method will be retrieved using the given Lookup and must match the end signature exactly. If the final handle's type does not exactly match the initial type for this Binder, an additional cast will be attempted. @param lookup the MethodHandles.Lookup to use to look up the method @param name the name of the method to invoke @param caller the calling class @return the full handle chain, bound to the given method @throws java.lang.NoSuchMethodException if the method does not exist @throws java.lang.IllegalAccessException if the method is not accessible
[ "Apply", "the", "chain", "of", "transforms", "and", "bind", "them", "to", "a", "special", "method", "specified", "using", "the", "end", "signature", "plus", "the", "given", "class", "and", "name", ".", "The", "method", "will", "be", "retrieved", "using", "the", "given", "Lookup", "and", "must", "match", "the", "end", "signature", "exactly", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Binder.java#L1298-L1300
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/predicate/PropertyReference.java
PropertyReference.propertyRef
public static P<Object> propertyRef(Compare p,String columnName) { """ build a predicate from a compare operation and a column name @param p @param columnName @return """ return new RefP(p, new PropertyReference(columnName)); }
java
public static P<Object> propertyRef(Compare p,String columnName){ return new RefP(p, new PropertyReference(columnName)); }
[ "public", "static", "P", "<", "Object", ">", "propertyRef", "(", "Compare", "p", ",", "String", "columnName", ")", "{", "return", "new", "RefP", "(", "p", ",", "new", "PropertyReference", "(", "columnName", ")", ")", ";", "}" ]
build a predicate from a compare operation and a column name @param p @param columnName @return
[ "build", "a", "predicate", "from", "a", "compare", "operation", "and", "a", "column", "name" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/predicate/PropertyReference.java#L39-L41
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.cart_cartId_item_itemId_configuration_GET
public ArrayList<Long> cart_cartId_item_itemId_configuration_GET(String cartId, Long itemId, String label) throws IOException { """ Retrieve all configuration item of the cart item REST: GET /order/cart/{cartId}/item/{itemId}/configuration @param cartId [required] Cart identifier @param itemId [required] Product item identifier @param label [required] Filter the value of label property (=) """ String qPath = "/order/cart/{cartId}/item/{itemId}/configuration"; StringBuilder sb = path(qPath, cartId, itemId); query(sb, "label", label); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, t5); }
java
public ArrayList<Long> cart_cartId_item_itemId_configuration_GET(String cartId, Long itemId, String label) throws IOException { String qPath = "/order/cart/{cartId}/item/{itemId}/configuration"; StringBuilder sb = path(qPath, cartId, itemId); query(sb, "label", label); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, t5); }
[ "public", "ArrayList", "<", "Long", ">", "cart_cartId_item_itemId_configuration_GET", "(", "String", "cartId", ",", "Long", "itemId", ",", "String", "label", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/cart/{cartId}/item/{itemId}/configuration\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "cartId", ",", "itemId", ")", ";", "query", "(", "sb", ",", "\"label\"", ",", "label", ")", ";", "String", "resp", "=", "execN", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t5", ")", ";", "}" ]
Retrieve all configuration item of the cart item REST: GET /order/cart/{cartId}/item/{itemId}/configuration @param cartId [required] Cart identifier @param itemId [required] Product item identifier @param label [required] Filter the value of label property (=)
[ "Retrieve", "all", "configuration", "item", "of", "the", "cart", "item" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L8052-L8058
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java
TopologyBuilder.setBolt
public BoltDeclarer setBolt(String id, BaseWindowedBolt<Tuple> bolt, Number parallelism_hint) throws IllegalArgumentException { """ Define a new bolt in this topology. This defines a windowed bolt, intended for windowing operations. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the windowed bolt @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster. @return use the returned object to declare the inputs to this component @throws IllegalArgumentException if {@code parallelism_hint} is not positive """ boolean isEventTime = WindowAssigner.isEventTime(bolt.getWindowAssigner()); if (isEventTime && bolt.getTimestampExtractor() == null) { throw new IllegalArgumentException("timestamp extractor must be defined in event time!"); } return setBolt(id, new WindowedBoltExecutor(bolt), parallelism_hint); }
java
public BoltDeclarer setBolt(String id, BaseWindowedBolt<Tuple> bolt, Number parallelism_hint) throws IllegalArgumentException { boolean isEventTime = WindowAssigner.isEventTime(bolt.getWindowAssigner()); if (isEventTime && bolt.getTimestampExtractor() == null) { throw new IllegalArgumentException("timestamp extractor must be defined in event time!"); } return setBolt(id, new WindowedBoltExecutor(bolt), parallelism_hint); }
[ "public", "BoltDeclarer", "setBolt", "(", "String", "id", ",", "BaseWindowedBolt", "<", "Tuple", ">", "bolt", ",", "Number", "parallelism_hint", ")", "throws", "IllegalArgumentException", "{", "boolean", "isEventTime", "=", "WindowAssigner", ".", "isEventTime", "(", "bolt", ".", "getWindowAssigner", "(", ")", ")", ";", "if", "(", "isEventTime", "&&", "bolt", ".", "getTimestampExtractor", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"timestamp extractor must be defined in event time!\"", ")", ";", "}", "return", "setBolt", "(", "id", ",", "new", "WindowedBoltExecutor", "(", "bolt", ")", ",", "parallelism_hint", ")", ";", "}" ]
Define a new bolt in this topology. This defines a windowed bolt, intended for windowing operations. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the windowed bolt @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster. @return use the returned object to declare the inputs to this component @throws IllegalArgumentException if {@code parallelism_hint} is not positive
[ "Define", "a", "new", "bolt", "in", "this", "topology", ".", "This", "defines", "a", "windowed", "bolt", "intended", "for", "windowing", "operations", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java#L253-L260
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/ipv4/IPv4AddressSeqRange.java
IPv4AddressSeqRange.getIPv4PrefixCount
public long getIPv4PrefixCount(int prefixLength) { """ Equivalent to {@link #getPrefixCount(int)} but returns a long @return """ if(prefixLength < 0) { throw new PrefixLenException(this, prefixLength); } int bitCount = getBitCount(); if(bitCount <= prefixLength) { return getIPv4Count(); } int shiftAdjustment = bitCount - prefixLength; long upperAdjusted = getUpper().longValue() >>> shiftAdjustment; long lowerAdjusted = getLower().longValue() >>> shiftAdjustment; return upperAdjusted - lowerAdjusted + 1; }
java
public long getIPv4PrefixCount(int prefixLength) { if(prefixLength < 0) { throw new PrefixLenException(this, prefixLength); } int bitCount = getBitCount(); if(bitCount <= prefixLength) { return getIPv4Count(); } int shiftAdjustment = bitCount - prefixLength; long upperAdjusted = getUpper().longValue() >>> shiftAdjustment; long lowerAdjusted = getLower().longValue() >>> shiftAdjustment; return upperAdjusted - lowerAdjusted + 1; }
[ "public", "long", "getIPv4PrefixCount", "(", "int", "prefixLength", ")", "{", "if", "(", "prefixLength", "<", "0", ")", "{", "throw", "new", "PrefixLenException", "(", "this", ",", "prefixLength", ")", ";", "}", "int", "bitCount", "=", "getBitCount", "(", ")", ";", "if", "(", "bitCount", "<=", "prefixLength", ")", "{", "return", "getIPv4Count", "(", ")", ";", "}", "int", "shiftAdjustment", "=", "bitCount", "-", "prefixLength", ";", "long", "upperAdjusted", "=", "getUpper", "(", ")", ".", "longValue", "(", ")", ">>>", "shiftAdjustment", ";", "long", "lowerAdjusted", "=", "getLower", "(", ")", ".", "longValue", "(", ")", ">>>", "shiftAdjustment", ";", "return", "upperAdjusted", "-", "lowerAdjusted", "+", "1", ";", "}" ]
Equivalent to {@link #getPrefixCount(int)} but returns a long @return
[ "Equivalent", "to", "{", "@link", "#getPrefixCount", "(", "int", ")", "}", "but", "returns", "a", "long" ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv4/IPv4AddressSeqRange.java#L87-L99
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.getHierarchicalEntity
public HierarchicalEntityExtractor getHierarchicalEntity(UUID appId, String versionId, UUID hEntityId) { """ Gets information about the hierarchical entity model. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the HierarchicalEntityExtractor object if successful. """ return getHierarchicalEntityWithServiceResponseAsync(appId, versionId, hEntityId).toBlocking().single().body(); }
java
public HierarchicalEntityExtractor getHierarchicalEntity(UUID appId, String versionId, UUID hEntityId) { return getHierarchicalEntityWithServiceResponseAsync(appId, versionId, hEntityId).toBlocking().single().body(); }
[ "public", "HierarchicalEntityExtractor", "getHierarchicalEntity", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "hEntityId", ")", "{", "return", "getHierarchicalEntityWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "hEntityId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Gets information about the hierarchical entity model. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the HierarchicalEntityExtractor object if successful.
[ "Gets", "information", "about", "the", "hierarchical", "entity", "model", "." ]
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#L3656-L3658
apereo/cas
core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/PolicyBasedAuthenticationManager.java
PolicyBasedAuthenticationManager.evaluateFinalAuthentication
protected void evaluateFinalAuthentication(final AuthenticationBuilder builder, final AuthenticationTransaction transaction, final Set<AuthenticationHandler> authenticationHandlers) throws AuthenticationException { """ Evaluate produced authentication context. We apply an implicit security policy of at least one successful authentication. Then, we apply the configured security policy. @param builder the builder @param transaction the transaction @param authenticationHandlers the authentication handlers @throws AuthenticationException the authentication exception """ if (builder.getSuccesses().isEmpty()) { publishEvent(new CasAuthenticationTransactionFailureEvent(this, builder.getFailures(), transaction.getCredentials())); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } val authentication = builder.build(); val failures = evaluateAuthenticationPolicies(authentication, transaction, authenticationHandlers); if (!failures.getKey()) { publishEvent(new CasAuthenticationPolicyFailureEvent(this, builder.getFailures(), transaction, authentication)); failures.getValue().forEach(e -> handleAuthenticationException(e, e.getClass().getSimpleName(), builder)); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } }
java
protected void evaluateFinalAuthentication(final AuthenticationBuilder builder, final AuthenticationTransaction transaction, final Set<AuthenticationHandler> authenticationHandlers) throws AuthenticationException { if (builder.getSuccesses().isEmpty()) { publishEvent(new CasAuthenticationTransactionFailureEvent(this, builder.getFailures(), transaction.getCredentials())); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } val authentication = builder.build(); val failures = evaluateAuthenticationPolicies(authentication, transaction, authenticationHandlers); if (!failures.getKey()) { publishEvent(new CasAuthenticationPolicyFailureEvent(this, builder.getFailures(), transaction, authentication)); failures.getValue().forEach(e -> handleAuthenticationException(e, e.getClass().getSimpleName(), builder)); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } }
[ "protected", "void", "evaluateFinalAuthentication", "(", "final", "AuthenticationBuilder", "builder", ",", "final", "AuthenticationTransaction", "transaction", ",", "final", "Set", "<", "AuthenticationHandler", ">", "authenticationHandlers", ")", "throws", "AuthenticationException", "{", "if", "(", "builder", ".", "getSuccesses", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "publishEvent", "(", "new", "CasAuthenticationTransactionFailureEvent", "(", "this", ",", "builder", ".", "getFailures", "(", ")", ",", "transaction", ".", "getCredentials", "(", ")", ")", ")", ";", "throw", "new", "AuthenticationException", "(", "builder", ".", "getFailures", "(", ")", ",", "builder", ".", "getSuccesses", "(", ")", ")", ";", "}", "val", "authentication", "=", "builder", ".", "build", "(", ")", ";", "val", "failures", "=", "evaluateAuthenticationPolicies", "(", "authentication", ",", "transaction", ",", "authenticationHandlers", ")", ";", "if", "(", "!", "failures", ".", "getKey", "(", ")", ")", "{", "publishEvent", "(", "new", "CasAuthenticationPolicyFailureEvent", "(", "this", ",", "builder", ".", "getFailures", "(", ")", ",", "transaction", ",", "authentication", ")", ")", ";", "failures", ".", "getValue", "(", ")", ".", "forEach", "(", "e", "->", "handleAuthenticationException", "(", "e", ",", "e", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ",", "builder", ")", ")", ";", "throw", "new", "AuthenticationException", "(", "builder", ".", "getFailures", "(", ")", ",", "builder", ".", "getSuccesses", "(", ")", ")", ";", "}", "}" ]
Evaluate produced authentication context. We apply an implicit security policy of at least one successful authentication. Then, we apply the configured security policy. @param builder the builder @param transaction the transaction @param authenticationHandlers the authentication handlers @throws AuthenticationException the authentication exception
[ "Evaluate", "produced", "authentication", "context", ".", "We", "apply", "an", "implicit", "security", "policy", "of", "at", "least", "one", "successful", "authentication", ".", "Then", "we", "apply", "the", "configured", "security", "policy", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/PolicyBasedAuthenticationManager.java#L345-L360
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java
ApiKeyRealm.cacheAuthorizationInfoById
private void cacheAuthorizationInfoById(String id, AuthorizationInfo authorizationInfo) { """ If possible, this method caches the authorization info for an API key by its ID. This may be called either by an explicit call to get the authorization info by ID or as a side effect of loading the authorization info by API key and proactive caching by ID. """ Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache(); if (idAuthorizationCache != null) { idAuthorizationCache.put(id, authorizationInfo); } }
java
private void cacheAuthorizationInfoById(String id, AuthorizationInfo authorizationInfo) { Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache(); if (idAuthorizationCache != null) { idAuthorizationCache.put(id, authorizationInfo); } }
[ "private", "void", "cacheAuthorizationInfoById", "(", "String", "id", ",", "AuthorizationInfo", "authorizationInfo", ")", "{", "Cache", "<", "String", ",", "AuthorizationInfo", ">", "idAuthorizationCache", "=", "getAvailableIdAuthorizationCache", "(", ")", ";", "if", "(", "idAuthorizationCache", "!=", "null", ")", "{", "idAuthorizationCache", ".", "put", "(", "id", ",", "authorizationInfo", ")", ";", "}", "}" ]
If possible, this method caches the authorization info for an API key by its ID. This may be called either by an explicit call to get the authorization info by ID or as a side effect of loading the authorization info by API key and proactive caching by ID.
[ "If", "possible", "this", "method", "caches", "the", "authorization", "info", "for", "an", "API", "key", "by", "its", "ID", ".", "This", "may", "be", "called", "either", "by", "an", "explicit", "call", "to", "get", "the", "authorization", "info", "by", "ID", "or", "as", "a", "side", "effect", "of", "loading", "the", "authorization", "info", "by", "API", "key", "and", "proactive", "caching", "by", "ID", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L407-L413
kiegroup/drools
drools-core/src/main/java/org/drools/core/util/DroolsStreamUtils.java
DroolsStreamUtils.streamIn
public static Object streamIn(InputStream in) throws IOException, ClassNotFoundException { """ This method reads the contents from the given input stream and returns the object. It is expected that the contents in the given stream was not compressed, and it was written by the corresponding streamOut methods of this class. @param in @return @throws IOException @throws ClassNotFoundException """ return streamIn(in, null, false); }
java
public static Object streamIn(InputStream in) throws IOException, ClassNotFoundException { return streamIn(in, null, false); }
[ "public", "static", "Object", "streamIn", "(", "InputStream", "in", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "streamIn", "(", "in", ",", "null", ",", "false", ")", ";", "}" ]
This method reads the contents from the given input stream and returns the object. It is expected that the contents in the given stream was not compressed, and it was written by the corresponding streamOut methods of this class. @param in @return @throws IOException @throws ClassNotFoundException
[ "This", "method", "reads", "the", "contents", "from", "the", "given", "input", "stream", "and", "returns", "the", "object", ".", "It", "is", "expected", "that", "the", "contents", "in", "the", "given", "stream", "was", "not", "compressed", "and", "it", "was", "written", "by", "the", "corresponding", "streamOut", "methods", "of", "this", "class", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/util/DroolsStreamUtils.java#L173-L175
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java
Messenger.requestUploadState
@ObjectiveCName("requestUploadStateWithRid:withCallback:") public void requestUploadState(long rid, UploadFileCallback callback) { """ Request upload file state @param rid file's random id @param callback file state callback """ modules.getFilesModule().requestUploadState(rid, callback); }
java
@ObjectiveCName("requestUploadStateWithRid:withCallback:") public void requestUploadState(long rid, UploadFileCallback callback) { modules.getFilesModule().requestUploadState(rid, callback); }
[ "@", "ObjectiveCName", "(", "\"requestUploadStateWithRid:withCallback:\"", ")", "public", "void", "requestUploadState", "(", "long", "rid", ",", "UploadFileCallback", "callback", ")", "{", "modules", ".", "getFilesModule", "(", ")", ".", "requestUploadState", "(", "rid", ",", "callback", ")", ";", "}" ]
Request upload file state @param rid file's random id @param callback file state callback
[ "Request", "upload", "file", "state" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L1986-L1989
apereo/cas
support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java
LdapUtils.newLdaptiveSearchRequest
public static SearchRequest newLdaptiveSearchRequest(final String baseDn, final SearchFilter filter) { """ New ldaptive search request. Returns all attributes. @param baseDn the base dn @param filter the filter @return the search request """ return newLdaptiveSearchRequest(baseDn, filter, ReturnAttributes.ALL_USER.value(), ReturnAttributes.ALL_USER.value()); }
java
public static SearchRequest newLdaptiveSearchRequest(final String baseDn, final SearchFilter filter) { return newLdaptiveSearchRequest(baseDn, filter, ReturnAttributes.ALL_USER.value(), ReturnAttributes.ALL_USER.value()); }
[ "public", "static", "SearchRequest", "newLdaptiveSearchRequest", "(", "final", "String", "baseDn", ",", "final", "SearchFilter", "filter", ")", "{", "return", "newLdaptiveSearchRequest", "(", "baseDn", ",", "filter", ",", "ReturnAttributes", ".", "ALL_USER", ".", "value", "(", ")", ",", "ReturnAttributes", ".", "ALL_USER", ".", "value", "(", ")", ")", ";", "}" ]
New ldaptive search request. Returns all attributes. @param baseDn the base dn @param filter the filter @return the search request
[ "New", "ldaptive", "search", "request", ".", "Returns", "all", "attributes", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L488-L491
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.aget
public void aget(Local<?> target, Local<?> array, Local<Integer> index) { """ Assigns the element at {@code index} in {@code array} to {@code target}. """ addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition, RegisterSpecList.make(array.spec(), index.spec()), catches)); moveResult(target, true); }
java
public void aget(Local<?> target, Local<?> array, Local<Integer> index) { addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition, RegisterSpecList.make(array.spec(), index.spec()), catches)); moveResult(target, true); }
[ "public", "void", "aget", "(", "Local", "<", "?", ">", "target", ",", "Local", "<", "?", ">", "array", ",", "Local", "<", "Integer", ">", "index", ")", "{", "addInstruction", "(", "new", "ThrowingInsn", "(", "Rops", ".", "opAget", "(", "target", ".", "type", ".", "ropType", ")", ",", "sourcePosition", ",", "RegisterSpecList", ".", "make", "(", "array", ".", "spec", "(", ")", ",", "index", ".", "spec", "(", ")", ")", ",", "catches", ")", ")", ";", "moveResult", "(", "target", ",", "true", ")", ";", "}" ]
Assigns the element at {@code index} in {@code array} to {@code target}.
[ "Assigns", "the", "element", "at", "{" ]
train
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L803-L807
52inc/android-52Kit
library/src/main/java/com/ftinc/kit/util/IntentUtils.java
IntentUtils.sendEmail
public static Intent sendEmail(String to, String subject, String text) { """ Send email message @param to Receiver email @param subject Message subject @param text Message body @see #sendEmail(String[], String, String) """ return sendEmail(new String[]{to}, subject, text); }
java
public static Intent sendEmail(String to, String subject, String text) { return sendEmail(new String[]{to}, subject, text); }
[ "public", "static", "Intent", "sendEmail", "(", "String", "to", ",", "String", "subject", ",", "String", "text", ")", "{", "return", "sendEmail", "(", "new", "String", "[", "]", "{", "to", "}", ",", "subject", ",", "text", ")", ";", "}" ]
Send email message @param to Receiver email @param subject Message subject @param text Message body @see #sendEmail(String[], String, String)
[ "Send", "email", "message" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/IntentUtils.java#L78-L80
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.restoreStorageAccountAsync
public Observable<StorageBundle> restoreStorageAccountAsync(String vaultBaseUrl, byte[] storageBundleBackup) { """ Restores a backed up storage account to a vault. Restores a backed up storage account to a vault. This operation requires the storage/restore permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageBundleBackup The backup blob associated with a storage account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageBundle object """ return restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() { @Override public StorageBundle call(ServiceResponse<StorageBundle> response) { return response.body(); } }); }
java
public Observable<StorageBundle> restoreStorageAccountAsync(String vaultBaseUrl, byte[] storageBundleBackup) { return restoreStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageBundleBackup).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() { @Override public StorageBundle call(ServiceResponse<StorageBundle> response) { return response.body(); } }); }
[ "public", "Observable", "<", "StorageBundle", ">", "restoreStorageAccountAsync", "(", "String", "vaultBaseUrl", ",", "byte", "[", "]", "storageBundleBackup", ")", "{", "return", "restoreStorageAccountWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageBundleBackup", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "StorageBundle", ">", ",", "StorageBundle", ">", "(", ")", "{", "@", "Override", "public", "StorageBundle", "call", "(", "ServiceResponse", "<", "StorageBundle", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Restores a backed up storage account to a vault. Restores a backed up storage account to a vault. This operation requires the storage/restore permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageBundleBackup The backup blob associated with a storage account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageBundle object
[ "Restores", "a", "backed", "up", "storage", "account", "to", "a", "vault", ".", "Restores", "a", "backed", "up", "storage", "account", "to", "a", "vault", ".", "This", "operation", "requires", "the", "storage", "/", "restore", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9635-L9642
SonarSource/sonarqube
sonar-duplications/src/main/java/org/sonar/duplications/detector/original/Filter.java
Filter.containsIn
static boolean containsIn(CloneGroup first, CloneGroup second) { """ Checks that second clone contains first one. <p> Clone A is contained in another clone B, if every part pA from A has part pB in B, which satisfy the conditions: <pre> (pA.resourceId == pB.resourceId) and (pB.unitStart <= pA.unitStart) and (pA.unitEnd <= pB.unitEnd) </pre> And all resourcesId from B exactly the same as all resourceId from A, which means that also every part pB from B has part pA in A, which satisfy the condition: <pre> pB.resourceId == pA.resourceId </pre> So this relation is: <ul> <li>reflexive - A in A</li> <li>transitive - (A in B) and (B in C) => (A in C)</li> <li>antisymmetric - (A in B) and (B in A) <=> (A = B)</li> </ul> </p> <p> <strong>Important: this method relies on fact that all parts were already sorted by resourceId and unitStart by using {@link BlocksGroup.BlockComparator}, which uses {@link org.sonar.duplications.utils.FastStringComparator} for comparison by resourceId.</strong> </p> <p> Running time - O(|A|+|B|). </p> """ if (first.getCloneUnitLength() > second.getCloneUnitLength()) { return false; } List<ClonePart> firstParts = first.getCloneParts(); List<ClonePart> secondParts = second.getCloneParts(); return SortedListsUtils.contains(secondParts, firstParts, new ContainsInComparator(second.getCloneUnitLength(), first.getCloneUnitLength())) && SortedListsUtils.contains(firstParts, secondParts, ContainsInComparator.RESOURCE_ID_COMPARATOR); }
java
static boolean containsIn(CloneGroup first, CloneGroup second) { if (first.getCloneUnitLength() > second.getCloneUnitLength()) { return false; } List<ClonePart> firstParts = first.getCloneParts(); List<ClonePart> secondParts = second.getCloneParts(); return SortedListsUtils.contains(secondParts, firstParts, new ContainsInComparator(second.getCloneUnitLength(), first.getCloneUnitLength())) && SortedListsUtils.contains(firstParts, secondParts, ContainsInComparator.RESOURCE_ID_COMPARATOR); }
[ "static", "boolean", "containsIn", "(", "CloneGroup", "first", ",", "CloneGroup", "second", ")", "{", "if", "(", "first", ".", "getCloneUnitLength", "(", ")", ">", "second", ".", "getCloneUnitLength", "(", ")", ")", "{", "return", "false", ";", "}", "List", "<", "ClonePart", ">", "firstParts", "=", "first", ".", "getCloneParts", "(", ")", ";", "List", "<", "ClonePart", ">", "secondParts", "=", "second", ".", "getCloneParts", "(", ")", ";", "return", "SortedListsUtils", ".", "contains", "(", "secondParts", ",", "firstParts", ",", "new", "ContainsInComparator", "(", "second", ".", "getCloneUnitLength", "(", ")", ",", "first", ".", "getCloneUnitLength", "(", ")", ")", ")", "&&", "SortedListsUtils", ".", "contains", "(", "firstParts", ",", "secondParts", ",", "ContainsInComparator", ".", "RESOURCE_ID_COMPARATOR", ")", ";", "}" ]
Checks that second clone contains first one. <p> Clone A is contained in another clone B, if every part pA from A has part pB in B, which satisfy the conditions: <pre> (pA.resourceId == pB.resourceId) and (pB.unitStart <= pA.unitStart) and (pA.unitEnd <= pB.unitEnd) </pre> And all resourcesId from B exactly the same as all resourceId from A, which means that also every part pB from B has part pA in A, which satisfy the condition: <pre> pB.resourceId == pA.resourceId </pre> So this relation is: <ul> <li>reflexive - A in A</li> <li>transitive - (A in B) and (B in C) => (A in C)</li> <li>antisymmetric - (A in B) and (B in A) <=> (A = B)</li> </ul> </p> <p> <strong>Important: this method relies on fact that all parts were already sorted by resourceId and unitStart by using {@link BlocksGroup.BlockComparator}, which uses {@link org.sonar.duplications.utils.FastStringComparator} for comparison by resourceId.</strong> </p> <p> Running time - O(|A|+|B|). </p>
[ "Checks", "that", "second", "clone", "contains", "first", "one", ".", "<p", ">", "Clone", "A", "is", "contained", "in", "another", "clone", "B", "if", "every", "part", "pA", "from", "A", "has", "part", "pB", "in", "B", "which", "satisfy", "the", "conditions", ":", "<pre", ">", "(", "pA", ".", "resourceId", "==", "pB", ".", "resourceId", ")", "and", "(", "pB", ".", "unitStart", "<", "=", "pA", ".", "unitStart", ")", "and", "(", "pA", ".", "unitEnd", "<", "=", "pB", ".", "unitEnd", ")", "<", "/", "pre", ">", "And", "all", "resourcesId", "from", "B", "exactly", "the", "same", "as", "all", "resourceId", "from", "A", "which", "means", "that", "also", "every", "part", "pB", "from", "B", "has", "part", "pA", "in", "A", "which", "satisfy", "the", "condition", ":", "<pre", ">", "pB", ".", "resourceId", "==", "pA", ".", "resourceId", "<", "/", "pre", ">", "So", "this", "relation", "is", ":", "<ul", ">", "<li", ">", "reflexive", "-", "A", "in", "A<", "/", "li", ">", "<li", ">", "transitive", "-", "(", "A", "in", "B", ")", "and", "(", "B", "in", "C", ")", "=", ">", "(", "A", "in", "C", ")", "<", "/", "li", ">", "<li", ">", "antisymmetric", "-", "(", "A", "in", "B", ")", "and", "(", "B", "in", "A", ")", "<", "=", ">", "(", "A", "=", "B", ")", "<", "/", "li", ">", "<", "/", "ul", ">", "<", "/", "p", ">", "<p", ">", "<strong", ">", "Important", ":", "this", "method", "relies", "on", "fact", "that", "all", "parts", "were", "already", "sorted", "by", "resourceId", "and", "unitStart", "by", "using", "{" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/Filter.java#L109-L117
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookAlbumListFragment.java
FacebookAlbumListFragment.requestAccountName
private void requestAccountName() { """ Asynchronously requests the user name associated with the linked account. Tries to finish the {@link FacebookSettingsActivity} when completed. """ GraphUserCallback callback = new GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { FacebookSettingsActivity activity = (FacebookSettingsActivity) getActivity(); if (activity == null || activity.isFinishing()) { return; } if (response != null && response.getError() == null && user != null) { String accountName = user.getFirstName() + " " + user.getLastName(); if (accountName != null && accountName.length() > 0) { activity.mAccountName = accountName; } else { activity.mHasErrorOccurred = true; } } else { activity.mHasErrorOccurred = true; } activity.tryFinish(); } }; mFacebookEndpoint.requestAccountName(callback); }
java
private void requestAccountName() { GraphUserCallback callback = new GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { FacebookSettingsActivity activity = (FacebookSettingsActivity) getActivity(); if (activity == null || activity.isFinishing()) { return; } if (response != null && response.getError() == null && user != null) { String accountName = user.getFirstName() + " " + user.getLastName(); if (accountName != null && accountName.length() > 0) { activity.mAccountName = accountName; } else { activity.mHasErrorOccurred = true; } } else { activity.mHasErrorOccurred = true; } activity.tryFinish(); } }; mFacebookEndpoint.requestAccountName(callback); }
[ "private", "void", "requestAccountName", "(", ")", "{", "GraphUserCallback", "callback", "=", "new", "GraphUserCallback", "(", ")", "{", "@", "Override", "public", "void", "onCompleted", "(", "GraphUser", "user", ",", "Response", "response", ")", "{", "FacebookSettingsActivity", "activity", "=", "(", "FacebookSettingsActivity", ")", "getActivity", "(", ")", ";", "if", "(", "activity", "==", "null", "||", "activity", ".", "isFinishing", "(", ")", ")", "{", "return", ";", "}", "if", "(", "response", "!=", "null", "&&", "response", ".", "getError", "(", ")", "==", "null", "&&", "user", "!=", "null", ")", "{", "String", "accountName", "=", "user", ".", "getFirstName", "(", ")", "+", "\" \"", "+", "user", ".", "getLastName", "(", ")", ";", "if", "(", "accountName", "!=", "null", "&&", "accountName", ".", "length", "(", ")", ">", "0", ")", "{", "activity", ".", "mAccountName", "=", "accountName", ";", "}", "else", "{", "activity", ".", "mHasErrorOccurred", "=", "true", ";", "}", "}", "else", "{", "activity", ".", "mHasErrorOccurred", "=", "true", ";", "}", "activity", ".", "tryFinish", "(", ")", ";", "}", "}", ";", "mFacebookEndpoint", ".", "requestAccountName", "(", "callback", ")", ";", "}" ]
Asynchronously requests the user name associated with the linked account. Tries to finish the {@link FacebookSettingsActivity} when completed.
[ "Asynchronously", "requests", "the", "user", "name", "associated", "with", "the", "linked", "account", ".", "Tries", "to", "finish", "the", "{" ]
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookAlbumListFragment.java#L144-L169
codeprimate-software/cp-elements
src/main/java/org/cp/elements/data/struct/SimpleBloomFilter.java
SimpleBloomFilter.computeRequiredNumberOfBits
protected static int computeRequiredNumberOfBits(double approximateNumberOfElements, double acceptableFalsePositiveRate) { """ Computes the required number of bits needed by the Bloom Filter as a factor of the approximate number of elements to be added to the filter along with the desired, acceptable false positive rate (probability). m = n * (log p) / (log 2) ^ 2 m is the required number of bits needed for the Bloom Filter. n is the approximate number of elements to be added to the bloom filter p is the acceptable false positive rate between 0.0 and 1.0 exclusive @param approximateNumberOfElements integer value indicating the approximate, estimated number of elements the user expects will be added to the Bloom Filter. @param acceptableFalsePositiveRate a floating point value indicating the acceptable percentage of false positives returned by the Bloom Filter. @return the required number of bits needed by the Bloom Filter. """ double numberOfBits = Math.abs((approximateNumberOfElements * Math.log(acceptableFalsePositiveRate)) / Math.pow(Math.log(2.0d), 2.0d)); return Double.valueOf(Math.ceil(numberOfBits)).intValue(); }
java
protected static int computeRequiredNumberOfBits(double approximateNumberOfElements, double acceptableFalsePositiveRate) { double numberOfBits = Math.abs((approximateNumberOfElements * Math.log(acceptableFalsePositiveRate)) / Math.pow(Math.log(2.0d), 2.0d)); return Double.valueOf(Math.ceil(numberOfBits)).intValue(); }
[ "protected", "static", "int", "computeRequiredNumberOfBits", "(", "double", "approximateNumberOfElements", ",", "double", "acceptableFalsePositiveRate", ")", "{", "double", "numberOfBits", "=", "Math", ".", "abs", "(", "(", "approximateNumberOfElements", "*", "Math", ".", "log", "(", "acceptableFalsePositiveRate", ")", ")", "/", "Math", ".", "pow", "(", "Math", ".", "log", "(", "2.0d", ")", ",", "2.0d", ")", ")", ";", "return", "Double", ".", "valueOf", "(", "Math", ".", "ceil", "(", "numberOfBits", ")", ")", ".", "intValue", "(", ")", ";", "}" ]
Computes the required number of bits needed by the Bloom Filter as a factor of the approximate number of elements to be added to the filter along with the desired, acceptable false positive rate (probability). m = n * (log p) / (log 2) ^ 2 m is the required number of bits needed for the Bloom Filter. n is the approximate number of elements to be added to the bloom filter p is the acceptable false positive rate between 0.0 and 1.0 exclusive @param approximateNumberOfElements integer value indicating the approximate, estimated number of elements the user expects will be added to the Bloom Filter. @param acceptableFalsePositiveRate a floating point value indicating the acceptable percentage of false positives returned by the Bloom Filter. @return the required number of bits needed by the Bloom Filter.
[ "Computes", "the", "required", "number", "of", "bits", "needed", "by", "the", "Bloom", "Filter", "as", "a", "factor", "of", "the", "approximate", "number", "of", "elements", "to", "be", "added", "to", "the", "filter", "along", "with", "the", "desired", "acceptable", "false", "positive", "rate", "(", "probability", ")", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/struct/SimpleBloomFilter.java#L185-L191
davetcc/tcMenu
tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/domain/state/MenuTree.java
MenuTree.addMenuItem
public void addMenuItem(SubMenuItem parent, MenuItem item) { """ add a new menu item to a sub menu, for the top level menu use ROOT. @param parent the submenu where this should appear @param item the item to be added """ SubMenuItem subMenu = (parent != null) ? parent : ROOT; synchronized (subMenuItems) { ArrayList<MenuItem> subMenuChildren = subMenuItems.computeIfAbsent(subMenu, sm -> new ArrayList<>()); subMenuChildren.add(item); if (item.hasChildren()) { subMenuItems.put(item, new ArrayList<>()); } } }
java
public void addMenuItem(SubMenuItem parent, MenuItem item) { SubMenuItem subMenu = (parent != null) ? parent : ROOT; synchronized (subMenuItems) { ArrayList<MenuItem> subMenuChildren = subMenuItems.computeIfAbsent(subMenu, sm -> new ArrayList<>()); subMenuChildren.add(item); if (item.hasChildren()) { subMenuItems.put(item, new ArrayList<>()); } } }
[ "public", "void", "addMenuItem", "(", "SubMenuItem", "parent", ",", "MenuItem", "item", ")", "{", "SubMenuItem", "subMenu", "=", "(", "parent", "!=", "null", ")", "?", "parent", ":", "ROOT", ";", "synchronized", "(", "subMenuItems", ")", "{", "ArrayList", "<", "MenuItem", ">", "subMenuChildren", "=", "subMenuItems", ".", "computeIfAbsent", "(", "subMenu", ",", "sm", "->", "new", "ArrayList", "<>", "(", ")", ")", ";", "subMenuChildren", ".", "add", "(", "item", ")", ";", "if", "(", "item", ".", "hasChildren", "(", ")", ")", "{", "subMenuItems", ".", "put", "(", "item", ",", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "}", "}" ]
add a new menu item to a sub menu, for the top level menu use ROOT. @param parent the submenu where this should appear @param item the item to be added
[ "add", "a", "new", "menu", "item", "to", "a", "sub", "menu", "for", "the", "top", "level", "menu", "use", "ROOT", "." ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/domain/state/MenuTree.java#L62-L73
google/closure-compiler
src/com/google/javascript/jscomp/CheckJSDoc.java
CheckJSDoc.validateTypeAnnotations
private void validateTypeAnnotations(Node n, JSDocInfo info) { """ Check that JSDoc with a {@code @type} annotation is in a valid place. """ if (info != null && info.hasType()) { boolean valid = false; switch (n.getToken()) { // Function declarations are valid case FUNCTION: valid = NodeUtil.isFunctionDeclaration(n); break; // Object literal properties, catch declarations and variable // initializers are valid. case NAME: valid = isTypeAnnotationAllowedForName(n); break; case ARRAY_PATTERN: case OBJECT_PATTERN: // allow JSDoc like // function f(/** !Object */ {x}) {} // function f(/** !Array */ [x]) {} valid = n.getParent().isParamList(); break; // Casts, exports, and Object literal properties are valid. case CAST: case EXPORT: case STRING_KEY: case GETTER_DEF: case SETTER_DEF: valid = true; break; // Declarations are valid iff they only contain simple names // /** @type {number} */ var x = 3; // ok // /** @type {number} */ var {x} = obj; // forbidden case VAR: case LET: case CONST: valid = !NodeUtil.isDestructuringDeclaration(n); break; // Property assignments are valid, if at the root of an expression. case ASSIGN: { Node lvalue = n.getFirstChild(); valid = n.getParent().isExprResult() && (lvalue.isGetProp() || lvalue.isGetElem() || lvalue.matchesQualifiedName("exports")); break; } case GETPROP: valid = n.getParent().isExprResult() && n.isQualifiedName(); break; case CALL: valid = info.isDefine(); break; default: break; } if (!valid) { reportMisplaced(n, "type", "Type annotations are not allowed here. " + "Are you missing parentheses?"); } } }
java
private void validateTypeAnnotations(Node n, JSDocInfo info) { if (info != null && info.hasType()) { boolean valid = false; switch (n.getToken()) { // Function declarations are valid case FUNCTION: valid = NodeUtil.isFunctionDeclaration(n); break; // Object literal properties, catch declarations and variable // initializers are valid. case NAME: valid = isTypeAnnotationAllowedForName(n); break; case ARRAY_PATTERN: case OBJECT_PATTERN: // allow JSDoc like // function f(/** !Object */ {x}) {} // function f(/** !Array */ [x]) {} valid = n.getParent().isParamList(); break; // Casts, exports, and Object literal properties are valid. case CAST: case EXPORT: case STRING_KEY: case GETTER_DEF: case SETTER_DEF: valid = true; break; // Declarations are valid iff they only contain simple names // /** @type {number} */ var x = 3; // ok // /** @type {number} */ var {x} = obj; // forbidden case VAR: case LET: case CONST: valid = !NodeUtil.isDestructuringDeclaration(n); break; // Property assignments are valid, if at the root of an expression. case ASSIGN: { Node lvalue = n.getFirstChild(); valid = n.getParent().isExprResult() && (lvalue.isGetProp() || lvalue.isGetElem() || lvalue.matchesQualifiedName("exports")); break; } case GETPROP: valid = n.getParent().isExprResult() && n.isQualifiedName(); break; case CALL: valid = info.isDefine(); break; default: break; } if (!valid) { reportMisplaced(n, "type", "Type annotations are not allowed here. " + "Are you missing parentheses?"); } } }
[ "private", "void", "validateTypeAnnotations", "(", "Node", "n", ",", "JSDocInfo", "info", ")", "{", "if", "(", "info", "!=", "null", "&&", "info", ".", "hasType", "(", ")", ")", "{", "boolean", "valid", "=", "false", ";", "switch", "(", "n", ".", "getToken", "(", ")", ")", "{", "// Function declarations are valid", "case", "FUNCTION", ":", "valid", "=", "NodeUtil", ".", "isFunctionDeclaration", "(", "n", ")", ";", "break", ";", "// Object literal properties, catch declarations and variable", "// initializers are valid.", "case", "NAME", ":", "valid", "=", "isTypeAnnotationAllowedForName", "(", "n", ")", ";", "break", ";", "case", "ARRAY_PATTERN", ":", "case", "OBJECT_PATTERN", ":", "// allow JSDoc like", "// function f(/** !Object */ {x}) {}", "// function f(/** !Array */ [x]) {}", "valid", "=", "n", ".", "getParent", "(", ")", ".", "isParamList", "(", ")", ";", "break", ";", "// Casts, exports, and Object literal properties are valid.", "case", "CAST", ":", "case", "EXPORT", ":", "case", "STRING_KEY", ":", "case", "GETTER_DEF", ":", "case", "SETTER_DEF", ":", "valid", "=", "true", ";", "break", ";", "// Declarations are valid iff they only contain simple names", "// /** @type {number} */ var x = 3; // ok", "// /** @type {number} */ var {x} = obj; // forbidden", "case", "VAR", ":", "case", "LET", ":", "case", "CONST", ":", "valid", "=", "!", "NodeUtil", ".", "isDestructuringDeclaration", "(", "n", ")", ";", "break", ";", "// Property assignments are valid, if at the root of an expression.", "case", "ASSIGN", ":", "{", "Node", "lvalue", "=", "n", ".", "getFirstChild", "(", ")", ";", "valid", "=", "n", ".", "getParent", "(", ")", ".", "isExprResult", "(", ")", "&&", "(", "lvalue", ".", "isGetProp", "(", ")", "||", "lvalue", ".", "isGetElem", "(", ")", "||", "lvalue", ".", "matchesQualifiedName", "(", "\"exports\"", ")", ")", ";", "break", ";", "}", "case", "GETPROP", ":", "valid", "=", "n", ".", "getParent", "(", ")", ".", "isExprResult", "(", ")", "&&", "n", ".", "isQualifiedName", "(", ")", ";", "break", ";", "case", "CALL", ":", "valid", "=", "info", ".", "isDefine", "(", ")", ";", "break", ";", "default", ":", "break", ";", "}", "if", "(", "!", "valid", ")", "{", "reportMisplaced", "(", "n", ",", "\"type\"", ",", "\"Type annotations are not allowed here. \"", "+", "\"Are you missing parentheses?\"", ")", ";", "}", "}", "}" ]
Check that JSDoc with a {@code @type} annotation is in a valid place.
[ "Check", "that", "JSDoc", "with", "a", "{" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L532-L592
msteiger/jxmapviewer2
jxmapviewer2/src/main/java/org/jxmapviewer/viewer/wms/WMSService.java
WMSService.toWMSURL
public String toWMSURL(int x, int y, int zoom, int tileSize) { """ Convertes to a WMS URL @param x the x coordinate @param y the y coordinate @param zoom the zomm factor @param tileSize the tile size @return a URL request string """ String format = "image/jpeg"; String styles = ""; String srs = "EPSG:4326"; int ts = tileSize; int circumference = widthOfWorldInPixels(zoom, tileSize); double radius = circumference / (2 * Math.PI); double ulx = MercatorUtils.xToLong(x * ts, radius); double uly = MercatorUtils.yToLat(y * ts, radius); double lrx = MercatorUtils.xToLong((x + 1) * ts, radius); double lry = MercatorUtils.yToLat((y + 1) * ts, radius); String bbox = ulx + "," + uly + "," + lrx + "," + lry; String url = getBaseUrl() + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format + "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles + // "&transparent=TRUE"+ ""; return url; }
java
public String toWMSURL(int x, int y, int zoom, int tileSize) { String format = "image/jpeg"; String styles = ""; String srs = "EPSG:4326"; int ts = tileSize; int circumference = widthOfWorldInPixels(zoom, tileSize); double radius = circumference / (2 * Math.PI); double ulx = MercatorUtils.xToLong(x * ts, radius); double uly = MercatorUtils.yToLat(y * ts, radius); double lrx = MercatorUtils.xToLong((x + 1) * ts, radius); double lry = MercatorUtils.yToLat((y + 1) * ts, radius); String bbox = ulx + "," + uly + "," + lrx + "," + lry; String url = getBaseUrl() + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format + "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles + // "&transparent=TRUE"+ ""; return url; }
[ "public", "String", "toWMSURL", "(", "int", "x", ",", "int", "y", ",", "int", "zoom", ",", "int", "tileSize", ")", "{", "String", "format", "=", "\"image/jpeg\"", ";", "String", "styles", "=", "\"\"", ";", "String", "srs", "=", "\"EPSG:4326\"", ";", "int", "ts", "=", "tileSize", ";", "int", "circumference", "=", "widthOfWorldInPixels", "(", "zoom", ",", "tileSize", ")", ";", "double", "radius", "=", "circumference", "/", "(", "2", "*", "Math", ".", "PI", ")", ";", "double", "ulx", "=", "MercatorUtils", ".", "xToLong", "(", "x", "*", "ts", ",", "radius", ")", ";", "double", "uly", "=", "MercatorUtils", ".", "yToLat", "(", "y", "*", "ts", ",", "radius", ")", ";", "double", "lrx", "=", "MercatorUtils", ".", "xToLong", "(", "(", "x", "+", "1", ")", "*", "ts", ",", "radius", ")", ";", "double", "lry", "=", "MercatorUtils", ".", "yToLat", "(", "(", "y", "+", "1", ")", "*", "ts", ",", "radius", ")", ";", "String", "bbox", "=", "ulx", "+", "\",\"", "+", "uly", "+", "\",\"", "+", "lrx", "+", "\",\"", "+", "lry", ";", "String", "url", "=", "getBaseUrl", "(", ")", "+", "\"version=1.1.1&request=\"", "+", "\"GetMap&Layers=\"", "+", "layer", "+", "\"&format=\"", "+", "format", "+", "\"&BBOX=\"", "+", "bbox", "+", "\"&width=\"", "+", "ts", "+", "\"&height=\"", "+", "ts", "+", "\"&SRS=\"", "+", "srs", "+", "\"&Styles=\"", "+", "styles", "+", "// \"&transparent=TRUE\"+", "\"\"", ";", "return", "url", ";", "}" ]
Convertes to a WMS URL @param x the x coordinate @param y the y coordinate @param zoom the zomm factor @param tileSize the tile size @return a URL request string
[ "Convertes", "to", "a", "WMS", "URL" ]
train
https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/viewer/wms/WMSService.java#L53-L71
netty/netty
example/src/main/java/io/netty/example/http/upload/HttpUploadClient.java
HttpUploadClient.formpost
private static List<InterfaceHttpData> formpost( Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { """ Standard post without multipart but already support on Factory (memory management) @return the list of HttpData object (attribute and file) to be reused on next post """ // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the next request // for the example (limit action on client side). Take this as a broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
java
private static List<InterfaceHttpData> formpost( Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the next request // for the example (limit action on client side). Take this as a broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
[ "private", "static", "List", "<", "InterfaceHttpData", ">", "formpost", "(", "Bootstrap", "bootstrap", ",", "String", "host", ",", "int", "port", ",", "URI", "uriSimple", ",", "File", "file", ",", "HttpDataFactory", "factory", ",", "List", "<", "Entry", "<", "String", ",", "String", ">", ">", "headers", ")", "throws", "Exception", "{", "// XXX /formpost", "// Start the connection attempt.", "ChannelFuture", "future", "=", "bootstrap", ".", "connect", "(", "SocketUtils", ".", "socketAddress", "(", "host", ",", "port", ")", ")", ";", "// Wait until the connection attempt succeeds or fails.", "Channel", "channel", "=", "future", ".", "sync", "(", ")", ".", "channel", "(", ")", ";", "// Prepare the HTTP request.", "HttpRequest", "request", "=", "new", "DefaultHttpRequest", "(", "HttpVersion", ".", "HTTP_1_1", ",", "HttpMethod", ".", "POST", ",", "uriSimple", ".", "toASCIIString", "(", ")", ")", ";", "// Use the PostBody encoder", "HttpPostRequestEncoder", "bodyRequestEncoder", "=", "new", "HttpPostRequestEncoder", "(", "factory", ",", "request", ",", "false", ")", ";", "// false => not multipart", "// it is legal to add directly header or cookie into the request until finalize", "for", "(", "Entry", "<", "String", ",", "String", ">", "entry", ":", "headers", ")", "{", "request", ".", "headers", "(", ")", ".", "set", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "// add Form attribute", "bodyRequestEncoder", ".", "addBodyAttribute", "(", "\"getform\"", ",", "\"POST\"", ")", ";", "bodyRequestEncoder", ".", "addBodyAttribute", "(", "\"info\"", ",", "\"first value\"", ")", ";", "bodyRequestEncoder", ".", "addBodyAttribute", "(", "\"secondinfo\"", ",", "\"secondvalue ���&\");", "", "", "bodyRequestEncoder", ".", "addBodyAttribute", "(", "\"thirdinfo\"", ",", "textArea", ")", ";", "bodyRequestEncoder", ".", "addBodyAttribute", "(", "\"fourthinfo\"", ",", "textAreaLong", ")", ";", "bodyRequestEncoder", ".", "addBodyFileUpload", "(", "\"myfile\"", ",", "file", ",", "\"application/x-zip-compressed\"", ",", "false", ")", ";", "// finalize request", "request", "=", "bodyRequestEncoder", ".", "finalizeRequest", "(", ")", ";", "// Create the bodylist to be reused on the last version with Multipart support", "List", "<", "InterfaceHttpData", ">", "bodylist", "=", "bodyRequestEncoder", ".", "getBodyListAttributes", "(", ")", ";", "// send request", "channel", ".", "write", "(", "request", ")", ";", "// test if request was chunked and if so, finish the write", "if", "(", "bodyRequestEncoder", ".", "isChunked", "(", ")", ")", "{", "// could do either request.isChunked()", "// either do it through ChunkedWriteHandler", "channel", ".", "write", "(", "bodyRequestEncoder", ")", ";", "}", "channel", ".", "flush", "(", ")", ";", "// Do not clear here since we will reuse the InterfaceHttpData on the next request", "// for the example (limit action on client side). Take this as a broadcast of the same", "// request on both Post actions.", "//", "// On standard program, it is clearly recommended to clean all files after each request", "// bodyRequestEncoder.cleanFiles();", "// Wait for the server to close the connection.", "channel", ".", "closeFuture", "(", ")", ".", "sync", "(", ")", ";", "return", "bodylist", ";", "}" ]
Standard post without multipart but already support on Factory (memory management) @return the list of HttpData object (attribute and file) to be reused on next post
[ "Standard", "post", "without", "multipart", "but", "already", "support", "on", "Factory", "(", "memory", "management", ")" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http/upload/HttpUploadClient.java#L204-L260
aws/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/AccountSettings.java
AccountSettings.withMaxSlots
public AccountSettings withMaxSlots(java.util.Map<String, Integer> maxSlots) { """ <p> The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by the <code>ListOfferings</code> command. </p> @param maxSlots The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by the <code>ListOfferings</code> command. @return Returns a reference to this object so that method calls can be chained together. """ setMaxSlots(maxSlots); return this; }
java
public AccountSettings withMaxSlots(java.util.Map<String, Integer> maxSlots) { setMaxSlots(maxSlots); return this; }
[ "public", "AccountSettings", "withMaxSlots", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "Integer", ">", "maxSlots", ")", "{", "setMaxSlots", "(", "maxSlots", ")", ";", "return", "this", ";", "}" ]
<p> The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by the <code>ListOfferings</code> command. </p> @param maxSlots The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by the <code>ListOfferings</code> command. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "maximum", "number", "of", "device", "slots", "that", "the", "AWS", "account", "can", "purchase", ".", "Each", "maximum", "is", "expressed", "as", "an", "<code", ">", "offering", "-", "id", ":", "number<", "/", "code", ">", "pair", "where", "the", "<code", ">", "offering", "-", "id<", "/", "code", ">", "represents", "one", "of", "the", "IDs", "returned", "by", "the", "<code", ">", "ListOfferings<", "/", "code", ">", "command", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/AccountSettings.java#L377-L380
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopyableFile.java
CopyableFile.setFsDatasets
public void setFsDatasets(FileSystem originFs, FileSystem targetFs) { """ Set file system based source and destination dataset for this {@link CopyableFile} @param originFs {@link FileSystem} where this {@link CopyableFile} origins @param targetFs {@link FileSystem} where this {@link CopyableFile} is copied to """ /* * By default, the raw Gobblin dataset for CopyableFile lineage is its parent folder * if itself is not a folder */ boolean isDir = origin.isDirectory(); Path fullSourcePath = Path.getPathWithoutSchemeAndAuthority(origin.getPath()); String sourceDatasetName = isDir ? fullSourcePath.toString() : fullSourcePath.getParent().toString(); DatasetDescriptor sourceDataset = new DatasetDescriptor(originFs.getScheme(), sourceDatasetName); sourceDataset.addMetadata(DatasetConstants.FS_URI, originFs.getUri().toString()); sourceData = sourceDataset; Path fullDestinationPath = Path.getPathWithoutSchemeAndAuthority(destination); String destinationDatasetName = isDir ? fullDestinationPath.toString() : fullDestinationPath.getParent().toString(); DatasetDescriptor destinationDataset = new DatasetDescriptor(targetFs.getScheme(), destinationDatasetName); destinationDataset.addMetadata(DatasetConstants.FS_URI, targetFs.getUri().toString()); destinationData = destinationDataset; }
java
public void setFsDatasets(FileSystem originFs, FileSystem targetFs) { /* * By default, the raw Gobblin dataset for CopyableFile lineage is its parent folder * if itself is not a folder */ boolean isDir = origin.isDirectory(); Path fullSourcePath = Path.getPathWithoutSchemeAndAuthority(origin.getPath()); String sourceDatasetName = isDir ? fullSourcePath.toString() : fullSourcePath.getParent().toString(); DatasetDescriptor sourceDataset = new DatasetDescriptor(originFs.getScheme(), sourceDatasetName); sourceDataset.addMetadata(DatasetConstants.FS_URI, originFs.getUri().toString()); sourceData = sourceDataset; Path fullDestinationPath = Path.getPathWithoutSchemeAndAuthority(destination); String destinationDatasetName = isDir ? fullDestinationPath.toString() : fullDestinationPath.getParent().toString(); DatasetDescriptor destinationDataset = new DatasetDescriptor(targetFs.getScheme(), destinationDatasetName); destinationDataset.addMetadata(DatasetConstants.FS_URI, targetFs.getUri().toString()); destinationData = destinationDataset; }
[ "public", "void", "setFsDatasets", "(", "FileSystem", "originFs", ",", "FileSystem", "targetFs", ")", "{", "/*\n * By default, the raw Gobblin dataset for CopyableFile lineage is its parent folder\n * if itself is not a folder\n */", "boolean", "isDir", "=", "origin", ".", "isDirectory", "(", ")", ";", "Path", "fullSourcePath", "=", "Path", ".", "getPathWithoutSchemeAndAuthority", "(", "origin", ".", "getPath", "(", ")", ")", ";", "String", "sourceDatasetName", "=", "isDir", "?", "fullSourcePath", ".", "toString", "(", ")", ":", "fullSourcePath", ".", "getParent", "(", ")", ".", "toString", "(", ")", ";", "DatasetDescriptor", "sourceDataset", "=", "new", "DatasetDescriptor", "(", "originFs", ".", "getScheme", "(", ")", ",", "sourceDatasetName", ")", ";", "sourceDataset", ".", "addMetadata", "(", "DatasetConstants", ".", "FS_URI", ",", "originFs", ".", "getUri", "(", ")", ".", "toString", "(", ")", ")", ";", "sourceData", "=", "sourceDataset", ";", "Path", "fullDestinationPath", "=", "Path", ".", "getPathWithoutSchemeAndAuthority", "(", "destination", ")", ";", "String", "destinationDatasetName", "=", "isDir", "?", "fullDestinationPath", ".", "toString", "(", ")", ":", "fullDestinationPath", ".", "getParent", "(", ")", ".", "toString", "(", ")", ";", "DatasetDescriptor", "destinationDataset", "=", "new", "DatasetDescriptor", "(", "targetFs", ".", "getScheme", "(", ")", ",", "destinationDatasetName", ")", ";", "destinationDataset", ".", "addMetadata", "(", "DatasetConstants", ".", "FS_URI", ",", "targetFs", ".", "getUri", "(", ")", ".", "toString", "(", ")", ")", ";", "destinationData", "=", "destinationDataset", ";", "}" ]
Set file system based source and destination dataset for this {@link CopyableFile} @param originFs {@link FileSystem} where this {@link CopyableFile} origins @param targetFs {@link FileSystem} where this {@link CopyableFile} is copied to
[ "Set", "file", "system", "based", "source", "and", "destination", "dataset", "for", "this", "{", "@link", "CopyableFile", "}" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopyableFile.java#L130-L148
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.identity_group_POST
public OvhGroup identity_group_POST(String description, String name, OvhRoleEnum role) throws IOException { """ Create a new group REST: POST /me/identity/group @param name [required] Group's name @param description [required] Group's description @param role [required] Group's Role """ String qPath = "/me/identity/group"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "name", name); addBody(o, "role", role); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhGroup.class); }
java
public OvhGroup identity_group_POST(String description, String name, OvhRoleEnum role) throws IOException { String qPath = "/me/identity/group"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "name", name); addBody(o, "role", role); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhGroup.class); }
[ "public", "OvhGroup", "identity_group_POST", "(", "String", "description", ",", "String", "name", ",", "OvhRoleEnum", "role", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/identity/group\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"name\"", ",", "name", ")", ";", "addBody", "(", "o", ",", "\"role\"", ",", "role", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhGroup", ".", "class", ")", ";", "}" ]
Create a new group REST: POST /me/identity/group @param name [required] Group's name @param description [required] Group's description @param role [required] Group's Role
[ "Create", "a", "new", "group" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L328-L337
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java
MercatorProjection.getPixelRelative
public static Point getPixelRelative(LatLong latLong, long mapSize, double x, double y) { """ Calculates the absolute pixel position for a map size and tile size relative to origin @param latLong the geographic position. @param mapSize precomputed size of map. @return the relative pixel position to the origin values (e.g. for a tile) """ double pixelX = MercatorProjection.longitudeToPixelX(latLong.longitude, mapSize) - x; double pixelY = MercatorProjection.latitudeToPixelY(latLong.latitude, mapSize) - y; return new Point(pixelX, pixelY); }
java
public static Point getPixelRelative(LatLong latLong, long mapSize, double x, double y) { double pixelX = MercatorProjection.longitudeToPixelX(latLong.longitude, mapSize) - x; double pixelY = MercatorProjection.latitudeToPixelY(latLong.latitude, mapSize) - y; return new Point(pixelX, pixelY); }
[ "public", "static", "Point", "getPixelRelative", "(", "LatLong", "latLong", ",", "long", "mapSize", ",", "double", "x", ",", "double", "y", ")", "{", "double", "pixelX", "=", "MercatorProjection", ".", "longitudeToPixelX", "(", "latLong", ".", "longitude", ",", "mapSize", ")", "-", "x", ";", "double", "pixelY", "=", "MercatorProjection", ".", "latitudeToPixelY", "(", "latLong", ".", "latitude", ",", "mapSize", ")", "-", "y", ";", "return", "new", "Point", "(", "pixelX", ",", "pixelY", ")", ";", "}" ]
Calculates the absolute pixel position for a map size and tile size relative to origin @param latLong the geographic position. @param mapSize precomputed size of map. @return the relative pixel position to the origin values (e.g. for a tile)
[ "Calculates", "the", "absolute", "pixel", "position", "for", "a", "map", "size", "and", "tile", "size", "relative", "to", "origin" ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L150-L154
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.sendComposingNotification
public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { """ Sends the notification that the receiver of the message is composing a reply. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException """ // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setComposing(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
java
public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setComposing(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
[ "public", "void", "sendComposingNotification", "(", "Jid", "to", ",", "String", "packetID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create the message to send", "Message", "msg", "=", "new", "Message", "(", "to", ")", ";", "// Create a MessageEvent Package and add it to the message", "MessageEvent", "messageEvent", "=", "new", "MessageEvent", "(", ")", ";", "messageEvent", ".", "setComposing", "(", "true", ")", ";", "messageEvent", ".", "setStanzaId", "(", "packetID", ")", ";", "msg", ".", "addExtension", "(", "messageEvent", ")", ";", "// Send the packet", "connection", "(", ")", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends the notification that the receiver of the message is composing a reply. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "the", "notification", "that", "the", "receiver", "of", "the", "message", "is", "composing", "a", "reply", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L255-L265
sagiegurari/fax4j
src/main/java/org/fax4j/spi/FaxJobMonitorImpl.java
FaxJobMonitorImpl.monitorFaxJobImpl
@Override public void monitorFaxJobImpl(FaxClientSpi faxClientSpi,FaxJob faxJob) { """ This function starts monitoring the requested fax job. @param faxClientSpi The fax client SPI @param faxJob The fax job to monitor """ //get fax job status FaxJobStatus faxJobStatus=faxClientSpi.getFaxJobStatus(faxJob); if(faxJobStatus==null) { throw new FaxException("Unable to extract fax job status for fax job: "+faxJob.getID()); } synchronized(this.LOCK) { Map<FaxJob,FaxJobStatus> faxJobMap=this.data.get(faxClientSpi); if(faxJobMap==null) { faxJobMap=new HashMap<FaxJob,FaxJobStatus>(500); this.data.put(faxClientSpi,faxJobMap); } //add new fax job faxJobMap.put(faxJob,faxJobStatus); if(!this.pollerTask.isRunning()) { this.pollerTask.startTask(); } } }
java
@Override public void monitorFaxJobImpl(FaxClientSpi faxClientSpi,FaxJob faxJob) { //get fax job status FaxJobStatus faxJobStatus=faxClientSpi.getFaxJobStatus(faxJob); if(faxJobStatus==null) { throw new FaxException("Unable to extract fax job status for fax job: "+faxJob.getID()); } synchronized(this.LOCK) { Map<FaxJob,FaxJobStatus> faxJobMap=this.data.get(faxClientSpi); if(faxJobMap==null) { faxJobMap=new HashMap<FaxJob,FaxJobStatus>(500); this.data.put(faxClientSpi,faxJobMap); } //add new fax job faxJobMap.put(faxJob,faxJobStatus); if(!this.pollerTask.isRunning()) { this.pollerTask.startTask(); } } }
[ "@", "Override", "public", "void", "monitorFaxJobImpl", "(", "FaxClientSpi", "faxClientSpi", ",", "FaxJob", "faxJob", ")", "{", "//get fax job status", "FaxJobStatus", "faxJobStatus", "=", "faxClientSpi", ".", "getFaxJobStatus", "(", "faxJob", ")", ";", "if", "(", "faxJobStatus", "==", "null", ")", "{", "throw", "new", "FaxException", "(", "\"Unable to extract fax job status for fax job: \"", "+", "faxJob", ".", "getID", "(", ")", ")", ";", "}", "synchronized", "(", "this", ".", "LOCK", ")", "{", "Map", "<", "FaxJob", ",", "FaxJobStatus", ">", "faxJobMap", "=", "this", ".", "data", ".", "get", "(", "faxClientSpi", ")", ";", "if", "(", "faxJobMap", "==", "null", ")", "{", "faxJobMap", "=", "new", "HashMap", "<", "FaxJob", ",", "FaxJobStatus", ">", "(", "500", ")", ";", "this", ".", "data", ".", "put", "(", "faxClientSpi", ",", "faxJobMap", ")", ";", "}", "//add new fax job", "faxJobMap", ".", "put", "(", "faxJob", ",", "faxJobStatus", ")", ";", "if", "(", "!", "this", ".", "pollerTask", ".", "isRunning", "(", ")", ")", "{", "this", ".", "pollerTask", ".", "startTask", "(", ")", ";", "}", "}", "}" ]
This function starts monitoring the requested fax job. @param faxClientSpi The fax client SPI @param faxJob The fax job to monitor
[ "This", "function", "starts", "monitoring", "the", "requested", "fax", "job", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/FaxJobMonitorImpl.java#L101-L128
segmentio/analytics-android
analytics/src/main/java/com/segment/analytics/internal/Utils.java
Utils.getResourceString
public static String getResourceString(Context context, String key) { """ Get the string resource for the given key. Returns null if not found. """ int id = getIdentifier(context, "string", key); if (id != 0) { return context.getResources().getString(id); } else { return null; } }
java
public static String getResourceString(Context context, String key) { int id = getIdentifier(context, "string", key); if (id != 0) { return context.getResources().getString(id); } else { return null; } }
[ "public", "static", "String", "getResourceString", "(", "Context", "context", ",", "String", "key", ")", "{", "int", "id", "=", "getIdentifier", "(", "context", ",", "\"string\"", ",", "key", ")", ";", "if", "(", "id", "!=", "0", ")", "{", "return", "context", ".", "getResources", "(", ")", ".", "getString", "(", "id", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the string resource for the given key. Returns null if not found.
[ "Get", "the", "string", "resource", "for", "the", "given", "key", ".", "Returns", "null", "if", "not", "found", "." ]
train
https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/internal/Utils.java#L289-L296
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.requestTimeout
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) { """ Specifies the timeout for a network request. @param timeout The timeout for a network request. @param unit The time unit of the specified timeout. @return This builder instance. """ assertNumericArgument(timeout, true); this.requestTimeout = unit.toMillis(timeout); return this; }
java
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) { assertNumericArgument(timeout, true); this.requestTimeout = unit.toMillis(timeout); return this; }
[ "public", "ConverterServerBuilder", "requestTimeout", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "assertNumericArgument", "(", "timeout", ",", "true", ")", ";", "this", ".", "requestTimeout", "=", "unit", ".", "toMillis", "(", "timeout", ")", ";", "return", "this", ";", "}" ]
Specifies the timeout for a network request. @param timeout The timeout for a network request. @param unit The time unit of the specified timeout. @return This builder instance.
[ "Specifies", "the", "timeout", "for", "a", "network", "request", "." ]
train
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L137-L141
zaproxy/zaproxy
src/org/parosproxy/paros/core/proxy/ProxyThread.java
ProxyThread.notifyPersistentConnectionListener
private boolean notifyPersistentConnectionListener(HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) { """ Go thru each listener and offer him to take over the connection. The first observer that returns true gets exclusive rights. @param httpMessage Contains HTTP request &amp; response. @param inSocket Encapsulates the TCP connection to the browser. @param method Provides more power to process response. @return Boolean to indicate if socket should be kept open. """ boolean keepSocketOpen = false; PersistentConnectionListener listener = null; List<PersistentConnectionListener> listenerList = parentServer.getPersistentConnectionListenerList(); for (int i=0; i<listenerList.size(); i++) { listener = listenerList.get(i); try { if (listener.onHandshakeResponse(httpMessage, inSocket, method)) { // inform as long as one listener wishes to overtake the connection keepSocketOpen = true; break; } } catch (Exception e) { log.error("An error occurred while notifying listener:", e); } } return keepSocketOpen; }
java
private boolean notifyPersistentConnectionListener(HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) { boolean keepSocketOpen = false; PersistentConnectionListener listener = null; List<PersistentConnectionListener> listenerList = parentServer.getPersistentConnectionListenerList(); for (int i=0; i<listenerList.size(); i++) { listener = listenerList.get(i); try { if (listener.onHandshakeResponse(httpMessage, inSocket, method)) { // inform as long as one listener wishes to overtake the connection keepSocketOpen = true; break; } } catch (Exception e) { log.error("An error occurred while notifying listener:", e); } } return keepSocketOpen; }
[ "private", "boolean", "notifyPersistentConnectionListener", "(", "HttpMessage", "httpMessage", ",", "Socket", "inSocket", ",", "ZapGetMethod", "method", ")", "{", "boolean", "keepSocketOpen", "=", "false", ";", "PersistentConnectionListener", "listener", "=", "null", ";", "List", "<", "PersistentConnectionListener", ">", "listenerList", "=", "parentServer", ".", "getPersistentConnectionListenerList", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "listenerList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "listener", "=", "listenerList", ".", "get", "(", "i", ")", ";", "try", "{", "if", "(", "listener", ".", "onHandshakeResponse", "(", "httpMessage", ",", "inSocket", ",", "method", ")", ")", "{", "// inform as long as one listener wishes to overtake the connection\r", "keepSocketOpen", "=", "true", ";", "break", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"An error occurred while notifying listener:\"", ",", "e", ")", ";", "}", "}", "return", "keepSocketOpen", ";", "}" ]
Go thru each listener and offer him to take over the connection. The first observer that returns true gets exclusive rights. @param httpMessage Contains HTTP request &amp; response. @param inSocket Encapsulates the TCP connection to the browser. @param method Provides more power to process response. @return Boolean to indicate if socket should be kept open.
[ "Go", "thru", "each", "listener", "and", "offer", "him", "to", "take", "over", "the", "connection", ".", "The", "first", "observer", "that", "returns", "true", "gets", "exclusive", "rights", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/proxy/ProxyThread.java#L754-L771
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayRemove
public static Expression arrayRemove(JsonArray array, Expression value) { """ Returned expression results in new array with all occurrences of value removed. """ return arrayRemove(x(array), value); }
java
public static Expression arrayRemove(JsonArray array, Expression value) { return arrayRemove(x(array), value); }
[ "public", "static", "Expression", "arrayRemove", "(", "JsonArray", "array", ",", "Expression", "value", ")", "{", "return", "arrayRemove", "(", "x", "(", "array", ")", ",", "value", ")", ";", "}" ]
Returned expression results in new array with all occurrences of value removed.
[ "Returned", "expression", "results", "in", "new", "array", "with", "all", "occurrences", "of", "value", "removed", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L358-L360
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.readFolder
public CmsFolder readFolder(String resourcename, CmsResourceFilter filter) throws CmsException { """ Reads a folder resource from the VFS, using the specified resource filter.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param resourcename the name of the folder resource to read (full current site relative path) @param filter the resource filter to use while reading @return the folder resource that was read @throws CmsException if the resource could not be read for any reason @see #readResource(String, CmsResourceFilter) """ return m_securityManager.readFolder(m_context, addSiteRoot(resourcename), filter); }
java
public CmsFolder readFolder(String resourcename, CmsResourceFilter filter) throws CmsException { return m_securityManager.readFolder(m_context, addSiteRoot(resourcename), filter); }
[ "public", "CmsFolder", "readFolder", "(", "String", "resourcename", ",", "CmsResourceFilter", "filter", ")", "throws", "CmsException", "{", "return", "m_securityManager", ".", "readFolder", "(", "m_context", ",", "addSiteRoot", "(", "resourcename", ")", ",", "filter", ")", ";", "}" ]
Reads a folder resource from the VFS, using the specified resource filter.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param resourcename the name of the folder resource to read (full current site relative path) @param filter the resource filter to use while reading @return the folder resource that was read @throws CmsException if the resource could not be read for any reason @see #readResource(String, CmsResourceFilter)
[ "Reads", "a", "folder", "resource", "from", "the", "VFS", "using", "the", "specified", "resource", "filter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L2603-L2606
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.decodeFromFile
@Nonnull @ReturnsMutableCopy public static byte [] decodeFromFile (@Nonnull final String filename) throws IOException { """ Convenience method for reading a base64-encoded file and decoding it. <p> As of v 2.3, if there is a error, the method will throw an IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param filename Filename for reading encoded data @return decoded byte array @throws IOException if there is an error @since 2.1 """ // Setup some useful variables final File file = new File (filename); // Check for size of file if (file.length () > Integer.MAX_VALUE) throw new IOException ("File is too big for this convenience method (" + file.length () + " bytes)."); final byte [] buffer = new byte [(int) file.length ()]; // Open a stream try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), DECODE)) { int nOfs = 0; int numBytes; // Read until done while ((numBytes = bis.read (buffer, nOfs, 4096)) >= 0) { nOfs += numBytes; } // Save in a variable to return final byte [] decodedData = new byte [nOfs]; System.arraycopy (buffer, 0, decodedData, 0, nOfs); return decodedData; } }
java
@Nonnull @ReturnsMutableCopy public static byte [] decodeFromFile (@Nonnull final String filename) throws IOException { // Setup some useful variables final File file = new File (filename); // Check for size of file if (file.length () > Integer.MAX_VALUE) throw new IOException ("File is too big for this convenience method (" + file.length () + " bytes)."); final byte [] buffer = new byte [(int) file.length ()]; // Open a stream try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), DECODE)) { int nOfs = 0; int numBytes; // Read until done while ((numBytes = bis.read (buffer, nOfs, 4096)) >= 0) { nOfs += numBytes; } // Save in a variable to return final byte [] decodedData = new byte [nOfs]; System.arraycopy (buffer, 0, decodedData, 0, nOfs); return decodedData; } }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "byte", "[", "]", "decodeFromFile", "(", "@", "Nonnull", "final", "String", "filename", ")", "throws", "IOException", "{", "// Setup some useful variables", "final", "File", "file", "=", "new", "File", "(", "filename", ")", ";", "// Check for size of file", "if", "(", "file", ".", "length", "(", ")", ">", "Integer", ".", "MAX_VALUE", ")", "throw", "new", "IOException", "(", "\"File is too big for this convenience method (\"", "+", "file", ".", "length", "(", ")", "+", "\" bytes).\"", ")", ";", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "(", "int", ")", "file", ".", "length", "(", ")", "]", ";", "// Open a stream", "try", "(", "final", "Base64InputStream", "bis", "=", "new", "Base64InputStream", "(", "FileHelper", ".", "getBufferedInputStream", "(", "file", ")", ",", "DECODE", ")", ")", "{", "int", "nOfs", "=", "0", ";", "int", "numBytes", ";", "// Read until done", "while", "(", "(", "numBytes", "=", "bis", ".", "read", "(", "buffer", ",", "nOfs", ",", "4096", ")", ")", ">=", "0", ")", "{", "nOfs", "+=", "numBytes", ";", "}", "// Save in a variable to return", "final", "byte", "[", "]", "decodedData", "=", "new", "byte", "[", "nOfs", "]", ";", "System", ".", "arraycopy", "(", "buffer", ",", "0", ",", "decodedData", ",", "0", ",", "nOfs", ")", ";", "return", "decodedData", ";", "}", "}" ]
Convenience method for reading a base64-encoded file and decoding it. <p> As of v 2.3, if there is a error, the method will throw an IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param filename Filename for reading encoded data @return decoded byte array @throws IOException if there is an error @since 2.1
[ "Convenience", "method", "for", "reading", "a", "base64", "-", "encoded", "file", "and", "decoding", "it", ".", "<p", ">", "As", "of", "v", "2", ".", "3", "if", "there", "is", "a", "error", "the", "method", "will", "throw", "an", "IOException", ".", "<b", ">", "This", "is", "new", "to", "v2", ".", "3!<", "/", "b", ">", "In", "earlier", "versions", "it", "just", "returned", "false", "but", "in", "retrospect", "that", "s", "a", "pretty", "poor", "way", "to", "handle", "it", ".", "<", "/", "p", ">" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2413-L2443
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java
MethodsBag.itos
public final static void itos(int i, int index, char[] buf) { """ Places characters representing the integer i into the character array buf. The characters are placed into the buffer backwards starting with the least significant digit at the specified index (exclusive), and working backwards from there. Will fail if i == Integer.MIN_VALUE @param i integer @param index index @param buf character buffer """ assert (!(i == Integer.MIN_VALUE)); int q, r; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Generate two digits per iteration while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf[--index] = DigitOnes[r]; buf[--index] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--index] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--index] = sign; } }
java
public final static void itos(int i, int index, char[] buf) { assert (!(i == Integer.MIN_VALUE)); int q, r; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Generate two digits per iteration while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf[--index] = DigitOnes[r]; buf[--index] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--index] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--index] = sign; } }
[ "public", "final", "static", "void", "itos", "(", "int", "i", ",", "int", "index", ",", "char", "[", "]", "buf", ")", "{", "assert", "(", "!", "(", "i", "==", "Integer", ".", "MIN_VALUE", ")", ")", ";", "int", "q", ",", "r", ";", "char", "sign", "=", "0", ";", "if", "(", "i", "<", "0", ")", "{", "sign", "=", "'", "'", ";", "i", "=", "-", "i", ";", "}", "// Generate two digits per iteration", "while", "(", "i", ">=", "65536", ")", "{", "q", "=", "i", "/", "100", ";", "// really: r = i - (q * 100);", "r", "=", "i", "-", "(", "(", "q", "<<", "6", ")", "+", "(", "q", "<<", "5", ")", "+", "(", "q", "<<", "2", ")", ")", ";", "i", "=", "q", ";", "buf", "[", "--", "index", "]", "=", "DigitOnes", "[", "r", "]", ";", "buf", "[", "--", "index", "]", "=", "DigitTens", "[", "r", "]", ";", "}", "// Fall thru to fast mode for smaller numbers", "// assert(i <= 65536, i);", "for", "(", ";", ";", ")", "{", "q", "=", "(", "i", "*", "52429", ")", ">>>", "(", "16", "+", "3", ")", ";", "r", "=", "i", "-", "(", "(", "q", "<<", "3", ")", "+", "(", "q", "<<", "1", ")", ")", ";", "// r = i-(q*10) ...", "buf", "[", "--", "index", "]", "=", "digits", "[", "r", "]", ";", "i", "=", "q", ";", "if", "(", "i", "==", "0", ")", "break", ";", "}", "if", "(", "sign", "!=", "0", ")", "{", "buf", "[", "--", "index", "]", "=", "sign", ";", "}", "}" ]
Places characters representing the integer i into the character array buf. The characters are placed into the buffer backwards starting with the least significant digit at the specified index (exclusive), and working backwards from there. Will fail if i == Integer.MIN_VALUE @param i integer @param index index @param buf character buffer
[ "Places", "characters", "representing", "the", "integer", "i", "into", "the", "character", "array", "buf", ".", "The", "characters", "are", "placed", "into", "the", "buffer", "backwards", "starting", "with", "the", "least", "significant", "digit", "at", "the", "specified", "index", "(", "exclusive", ")", "and", "working", "backwards", "from", "there", "." ]
train
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java#L317-L351
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.setGeolocation
public boolean setGeolocation(int iid, double latitude, double longitude) { """ This method is used to set the geolocation of a previously indexed vector. If the geolocation is already set, this method replaces it. @param iid The internal id of the vector @param latitude @param longitude @return true if geolocation is successfully set, false otherwise """ if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); TupleOutput output = new TupleOutput(); output.writeDouble(latitude); output.writeDouble(longitude); TupleBinding.outputToEntry(output, data); if (iidToGeolocationDB.put(null, key, data) == OperationStatus.SUCCESS) { return true; } else { return false; } }
java
public boolean setGeolocation(int iid, double latitude, double longitude) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); TupleOutput output = new TupleOutput(); output.writeDouble(latitude); output.writeDouble(longitude); TupleBinding.outputToEntry(output, data); if (iidToGeolocationDB.put(null, key, data) == OperationStatus.SUCCESS) { return true; } else { return false; } }
[ "public", "boolean", "setGeolocation", "(", "int", "iid", ",", "double", "latitude", ",", "double", "longitude", ")", "{", "if", "(", "iid", "<", "0", "||", "iid", ">", "loadCounter", ")", "{", "System", ".", "out", ".", "println", "(", "\"Internal id \"", "+", "iid", "+", "\" is out of range!\"", ")", ";", "return", "false", ";", "}", "DatabaseEntry", "key", "=", "new", "DatabaseEntry", "(", ")", ";", "DatabaseEntry", "data", "=", "new", "DatabaseEntry", "(", ")", ";", "IntegerBinding", ".", "intToEntry", "(", "iid", ",", "key", ")", ";", "TupleOutput", "output", "=", "new", "TupleOutput", "(", ")", ";", "output", ".", "writeDouble", "(", "latitude", ")", ";", "output", ".", "writeDouble", "(", "longitude", ")", ";", "TupleBinding", ".", "outputToEntry", "(", "output", ",", "data", ")", ";", "if", "(", "iidToGeolocationDB", ".", "put", "(", "null", ",", "key", ",", "data", ")", "==", "OperationStatus", ".", "SUCCESS", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
This method is used to set the geolocation of a previously indexed vector. If the geolocation is already set, this method replaces it. @param iid The internal id of the vector @param latitude @param longitude @return true if geolocation is successfully set, false otherwise
[ "This", "method", "is", "used", "to", "set", "the", "geolocation", "of", "a", "previously", "indexed", "vector", ".", "If", "the", "geolocation", "is", "already", "set", "this", "method", "replaces", "it", "." ]
train
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L477-L496
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedBackupShortTermRetentionPoliciesInner.java
ManagedBackupShortTermRetentionPoliciesInner.createOrUpdateAsync
public Observable<ManagedBackupShortTermRetentionPolicyInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String databaseName, Integer retentionDays) { """ Updates a managed database's short term retention policy. @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 databaseName The name of the database. @param retentionDays The backup retention period in days. This is how many days Point-in-Time Restore will be supported. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, retentionDays).map(new Func1<ServiceResponse<ManagedBackupShortTermRetentionPolicyInner>, ManagedBackupShortTermRetentionPolicyInner>() { @Override public ManagedBackupShortTermRetentionPolicyInner call(ServiceResponse<ManagedBackupShortTermRetentionPolicyInner> response) { return response.body(); } }); }
java
public Observable<ManagedBackupShortTermRetentionPolicyInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String databaseName, Integer retentionDays) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, retentionDays).map(new Func1<ServiceResponse<ManagedBackupShortTermRetentionPolicyInner>, ManagedBackupShortTermRetentionPolicyInner>() { @Override public ManagedBackupShortTermRetentionPolicyInner call(ServiceResponse<ManagedBackupShortTermRetentionPolicyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ManagedBackupShortTermRetentionPolicyInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "String", "databaseName", ",", "Integer", "retentionDays", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "databaseName", ",", "retentionDays", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ManagedBackupShortTermRetentionPolicyInner", ">", ",", "ManagedBackupShortTermRetentionPolicyInner", ">", "(", ")", "{", "@", "Override", "public", "ManagedBackupShortTermRetentionPolicyInner", "call", "(", "ServiceResponse", "<", "ManagedBackupShortTermRetentionPolicyInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a managed database's short term retention policy. @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 databaseName The name of the database. @param retentionDays The backup retention period in days. This is how many days Point-in-Time Restore will be supported. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "a", "managed", "database", "s", "short", "term", "retention", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedBackupShortTermRetentionPoliciesInner.java#L307-L314
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/concurrency/WorkQueue.java
WorkQueue.startWorkers
private void startWorkers(final ExecutorService executorService, final int numTasks) { """ Start worker threads with a shared log. @param executorService the executor service @param numTasks the number of worker tasks to start """ for (int i = 0; i < numTasks; i++) { workerFutures.add(executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { runWorkLoop(); return null; } })); } }
java
private void startWorkers(final ExecutorService executorService, final int numTasks) { for (int i = 0; i < numTasks; i++) { workerFutures.add(executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { runWorkLoop(); return null; } })); } }
[ "private", "void", "startWorkers", "(", "final", "ExecutorService", "executorService", ",", "final", "int", "numTasks", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numTasks", ";", "i", "++", ")", "{", "workerFutures", ".", "add", "(", "executorService", ".", "submit", "(", "new", "Callable", "<", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", ")", "throws", "Exception", "{", "runWorkLoop", "(", ")", ";", "return", "null", ";", "}", "}", ")", ")", ";", "}", "}" ]
Start worker threads with a shared log. @param executorService the executor service @param numTasks the number of worker tasks to start
[ "Start", "worker", "threads", "with", "a", "shared", "log", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/concurrency/WorkQueue.java#L196-L206
assertthat/selenium-shutterbug
src/main/java/com/assertthat/selenium_shutterbug/core/PageSnapshot.java
PageSnapshot.cropAround
public PageSnapshot cropAround(WebElement element, int offsetX, int offsetY) { """ Crop the image around specified element with offset. @param element WebElement to crop around @param offsetX offsetX around element in px @param offsetY offsetY around element in px @return instance of type PageSnapshot """ try{ image = ImageProcessor.cropAround(image, new Coordinates(element,devicePixelRatio), offsetX, offsetY); }catch(RasterFormatException rfe){ throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe); } return this; }
java
public PageSnapshot cropAround(WebElement element, int offsetX, int offsetY) { try{ image = ImageProcessor.cropAround(image, new Coordinates(element,devicePixelRatio), offsetX, offsetY); }catch(RasterFormatException rfe){ throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe); } return this; }
[ "public", "PageSnapshot", "cropAround", "(", "WebElement", "element", ",", "int", "offsetX", ",", "int", "offsetY", ")", "{", "try", "{", "image", "=", "ImageProcessor", ".", "cropAround", "(", "image", ",", "new", "Coordinates", "(", "element", ",", "devicePixelRatio", ")", ",", "offsetX", ",", "offsetY", ")", ";", "}", "catch", "(", "RasterFormatException", "rfe", ")", "{", "throw", "new", "ElementOutsideViewportException", "(", "ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE", ",", "rfe", ")", ";", "}", "return", "this", ";", "}" ]
Crop the image around specified element with offset. @param element WebElement to crop around @param offsetX offsetX around element in px @param offsetY offsetY around element in px @return instance of type PageSnapshot
[ "Crop", "the", "image", "around", "specified", "element", "with", "offset", "." ]
train
https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/PageSnapshot.java#L167-L174
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java
ComboBoxArrowButtonPainter.getComboBoxButtonBorderPaint
public Paint getComboBoxButtonBorderPaint(Shape s, CommonControlState type) { """ DOCUMENT ME! @param s DOCUMENT ME! @param type DOCUMENT ME! @return DOCUMENT ME! """ TwoColors colors = getCommonBorderColors(type); return createVerticalGradient(s, colors); }
java
public Paint getComboBoxButtonBorderPaint(Shape s, CommonControlState type) { TwoColors colors = getCommonBorderColors(type); return createVerticalGradient(s, colors); }
[ "public", "Paint", "getComboBoxButtonBorderPaint", "(", "Shape", "s", ",", "CommonControlState", "type", ")", "{", "TwoColors", "colors", "=", "getCommonBorderColors", "(", "type", ")", ";", "return", "createVerticalGradient", "(", "s", ",", "colors", ")", ";", "}" ]
DOCUMENT ME! @param s DOCUMENT ME! @param type DOCUMENT ME! @return DOCUMENT ME!
[ "DOCUMENT", "ME!" ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java#L230-L234
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnGetReductionIndicesSize
public static int cudnnGetReductionIndicesSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { """ Helper function to return the minimum size of the index space to be passed to the reduction given the input and output tensors """ return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
java
public static int cudnnGetReductionIndicesSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
[ "public", "static", "int", "cudnnGetReductionIndicesSize", "(", "cudnnHandle", "handle", ",", "cudnnReduceTensorDescriptor", "reduceTensorDesc", ",", "cudnnTensorDescriptor", "aDesc", ",", "cudnnTensorDescriptor", "cDesc", ",", "long", "[", "]", "sizeInBytes", ")", "{", "return", "checkResult", "(", "cudnnGetReductionIndicesSizeNative", "(", "handle", ",", "reduceTensorDesc", ",", "aDesc", ",", "cDesc", ",", "sizeInBytes", ")", ")", ";", "}" ]
Helper function to return the minimum size of the index space to be passed to the reduction given the input and output tensors
[ "Helper", "function", "to", "return", "the", "minimum", "size", "of", "the", "index", "space", "to", "be", "passed", "to", "the", "reduction", "given", "the", "input", "and", "output", "tensors" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L619-L627
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java
HiveDataset.sortPartitions
public static List<Partition> sortPartitions(List<Partition> partitions) { """ Sort all partitions inplace on the basis of complete name ie dbName.tableName.partitionName """ Collections.sort(partitions, new Comparator<Partition>() { @Override public int compare(Partition o1, Partition o2) { return o1.getCompleteName().compareTo(o2.getCompleteName()); } }); return partitions; }
java
public static List<Partition> sortPartitions(List<Partition> partitions) { Collections.sort(partitions, new Comparator<Partition>() { @Override public int compare(Partition o1, Partition o2) { return o1.getCompleteName().compareTo(o2.getCompleteName()); } }); return partitions; }
[ "public", "static", "List", "<", "Partition", ">", "sortPartitions", "(", "List", "<", "Partition", ">", "partitions", ")", "{", "Collections", ".", "sort", "(", "partitions", ",", "new", "Comparator", "<", "Partition", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Partition", "o1", ",", "Partition", "o2", ")", "{", "return", "o1", ".", "getCompleteName", "(", ")", ".", "compareTo", "(", "o2", ".", "getCompleteName", "(", ")", ")", ";", "}", "}", ")", ";", "return", "partitions", ";", "}" ]
Sort all partitions inplace on the basis of complete name ie dbName.tableName.partitionName
[ "Sort", "all", "partitions", "inplace", "on", "the", "basis", "of", "complete", "name", "ie", "dbName", ".", "tableName", ".", "partitionName" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java#L303-L311
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java
BooleanExtensions.operator_greaterEqualsThan
@Pure @Inline(value = "($3.compare($1, $2) >= 0)", imported = Booleans.class) public static boolean operator_greaterEqualsThan(boolean a, boolean b) { """ The binary <code>greaterEqualsThan</code> operator for boolean values. {@code false} is considered less than {@code true}. @see Boolean#compareTo(Boolean) @see Booleans#compare(boolean, boolean) @param a a boolean. @param b another boolean. @return <code>Booleans.compare(a, b)&gt;=0</code> @since 2.4 """ return Booleans.compare(a, b) >= 0; }
java
@Pure @Inline(value = "($3.compare($1, $2) >= 0)", imported = Booleans.class) public static boolean operator_greaterEqualsThan(boolean a, boolean b) { return Booleans.compare(a, b) >= 0; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($3.compare($1, $2) >= 0)\"", ",", "imported", "=", "Booleans", ".", "class", ")", "public", "static", "boolean", "operator_greaterEqualsThan", "(", "boolean", "a", ",", "boolean", "b", ")", "{", "return", "Booleans", ".", "compare", "(", "a", ",", "b", ")", ">=", "0", ";", "}" ]
The binary <code>greaterEqualsThan</code> operator for boolean values. {@code false} is considered less than {@code true}. @see Boolean#compareTo(Boolean) @see Booleans#compare(boolean, boolean) @param a a boolean. @param b another boolean. @return <code>Booleans.compare(a, b)&gt;=0</code> @since 2.4
[ "The", "binary", "<code", ">", "greaterEqualsThan<", "/", "code", ">", "operator", "for", "boolean", "values", ".", "{", "@code", "false", "}", "is", "considered", "less", "than", "{", "@code", "true", "}", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java#L171-L175
m-m-m/util
version/src/main/java/net/sf/mmm/util/version/base/AbstractNameVersion.java
AbstractNameVersion.doWrite
protected void doWrite(Appendable appendable, boolean fromToString) throws IOException { """ Called from {@link #write(Appendable)} or {@link #toString()} to write the serialized data of this object. @param appendable the {@link StringBuilder} where to {@link StringBuilder#append(String) append} to. @param fromToString - {@code true} if called from {@link #toString()}, {@code false} otherwise. Can be ignored if not relevant. @throws IOException if an error occurred whilst writing the data. """ appendable.append(getName()); appendable.append(NAME_VERSION_SEPARATOR); appendable.append(this.version); }
java
protected void doWrite(Appendable appendable, boolean fromToString) throws IOException { appendable.append(getName()); appendable.append(NAME_VERSION_SEPARATOR); appendable.append(this.version); }
[ "protected", "void", "doWrite", "(", "Appendable", "appendable", ",", "boolean", "fromToString", ")", "throws", "IOException", "{", "appendable", ".", "append", "(", "getName", "(", ")", ")", ";", "appendable", ".", "append", "(", "NAME_VERSION_SEPARATOR", ")", ";", "appendable", ".", "append", "(", "this", ".", "version", ")", ";", "}" ]
Called from {@link #write(Appendable)} or {@link #toString()} to write the serialized data of this object. @param appendable the {@link StringBuilder} where to {@link StringBuilder#append(String) append} to. @param fromToString - {@code true} if called from {@link #toString()}, {@code false} otherwise. Can be ignored if not relevant. @throws IOException if an error occurred whilst writing the data.
[ "Called", "from", "{", "@link", "#write", "(", "Appendable", ")", "}", "or", "{", "@link", "#toString", "()", "}", "to", "write", "the", "serialized", "data", "of", "this", "object", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/version/src/main/java/net/sf/mmm/util/version/base/AbstractNameVersion.java#L67-L72
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java
CPSpecificationOptionWrapper.getTitle
@Override public String getTitle(String languageId, boolean useDefault) { """ Returns the localized title of this cp specification option in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized title of this cp specification option """ return _cpSpecificationOption.getTitle(languageId, useDefault); }
java
@Override public String getTitle(String languageId, boolean useDefault) { return _cpSpecificationOption.getTitle(languageId, useDefault); }
[ "@", "Override", "public", "String", "getTitle", "(", "String", "languageId", ",", "boolean", "useDefault", ")", "{", "return", "_cpSpecificationOption", ".", "getTitle", "(", "languageId", ",", "useDefault", ")", ";", "}" ]
Returns the localized title of this cp specification option in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized title of this cp specification option
[ "Returns", "the", "localized", "title", "of", "this", "cp", "specification", "option", "in", "the", "language", "optionally", "using", "the", "default", "language", "if", "no", "localization", "exists", "for", "the", "requested", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java#L433-L436
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java
ThriftRangeUtils.deepTokenRanges
public List<DeepTokenRange> deepTokenRanges(List<CfSplit> splits, List<String> endpoints) { """ Returns the Deep splits represented by the specified Thrift splits using the specified endpoints for all of them. Note that the returned list can contain one more ranges than the specified because the range containing the partitioner's minimum token are divided into two ranges. @param splits the Thrift splits to be converted. @param endpoints the endpoints list to be set in each generated Deep split @return the {@link com.stratio.deep.commons.rdd.DeepTokenRange}s represented by the specified {@link org.apache.cassandra.thrift.CfSplit}s """ List<DeepTokenRange> result = new ArrayList<>(); for (CfSplit split : splits) { Comparable splitStart = tokenAsComparable(split.getStart_token()); Comparable splitEnd = tokenAsComparable(split.getEnd_token()); if (splitStart.equals(splitEnd)) { result.add(new DeepTokenRange(minToken, minToken, endpoints)); } else if (splitStart.compareTo(splitEnd) > 0) { result.add(new DeepTokenRange(splitStart, minToken, endpoints)); result.add(new DeepTokenRange(minToken, splitEnd, endpoints)); } else { result.add(new DeepTokenRange(splitStart, splitEnd, endpoints)); } } return result; }
java
public List<DeepTokenRange> deepTokenRanges(List<CfSplit> splits, List<String> endpoints) { List<DeepTokenRange> result = new ArrayList<>(); for (CfSplit split : splits) { Comparable splitStart = tokenAsComparable(split.getStart_token()); Comparable splitEnd = tokenAsComparable(split.getEnd_token()); if (splitStart.equals(splitEnd)) { result.add(new DeepTokenRange(minToken, minToken, endpoints)); } else if (splitStart.compareTo(splitEnd) > 0) { result.add(new DeepTokenRange(splitStart, minToken, endpoints)); result.add(new DeepTokenRange(minToken, splitEnd, endpoints)); } else { result.add(new DeepTokenRange(splitStart, splitEnd, endpoints)); } } return result; }
[ "public", "List", "<", "DeepTokenRange", ">", "deepTokenRanges", "(", "List", "<", "CfSplit", ">", "splits", ",", "List", "<", "String", ">", "endpoints", ")", "{", "List", "<", "DeepTokenRange", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "CfSplit", "split", ":", "splits", ")", "{", "Comparable", "splitStart", "=", "tokenAsComparable", "(", "split", ".", "getStart_token", "(", ")", ")", ";", "Comparable", "splitEnd", "=", "tokenAsComparable", "(", "split", ".", "getEnd_token", "(", ")", ")", ";", "if", "(", "splitStart", ".", "equals", "(", "splitEnd", ")", ")", "{", "result", ".", "add", "(", "new", "DeepTokenRange", "(", "minToken", ",", "minToken", ",", "endpoints", ")", ")", ";", "}", "else", "if", "(", "splitStart", ".", "compareTo", "(", "splitEnd", ")", ">", "0", ")", "{", "result", ".", "add", "(", "new", "DeepTokenRange", "(", "splitStart", ",", "minToken", ",", "endpoints", ")", ")", ";", "result", ".", "add", "(", "new", "DeepTokenRange", "(", "minToken", ",", "splitEnd", ",", "endpoints", ")", ")", ";", "}", "else", "{", "result", ".", "add", "(", "new", "DeepTokenRange", "(", "splitStart", ",", "splitEnd", ",", "endpoints", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns the Deep splits represented by the specified Thrift splits using the specified endpoints for all of them. Note that the returned list can contain one more ranges than the specified because the range containing the partitioner's minimum token are divided into two ranges. @param splits the Thrift splits to be converted. @param endpoints the endpoints list to be set in each generated Deep split @return the {@link com.stratio.deep.commons.rdd.DeepTokenRange}s represented by the specified {@link org.apache.cassandra.thrift.CfSplit}s
[ "Returns", "the", "Deep", "splits", "represented", "by", "the", "specified", "Thrift", "splits", "using", "the", "specified", "endpoints", "for", "all", "of", "them", ".", "Note", "that", "the", "returned", "list", "can", "contain", "one", "more", "ranges", "than", "the", "specified", "because", "the", "range", "containing", "the", "partitioner", "s", "minimum", "token", "are", "divided", "into", "two", "ranges", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/thrift/ThriftRangeUtils.java#L189-L204
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java
LoadBalancersInner.beginUpdateTags
public LoadBalancerInner beginUpdateTags(String resourceGroupName, String loadBalancerName, Map<String, String> tags) { """ Updates a load balancer tags. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @param tags Resource tags. @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 LoadBalancerInner object if successful. """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, loadBalancerName, tags).toBlocking().single().body(); }
java
public LoadBalancerInner beginUpdateTags(String resourceGroupName, String loadBalancerName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, loadBalancerName, tags).toBlocking().single().body(); }
[ "public", "LoadBalancerInner", "beginUpdateTags", "(", "String", "resourceGroupName", ",", "String", "loadBalancerName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "loadBalancerName", ",", "tags", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates a load balancer tags. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @param tags Resource tags. @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 LoadBalancerInner object if successful.
[ "Updates", "a", "load", "balancer", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java#L835-L837
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqldatabase
public static void sqldatabase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { """ database translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens """ zeroArgumentFunctionCall(buf, "current_database()", "database", parsedArgs); }
java
public static void sqldatabase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { zeroArgumentFunctionCall(buf, "current_database()", "database", parsedArgs); }
[ "public", "static", "void", "sqldatabase", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "zeroArgumentFunctionCall", "(", "buf", ",", "\"current_database()\"", ",", "\"database\"", ",", "parsedArgs", ")", ";", "}" ]
database translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "database", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L615-L617
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.deleteConversation
public Observable<ComapiResult<Void>> deleteConversation(@NonNull final String conversationId, final String eTag) { """ Returns observable to create a conversation. @param conversationId ID of a conversation to delete. @param eTag ETag for server to check if local version of the data is the same as the one the server side. @return Observable to to create a conversation. """ final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueDeleteConversation(conversationId, eTag); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doDeleteConversation(token, conversationId, eTag); } }
java
public Observable<ComapiResult<Void>> deleteConversation(@NonNull final String conversationId, final String eTag) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueDeleteConversation(conversationId, eTag); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doDeleteConversation(token, conversationId, eTag); } }
[ "public", "Observable", "<", "ComapiResult", "<", "Void", ">", ">", "deleteConversation", "(", "@", "NonNull", "final", "String", "conversationId", ",", "final", "String", "eTag", ")", "{", "final", "String", "token", "=", "getToken", "(", ")", ";", "if", "(", "sessionController", ".", "isCreatingSession", "(", ")", ")", "{", "return", "getTaskQueue", "(", ")", ".", "queueDeleteConversation", "(", "conversationId", ",", "eTag", ")", ";", "}", "else", "if", "(", "TextUtils", ".", "isEmpty", "(", "token", ")", ")", "{", "return", "Observable", ".", "error", "(", "getSessionStateErrorDescription", "(", ")", ")", ";", "}", "else", "{", "return", "doDeleteConversation", "(", "token", ",", "conversationId", ",", "eTag", ")", ";", "}", "}" ]
Returns observable to create a conversation. @param conversationId ID of a conversation to delete. @param eTag ETag for server to check if local version of the data is the same as the one the server side. @return Observable to to create a conversation.
[ "Returns", "observable", "to", "create", "a", "conversation", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L444-L455
VoltDB/voltdb
src/frontend/org/voltdb/compiler/VoltDDLElementTracker.java
VoltDDLElementTracker.addProcedurePartitionInfoTo
public void addProcedurePartitionInfoTo(String procedureName, ProcedurePartitionData data) throws VoltCompilerException { """ Associates the given partition info to the given tracked procedure @param procedureName the short name of the procedure name @param partitionInfo the partition info to associate with the procedure @throws VoltCompilerException when there is no corresponding tracked procedure """ ProcedureDescriptor descriptor = m_procedureMap.get(procedureName); if( descriptor == null) { throw m_compiler.new VoltCompilerException(String.format( "Partition references an undefined procedure \"%s\"", procedureName)); } // need to re-instantiate as descriptor fields are final if( descriptor.m_stmtLiterals == null) { // the longer form constructor asserts on singleStatement descriptor = m_compiler.new ProcedureDescriptor( descriptor.m_authGroups, descriptor.m_class, data); } else { descriptor = m_compiler.new ProcedureDescriptor( descriptor.m_authGroups, descriptor.m_className, descriptor.m_stmtLiterals, descriptor.m_joinOrder, data, false, descriptor.m_class); } m_procedureMap.put(procedureName, descriptor); }
java
public void addProcedurePartitionInfoTo(String procedureName, ProcedurePartitionData data) throws VoltCompilerException { ProcedureDescriptor descriptor = m_procedureMap.get(procedureName); if( descriptor == null) { throw m_compiler.new VoltCompilerException(String.format( "Partition references an undefined procedure \"%s\"", procedureName)); } // need to re-instantiate as descriptor fields are final if( descriptor.m_stmtLiterals == null) { // the longer form constructor asserts on singleStatement descriptor = m_compiler.new ProcedureDescriptor( descriptor.m_authGroups, descriptor.m_class, data); } else { descriptor = m_compiler.new ProcedureDescriptor( descriptor.m_authGroups, descriptor.m_className, descriptor.m_stmtLiterals, descriptor.m_joinOrder, data, false, descriptor.m_class); } m_procedureMap.put(procedureName, descriptor); }
[ "public", "void", "addProcedurePartitionInfoTo", "(", "String", "procedureName", ",", "ProcedurePartitionData", "data", ")", "throws", "VoltCompilerException", "{", "ProcedureDescriptor", "descriptor", "=", "m_procedureMap", ".", "get", "(", "procedureName", ")", ";", "if", "(", "descriptor", "==", "null", ")", "{", "throw", "m_compiler", ".", "new", "VoltCompilerException", "(", "String", ".", "format", "(", "\"Partition references an undefined procedure \\\"%s\\\"\"", ",", "procedureName", ")", ")", ";", "}", "// need to re-instantiate as descriptor fields are final", "if", "(", "descriptor", ".", "m_stmtLiterals", "==", "null", ")", "{", "// the longer form constructor asserts on singleStatement", "descriptor", "=", "m_compiler", ".", "new", "ProcedureDescriptor", "(", "descriptor", ".", "m_authGroups", ",", "descriptor", ".", "m_class", ",", "data", ")", ";", "}", "else", "{", "descriptor", "=", "m_compiler", ".", "new", "ProcedureDescriptor", "(", "descriptor", ".", "m_authGroups", ",", "descriptor", ".", "m_className", ",", "descriptor", ".", "m_stmtLiterals", ",", "descriptor", ".", "m_joinOrder", ",", "data", ",", "false", ",", "descriptor", ".", "m_class", ")", ";", "}", "m_procedureMap", ".", "put", "(", "procedureName", ",", "descriptor", ")", ";", "}" ]
Associates the given partition info to the given tracked procedure @param procedureName the short name of the procedure name @param partitionInfo the partition info to associate with the procedure @throws VoltCompilerException when there is no corresponding tracked procedure
[ "Associates", "the", "given", "partition", "info", "to", "the", "given", "tracked", "procedure" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltDDLElementTracker.java#L151-L179
chen0040/java-genetic-programming
src/main/java/com/github/chen0040/gp/lgp/gp/Replacement.java
Replacement.compete
public static Program compete(List<Program> programs, Program current, Program candidate, LGP manager, RandEngine randEngine) { """ this method returns the pointer to the loser in the competition for survival; """ if(manager.getReplacementStrategy() == LGPReplacementStrategy.DirectCompetition) { if (CollectionUtils.isBetterThan(candidate, current)) { int index = programs.indexOf(current); programs.set(index, candidate); return current; } else { return candidate; } } else { if(randEngine.uniform() <= manager.getReplacementProbability()){ int index = programs.indexOf(current); programs.set(index, candidate); return current; } else { return candidate; } } }
java
public static Program compete(List<Program> programs, Program current, Program candidate, LGP manager, RandEngine randEngine) { if(manager.getReplacementStrategy() == LGPReplacementStrategy.DirectCompetition) { if (CollectionUtils.isBetterThan(candidate, current)) { int index = programs.indexOf(current); programs.set(index, candidate); return current; } else { return candidate; } } else { if(randEngine.uniform() <= manager.getReplacementProbability()){ int index = programs.indexOf(current); programs.set(index, candidate); return current; } else { return candidate; } } }
[ "public", "static", "Program", "compete", "(", "List", "<", "Program", ">", "programs", ",", "Program", "current", ",", "Program", "candidate", ",", "LGP", "manager", ",", "RandEngine", "randEngine", ")", "{", "if", "(", "manager", ".", "getReplacementStrategy", "(", ")", "==", "LGPReplacementStrategy", ".", "DirectCompetition", ")", "{", "if", "(", "CollectionUtils", ".", "isBetterThan", "(", "candidate", ",", "current", ")", ")", "{", "int", "index", "=", "programs", ".", "indexOf", "(", "current", ")", ";", "programs", ".", "set", "(", "index", ",", "candidate", ")", ";", "return", "current", ";", "}", "else", "{", "return", "candidate", ";", "}", "}", "else", "{", "if", "(", "randEngine", ".", "uniform", "(", ")", "<=", "manager", ".", "getReplacementProbability", "(", ")", ")", "{", "int", "index", "=", "programs", ".", "indexOf", "(", "current", ")", ";", "programs", ".", "set", "(", "index", ",", "candidate", ")", ";", "return", "current", ";", "}", "else", "{", "return", "candidate", ";", "}", "}", "}" ]
this method returns the pointer to the loser in the competition for survival;
[ "this", "method", "returns", "the", "pointer", "to", "the", "loser", "in", "the", "competition", "for", "survival", ";" ]
train
https://github.com/chen0040/java-genetic-programming/blob/498fc8f4407ea9d45f2e0ac797a8948da337c74f/src/main/java/com/github/chen0040/gp/lgp/gp/Replacement.java#L19-L38
Stratio/bdt
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
DatabaseSpec.connectToElasticSearch
@Given("^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$") public void connectToElasticSearch(String host, String foo, String nativePort, String bar, String clusterName) throws DBException, UnknownHostException, NumberFormatException { """ Connect to ElasticSearch using custom parameters @param host ES host @param foo regex needed to match method @param nativePort ES port @param bar regex needed to match method @param clusterName ES clustername @throws DBException exception @throws UnknownHostException exception @throws NumberFormatException exception """ LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); if (clusterName != null) { settings_map.put("cluster.name", clusterName); } else { settings_map.put("cluster.name", ES_DEFAULT_CLUSTER_NAME); } commonspec.getElasticSearchClient().setSettings(settings_map); if (nativePort != null) { commonspec.getElasticSearchClient().setNativePort(Integer.valueOf(nativePort)); } else { commonspec.getElasticSearchClient().setNativePort(ES_DEFAULT_NATIVE_PORT); } commonspec.getElasticSearchClient().setHost(host); commonspec.getElasticSearchClient().connect(); }
java
@Given("^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$") public void connectToElasticSearch(String host, String foo, String nativePort, String bar, String clusterName) throws DBException, UnknownHostException, NumberFormatException { LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); if (clusterName != null) { settings_map.put("cluster.name", clusterName); } else { settings_map.put("cluster.name", ES_DEFAULT_CLUSTER_NAME); } commonspec.getElasticSearchClient().setSettings(settings_map); if (nativePort != null) { commonspec.getElasticSearchClient().setNativePort(Integer.valueOf(nativePort)); } else { commonspec.getElasticSearchClient().setNativePort(ES_DEFAULT_NATIVE_PORT); } commonspec.getElasticSearchClient().setHost(host); commonspec.getElasticSearchClient().connect(); }
[ "@", "Given", "(", "\"^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$\"", ")", "public", "void", "connectToElasticSearch", "(", "String", "host", ",", "String", "foo", ",", "String", "nativePort", ",", "String", "bar", ",", "String", "clusterName", ")", "throws", "DBException", ",", "UnknownHostException", ",", "NumberFormatException", "{", "LinkedHashMap", "<", "String", ",", "Object", ">", "settings_map", "=", "new", "LinkedHashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "if", "(", "clusterName", "!=", "null", ")", "{", "settings_map", ".", "put", "(", "\"cluster.name\"", ",", "clusterName", ")", ";", "}", "else", "{", "settings_map", ".", "put", "(", "\"cluster.name\"", ",", "ES_DEFAULT_CLUSTER_NAME", ")", ";", "}", "commonspec", ".", "getElasticSearchClient", "(", ")", ".", "setSettings", "(", "settings_map", ")", ";", "if", "(", "nativePort", "!=", "null", ")", "{", "commonspec", ".", "getElasticSearchClient", "(", ")", ".", "setNativePort", "(", "Integer", ".", "valueOf", "(", "nativePort", ")", ")", ";", "}", "else", "{", "commonspec", ".", "getElasticSearchClient", "(", ")", ".", "setNativePort", "(", "ES_DEFAULT_NATIVE_PORT", ")", ";", "}", "commonspec", ".", "getElasticSearchClient", "(", ")", ".", "setHost", "(", "host", ")", ";", "commonspec", ".", "getElasticSearchClient", "(", ")", ".", "connect", "(", ")", ";", "}" ]
Connect to ElasticSearch using custom parameters @param host ES host @param foo regex needed to match method @param nativePort ES port @param bar regex needed to match method @param clusterName ES clustername @throws DBException exception @throws UnknownHostException exception @throws NumberFormatException exception
[ "Connect", "to", "ElasticSearch", "using", "custom", "parameters" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L135-L151
OpenLiberty/open-liberty
dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkManagerImpl.java
WorkManagerImpl.doWork
@Override public void doWork( Work work, long startTimeout, ExecutionContext execContext, WorkListener workListener) throws WorkException { """ This method does not return until the work is completed as the caller expects to wait until the work is completed before getting control back. This method accomplishes this by NOT spinning a thread. @pre providerId != null @param work @param startTimeout @param execContext @param workListener @throws WorkException @see <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/resource/spi/work/WorkManager.html#doWork(com.ibm.javarx.spi.work.Work, long, com.ibm.javarx.spi.work.ExecutionContext, com.ibm.javarx.spi.work.WorkListener)"> com.ibm.javarx.spi.work.WorkManager.doWork(Work, long, ExecutionContext, WorkListener)</a> """ try { beforeRunCheck(work, workListener, startTimeout); new WorkProxy(work, startTimeout, execContext, workListener, bootstrapContext, runningWork, false).call(); } catch (WorkException ex) { throw ex; } catch (Throwable t) { WorkRejectedException wrex = new WorkRejectedException(t); wrex.setErrorCode(WorkException.INTERNAL); if (workListener != null) workListener.workRejected(new WorkEvent(work, WorkEvent.WORK_REJECTED, work, wrex)); throw wrex; } }
java
@Override public void doWork( Work work, long startTimeout, ExecutionContext execContext, WorkListener workListener) throws WorkException { try { beforeRunCheck(work, workListener, startTimeout); new WorkProxy(work, startTimeout, execContext, workListener, bootstrapContext, runningWork, false).call(); } catch (WorkException ex) { throw ex; } catch (Throwable t) { WorkRejectedException wrex = new WorkRejectedException(t); wrex.setErrorCode(WorkException.INTERNAL); if (workListener != null) workListener.workRejected(new WorkEvent(work, WorkEvent.WORK_REJECTED, work, wrex)); throw wrex; } }
[ "@", "Override", "public", "void", "doWork", "(", "Work", "work", ",", "long", "startTimeout", ",", "ExecutionContext", "execContext", ",", "WorkListener", "workListener", ")", "throws", "WorkException", "{", "try", "{", "beforeRunCheck", "(", "work", ",", "workListener", ",", "startTimeout", ")", ";", "new", "WorkProxy", "(", "work", ",", "startTimeout", ",", "execContext", ",", "workListener", ",", "bootstrapContext", ",", "runningWork", ",", "false", ")", ".", "call", "(", ")", ";", "}", "catch", "(", "WorkException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "WorkRejectedException", "wrex", "=", "new", "WorkRejectedException", "(", "t", ")", ";", "wrex", ".", "setErrorCode", "(", "WorkException", ".", "INTERNAL", ")", ";", "if", "(", "workListener", "!=", "null", ")", "workListener", ".", "workRejected", "(", "new", "WorkEvent", "(", "work", ",", "WorkEvent", ".", "WORK_REJECTED", ",", "work", ",", "wrex", ")", ")", ";", "throw", "wrex", ";", "}", "}" ]
This method does not return until the work is completed as the caller expects to wait until the work is completed before getting control back. This method accomplishes this by NOT spinning a thread. @pre providerId != null @param work @param startTimeout @param execContext @param workListener @throws WorkException @see <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/resource/spi/work/WorkManager.html#doWork(com.ibm.javarx.spi.work.Work, long, com.ibm.javarx.spi.work.ExecutionContext, com.ibm.javarx.spi.work.WorkListener)"> com.ibm.javarx.spi.work.WorkManager.doWork(Work, long, ExecutionContext, WorkListener)</a>
[ "This", "method", "does", "not", "return", "until", "the", "work", "is", "completed", "as", "the", "caller", "expects", "to", "wait", "until", "the", "work", "is", "completed", "before", "getting", "control", "back", ".", "This", "method", "accomplishes", "this", "by", "NOT", "spinning", "a", "thread", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkManagerImpl.java#L102-L122
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/TriggersInner.java
TriggersInner.beginCreateOrUpdate
public TriggerInner beginCreateOrUpdate(String deviceName, String name, String resourceGroupName, TriggerInner trigger) { """ Creates or updates a trigger. @param deviceName Creates or updates a trigger @param name The trigger name. @param resourceGroupName The resource group name. @param trigger The trigger. @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 TriggerInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, trigger).toBlocking().single().body(); }
java
public TriggerInner beginCreateOrUpdate(String deviceName, String name, String resourceGroupName, TriggerInner trigger) { return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, trigger).toBlocking().single().body(); }
[ "public", "TriggerInner", "beginCreateOrUpdate", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ",", "TriggerInner", "trigger", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGroupName", ",", "trigger", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a trigger. @param deviceName Creates or updates a trigger @param name The trigger name. @param resourceGroupName The resource group name. @param trigger The trigger. @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 TriggerInner object if successful.
[ "Creates", "or", "updates", "a", "trigger", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/TriggersInner.java#L528-L530
dbracewell/mango
src/main/java/com/davidbracewell/json/JsonWriter.java
JsonWriter.property
protected JsonWriter property(String key, Iterable<?> iterable) throws IOException { """ Writes an iterable with the given key name @param key the key name for the collection @param iterable the iterable to be written @return This structured writer @throws IOException Something went wrong writing """ Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array."); beginArray(key); for (Object o : iterable) { value(o); } endArray(); return this; }
java
protected JsonWriter property(String key, Iterable<?> iterable) throws IOException { Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array."); beginArray(key); for (Object o : iterable) { value(o); } endArray(); return this; }
[ "protected", "JsonWriter", "property", "(", "String", "key", ",", "Iterable", "<", "?", ">", "iterable", ")", "throws", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "!", "inArray", "(", ")", ",", "\"Cannot write a property inside an array.\"", ")", ";", "beginArray", "(", "key", ")", ";", "for", "(", "Object", "o", ":", "iterable", ")", "{", "value", "(", "o", ")", ";", "}", "endArray", "(", ")", ";", "return", "this", ";", "}" ]
Writes an iterable with the given key name @param key the key name for the collection @param iterable the iterable to be written @return This structured writer @throws IOException Something went wrong writing
[ "Writes", "an", "iterable", "with", "the", "given", "key", "name" ]
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/json/JsonWriter.java#L262-L270
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java
AbstractFilterRegistrationBean.setDispatcherTypes
public void setDispatcherTypes(DispatcherType first, DispatcherType... rest) { """ Convenience method to {@link #setDispatcherTypes(EnumSet) set dispatcher types} using the specified elements. @param first the first dispatcher type @param rest additional dispatcher types """ this.dispatcherTypes = EnumSet.of(first, rest); }
java
public void setDispatcherTypes(DispatcherType first, DispatcherType... rest) { this.dispatcherTypes = EnumSet.of(first, rest); }
[ "public", "void", "setDispatcherTypes", "(", "DispatcherType", "first", ",", "DispatcherType", "...", "rest", ")", "{", "this", ".", "dispatcherTypes", "=", "EnumSet", ".", "of", "(", "first", ",", "rest", ")", ";", "}" ]
Convenience method to {@link #setDispatcherTypes(EnumSet) set dispatcher types} using the specified elements. @param first the first dispatcher type @param rest additional dispatcher types
[ "Convenience", "method", "to", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java#L172-L174
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/abbvGapsHmm/AbbvGapsHMM.java
AbbvGapsHMM.smoothCounter
protected double smoothCounter(int i, List<Double> counters, List<Double> params) { """ Dirichlet smoothing ------------------- Without a prior: P(data | theta) = theta(i)^beta(i) = counters(i) With a dirichlet prior: P(data | theta)*p(theta) = theta(i)^(beta(i) + alpha(i)) = theta(i)^beta(i) + theta(i)^alpha(i) counters(i) + params(i)^alpha(i) """ double alpha = 1; return counters.get(i) + Math.pow(params.get(i), alpha); }
java
protected double smoothCounter(int i, List<Double> counters, List<Double> params){ double alpha = 1; return counters.get(i) + Math.pow(params.get(i), alpha); }
[ "protected", "double", "smoothCounter", "(", "int", "i", ",", "List", "<", "Double", ">", "counters", ",", "List", "<", "Double", ">", "params", ")", "{", "double", "alpha", "=", "1", ";", "return", "counters", ".", "get", "(", "i", ")", "+", "Math", ".", "pow", "(", "params", ".", "get", "(", "i", ")", ",", "alpha", ")", ";", "}" ]
Dirichlet smoothing ------------------- Without a prior: P(data | theta) = theta(i)^beta(i) = counters(i) With a dirichlet prior: P(data | theta)*p(theta) = theta(i)^(beta(i) + alpha(i)) = theta(i)^beta(i) + theta(i)^alpha(i) counters(i) + params(i)^alpha(i)
[ "Dirichlet", "smoothing", "-------------------" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/abbvGapsHmm/AbbvGapsHMM.java#L477-L480
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/BackupLongTermRetentionPoliciesInner.java
BackupLongTermRetentionPoliciesInner.beginCreateOrUpdateAsync
public Observable<BackupLongTermRetentionPolicyInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String databaseName, BackupLongTermRetentionPolicyInner parameters) { """ Creates or updates a database backup long term retention policy. @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 serverName The name of the server. @param databaseName The name of the database @param parameters The required parameters to update a backup long term retention policy @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BackupLongTermRetentionPolicyInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<BackupLongTermRetentionPolicyInner>, BackupLongTermRetentionPolicyInner>() { @Override public BackupLongTermRetentionPolicyInner call(ServiceResponse<BackupLongTermRetentionPolicyInner> response) { return response.body(); } }); }
java
public Observable<BackupLongTermRetentionPolicyInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String databaseName, BackupLongTermRetentionPolicyInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<BackupLongTermRetentionPolicyInner>, BackupLongTermRetentionPolicyInner>() { @Override public BackupLongTermRetentionPolicyInner call(ServiceResponse<BackupLongTermRetentionPolicyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BackupLongTermRetentionPolicyInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "BackupLongTermRetentionPolicyInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "BackupLongTermRetentionPolicyInner", ">", ",", "BackupLongTermRetentionPolicyInner", ">", "(", ")", "{", "@", "Override", "public", "BackupLongTermRetentionPolicyInner", "call", "(", "ServiceResponse", "<", "BackupLongTermRetentionPolicyInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a database backup long term retention policy. @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 serverName The name of the server. @param databaseName The name of the database @param parameters The required parameters to update a backup long term retention policy @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BackupLongTermRetentionPolicyInner object
[ "Creates", "or", "updates", "a", "database", "backup", "long", "term", "retention", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/BackupLongTermRetentionPoliciesInner.java#L296-L303
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Preconditions.checkArgument
public static void checkArgument(boolean condition, @Nullable Object errorMessage) { """ Checks the given boolean condition, and throws an {@code IllegalArgumentException} if the condition is not met (evaluates to {@code false}). The exception will have the given error message. @param condition The condition to check @param errorMessage The message for the {@code IllegalArgumentException} that is thrown if the check fails. @throws IllegalArgumentException Thrown, if the condition is violated. """ if (!condition) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } }
java
public static void checkArgument(boolean condition, @Nullable Object errorMessage) { if (!condition) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } }
[ "public", "static", "void", "checkArgument", "(", "boolean", "condition", ",", "@", "Nullable", "Object", "errorMessage", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "valueOf", "(", "errorMessage", ")", ")", ";", "}", "}" ]
Checks the given boolean condition, and throws an {@code IllegalArgumentException} if the condition is not met (evaluates to {@code false}). The exception will have the given error message. @param condition The condition to check @param errorMessage The message for the {@code IllegalArgumentException} that is thrown if the check fails. @throws IllegalArgumentException Thrown, if the condition is violated.
[ "Checks", "the", "given", "boolean", "condition", "and", "throws", "an", "{", "@code", "IllegalArgumentException", "}", "if", "the", "condition", "is", "not", "met", "(", "evaluates", "to", "{", "@code", "false", "}", ")", ".", "The", "exception", "will", "have", "the", "given", "error", "message", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/Preconditions.java#L137-L141
apereo/cas
core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java
AbstractCasWebflowConfigurer.createStateDefaultTransition
public void createStateDefaultTransition(final TransitionableState state, final String targetState) { """ Add a default transition to a given state. @param state the state to include the default transition @param targetState the id of the destination state to which the flow should transfer """ if (state == null) { LOGGER.trace("Cannot add default transition of [{}] to the given state is null and cannot be found in the flow.", targetState); return; } val transition = createTransition(targetState); state.getTransitionSet().add(transition); }
java
public void createStateDefaultTransition(final TransitionableState state, final String targetState) { if (state == null) { LOGGER.trace("Cannot add default transition of [{}] to the given state is null and cannot be found in the flow.", targetState); return; } val transition = createTransition(targetState); state.getTransitionSet().add(transition); }
[ "public", "void", "createStateDefaultTransition", "(", "final", "TransitionableState", "state", ",", "final", "String", "targetState", ")", "{", "if", "(", "state", "==", "null", ")", "{", "LOGGER", ".", "trace", "(", "\"Cannot add default transition of [{}] to the given state is null and cannot be found in the flow.\"", ",", "targetState", ")", ";", "return", ";", "}", "val", "transition", "=", "createTransition", "(", "targetState", ")", ";", "state", ".", "getTransitionSet", "(", ")", ".", "add", "(", "transition", ")", ";", "}" ]
Add a default transition to a given state. @param state the state to include the default transition @param targetState the id of the destination state to which the flow should transfer
[ "Add", "a", "default", "transition", "to", "a", "given", "state", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java#L268-L275
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/utils/ShellUtils.java
ShellUtils.execCommand
public static String execCommand(Map<String,String> env, String ... cmd) throws IOException { """ Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface. @param env the map of environment key=value @param cmd shell command to execute. @return the output of the executed command. """ return execCommand(env, cmd, 0L); }
java
public static String execCommand(Map<String,String> env, String ... cmd) throws IOException { return execCommand(env, cmd, 0L); }
[ "public", "static", "String", "execCommand", "(", "Map", "<", "String", ",", "String", ">", "env", ",", "String", "...", "cmd", ")", "throws", "IOException", "{", "return", "execCommand", "(", "env", ",", "cmd", ",", "0L", ")", ";", "}" ]
Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface. @param env the map of environment key=value @param cmd shell command to execute. @return the output of the executed command.
[ "Static", "method", "to", "execute", "a", "shell", "command", ".", "Covers", "most", "of", "the", "simple", "cases", "without", "requiring", "the", "user", "to", "implement", "the", "<code", ">", "Shell<", "/", "code", ">", "interface", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/ShellUtils.java#L454-L457
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java
LevelRipConverter.start
public static int start(Media levelrip, MapTile map, ProgressListener listener) { """ Run the converter. @param levelrip The file containing the levelrip as an image. @param map The destination map reference. @param listener The progress listener. @return The total number of not found tiles. @throws LionEngineException If media is <code>null</code> or image cannot be read. """ return start(levelrip, map, listener, null); }
java
public static int start(Media levelrip, MapTile map, ProgressListener listener) { return start(levelrip, map, listener, null); }
[ "public", "static", "int", "start", "(", "Media", "levelrip", ",", "MapTile", "map", ",", "ProgressListener", "listener", ")", "{", "return", "start", "(", "levelrip", ",", "map", ",", "listener", ",", "null", ")", ";", "}" ]
Run the converter. @param levelrip The file containing the levelrip as an image. @param map The destination map reference. @param listener The progress listener. @return The total number of not found tiles. @throws LionEngineException If media is <code>null</code> or image cannot be read.
[ "Run", "the", "converter", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java#L58-L61
Alluxio/alluxio
core/server/common/src/main/java/alluxio/StorageTierAssoc.java
StorageTierAssoc.interpretOrdinal
static int interpretOrdinal(int ordinal, int numTiers) { """ Interprets a tier ordinal given the number of tiers. Non-negative values identify tiers starting from top going down (0 identifies the first tier, 1 identifies the second tier, and so on). If the provided value is greater than the number of tiers, it identifies the last tier. Negative values identify tiers starting from the bottom going up (-1 identifies the last tier, -2 identifies the second to last tier, and so on). If the absolute value of the provided value is greater than the number of tiers, it identifies the first tier. @param ordinal the storage tier ordinal to interpret @param numTiers the number of storage tiers @return a valid tier ordinal """ if (ordinal >= 0) { return Math.min(ordinal, numTiers - 1); } return Math.max(numTiers + ordinal, 0); }
java
static int interpretOrdinal(int ordinal, int numTiers) { if (ordinal >= 0) { return Math.min(ordinal, numTiers - 1); } return Math.max(numTiers + ordinal, 0); }
[ "static", "int", "interpretOrdinal", "(", "int", "ordinal", ",", "int", "numTiers", ")", "{", "if", "(", "ordinal", ">=", "0", ")", "{", "return", "Math", ".", "min", "(", "ordinal", ",", "numTiers", "-", "1", ")", ";", "}", "return", "Math", ".", "max", "(", "numTiers", "+", "ordinal", ",", "0", ")", ";", "}" ]
Interprets a tier ordinal given the number of tiers. Non-negative values identify tiers starting from top going down (0 identifies the first tier, 1 identifies the second tier, and so on). If the provided value is greater than the number of tiers, it identifies the last tier. Negative values identify tiers starting from the bottom going up (-1 identifies the last tier, -2 identifies the second to last tier, and so on). If the absolute value of the provided value is greater than the number of tiers, it identifies the first tier. @param ordinal the storage tier ordinal to interpret @param numTiers the number of storage tiers @return a valid tier ordinal
[ "Interprets", "a", "tier", "ordinal", "given", "the", "number", "of", "tiers", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/StorageTierAssoc.java#L50-L55
google/closure-compiler
src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java
JsDocInfoParser.parseParamTypeExpression
private Node parseParamTypeExpression(JsDocToken token) { """ Parse a ParamTypeExpression: <pre> ParamTypeExpression := OptionalParameterType | TopLevelTypeExpression | '...' TopLevelTypeExpression OptionalParameterType := TopLevelTypeExpression '=' </pre> """ boolean restArg = false; if (token == JsDocToken.ELLIPSIS) { token = next(); if (token == JsDocToken.RIGHT_CURLY) { restoreLookAhead(token); // EMPTY represents the UNKNOWN type in the Type AST. return wrapNode(Token.ELLIPSIS, IR.empty()); } restArg = true; } Node typeNode = parseTopLevelTypeExpression(token); if (typeNode != null) { skipEOLs(); if (restArg) { typeNode = wrapNode(Token.ELLIPSIS, typeNode); } else if (match(JsDocToken.EQUALS)) { next(); skipEOLs(); typeNode = wrapNode(Token.EQUALS, typeNode); } } return typeNode; }
java
private Node parseParamTypeExpression(JsDocToken token) { boolean restArg = false; if (token == JsDocToken.ELLIPSIS) { token = next(); if (token == JsDocToken.RIGHT_CURLY) { restoreLookAhead(token); // EMPTY represents the UNKNOWN type in the Type AST. return wrapNode(Token.ELLIPSIS, IR.empty()); } restArg = true; } Node typeNode = parseTopLevelTypeExpression(token); if (typeNode != null) { skipEOLs(); if (restArg) { typeNode = wrapNode(Token.ELLIPSIS, typeNode); } else if (match(JsDocToken.EQUALS)) { next(); skipEOLs(); typeNode = wrapNode(Token.EQUALS, typeNode); } } return typeNode; }
[ "private", "Node", "parseParamTypeExpression", "(", "JsDocToken", "token", ")", "{", "boolean", "restArg", "=", "false", ";", "if", "(", "token", "==", "JsDocToken", ".", "ELLIPSIS", ")", "{", "token", "=", "next", "(", ")", ";", "if", "(", "token", "==", "JsDocToken", ".", "RIGHT_CURLY", ")", "{", "restoreLookAhead", "(", "token", ")", ";", "// EMPTY represents the UNKNOWN type in the Type AST.", "return", "wrapNode", "(", "Token", ".", "ELLIPSIS", ",", "IR", ".", "empty", "(", ")", ")", ";", "}", "restArg", "=", "true", ";", "}", "Node", "typeNode", "=", "parseTopLevelTypeExpression", "(", "token", ")", ";", "if", "(", "typeNode", "!=", "null", ")", "{", "skipEOLs", "(", ")", ";", "if", "(", "restArg", ")", "{", "typeNode", "=", "wrapNode", "(", "Token", ".", "ELLIPSIS", ",", "typeNode", ")", ";", "}", "else", "if", "(", "match", "(", "JsDocToken", ".", "EQUALS", ")", ")", "{", "next", "(", ")", ";", "skipEOLs", "(", ")", ";", "typeNode", "=", "wrapNode", "(", "Token", ".", "EQUALS", ",", "typeNode", ")", ";", "}", "}", "return", "typeNode", ";", "}" ]
Parse a ParamTypeExpression: <pre> ParamTypeExpression := OptionalParameterType | TopLevelTypeExpression | '...' TopLevelTypeExpression OptionalParameterType := TopLevelTypeExpression '=' </pre>
[ "Parse", "a", "ParamTypeExpression", ":" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L1973-L1998
zaproxy/zaproxy
src/org/zaproxy/zap/view/TabbedPanel2.java
TabbedPanel2.setTabLocked
public void setTabLocked(AbstractPanel panel, boolean lock) { """ Temporarily locks/unlocks the specified tab, eg if its active and mustn't be closed. <p> Locked (AbstractPanel) tabs will not have the pin/close tab buttons displayed. @param panel the panel being changed @param lock {@code true} if the panel should be locked, {@code false} otherwise. """ for (int i = 0; i < this.getTabCount(); i++) { Component tabCom = this.getTabComponentAt(i); if (tabCom != null && tabCom instanceof TabbedPanelTab && tabCom.isVisible()) { TabbedPanelTab jp = (TabbedPanelTab) tabCom; if (panel.equals(jp.getAbstractPanel())) { jp.setLocked(!lock); } } } }
java
public void setTabLocked(AbstractPanel panel, boolean lock) { for (int i = 0; i < this.getTabCount(); i++) { Component tabCom = this.getTabComponentAt(i); if (tabCom != null && tabCom instanceof TabbedPanelTab && tabCom.isVisible()) { TabbedPanelTab jp = (TabbedPanelTab) tabCom; if (panel.equals(jp.getAbstractPanel())) { jp.setLocked(!lock); } } } }
[ "public", "void", "setTabLocked", "(", "AbstractPanel", "panel", ",", "boolean", "lock", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "getTabCount", "(", ")", ";", "i", "++", ")", "{", "Component", "tabCom", "=", "this", ".", "getTabComponentAt", "(", "i", ")", ";", "if", "(", "tabCom", "!=", "null", "&&", "tabCom", "instanceof", "TabbedPanelTab", "&&", "tabCom", ".", "isVisible", "(", ")", ")", "{", "TabbedPanelTab", "jp", "=", "(", "TabbedPanelTab", ")", "tabCom", ";", "if", "(", "panel", ".", "equals", "(", "jp", ".", "getAbstractPanel", "(", ")", ")", ")", "{", "jp", ".", "setLocked", "(", "!", "lock", ")", ";", "}", "}", "}", "}" ]
Temporarily locks/unlocks the specified tab, eg if its active and mustn't be closed. <p> Locked (AbstractPanel) tabs will not have the pin/close tab buttons displayed. @param panel the panel being changed @param lock {@code true} if the panel should be locked, {@code false} otherwise.
[ "Temporarily", "locks", "/", "unlocks", "the", "specified", "tab", "eg", "if", "its", "active", "and", "mustn", "t", "be", "closed", ".", "<p", ">", "Locked", "(", "AbstractPanel", ")", "tabs", "will", "not", "have", "the", "pin", "/", "close", "tab", "buttons", "displayed", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/TabbedPanel2.java#L418-L428
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java
FacesImpl.findSimilarAsync
public Observable<List<SimilarFace>> findSimilarAsync(UUID faceId, FindSimilarOptionalParameter findSimilarOptionalParameter) { """ Given query face's faceId, find the similar-looking faces from a faceId array or a faceListId. @param faceId FaceId of the query face. User needs to call Face - Detect first to get a valid faceId. Note that this faceId is not persisted and will expire 24 hours after the detection call @param findSimilarOptionalParameter 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;SimilarFace&gt; object """ return findSimilarWithServiceResponseAsync(faceId, findSimilarOptionalParameter).map(new Func1<ServiceResponse<List<SimilarFace>>, List<SimilarFace>>() { @Override public List<SimilarFace> call(ServiceResponse<List<SimilarFace>> response) { return response.body(); } }); }
java
public Observable<List<SimilarFace>> findSimilarAsync(UUID faceId, FindSimilarOptionalParameter findSimilarOptionalParameter) { return findSimilarWithServiceResponseAsync(faceId, findSimilarOptionalParameter).map(new Func1<ServiceResponse<List<SimilarFace>>, List<SimilarFace>>() { @Override public List<SimilarFace> call(ServiceResponse<List<SimilarFace>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "SimilarFace", ">", ">", "findSimilarAsync", "(", "UUID", "faceId", ",", "FindSimilarOptionalParameter", "findSimilarOptionalParameter", ")", "{", "return", "findSimilarWithServiceResponseAsync", "(", "faceId", ",", "findSimilarOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "SimilarFace", ">", ">", ",", "List", "<", "SimilarFace", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "SimilarFace", ">", "call", "(", "ServiceResponse", "<", "List", "<", "SimilarFace", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Given query face's faceId, find the similar-looking faces from a faceId array or a faceListId. @param faceId FaceId of the query face. User needs to call Face - Detect first to get a valid faceId. Note that this faceId is not persisted and will expire 24 hours after the detection call @param findSimilarOptionalParameter 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;SimilarFace&gt; object
[ "Given", "query", "face", "s", "faceId", "find", "the", "similar", "-", "looking", "faces", "from", "a", "faceId", "array", "or", "a", "faceListId", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java#L145-L152
andkulikov/Transitions-Everywhere
library(1.x)/src/main/java/com/transitionseverywhere/TransitionManager.java
TransitionManager.setTransition
public void setTransition(@NonNull Scene fromScene, @NonNull Scene toScene, @Nullable Transition transition) { """ Sets a specific transition to occur when the given pair of scenes is exited/entered. @param fromScene The scene being exited when the given transition will be run @param toScene The scene being entered when the given transition will be run @param transition The transition that will play when the given scene is entered. A value of null will result in the default behavior of using the default transition instead. """ ArrayMap<Scene, Transition> sceneTransitionMap = mScenePairTransitions.get(toScene); if (sceneTransitionMap == null) { sceneTransitionMap = new ArrayMap<Scene, Transition>(); mScenePairTransitions.put(toScene, sceneTransitionMap); } sceneTransitionMap.put(fromScene, transition); }
java
public void setTransition(@NonNull Scene fromScene, @NonNull Scene toScene, @Nullable Transition transition) { ArrayMap<Scene, Transition> sceneTransitionMap = mScenePairTransitions.get(toScene); if (sceneTransitionMap == null) { sceneTransitionMap = new ArrayMap<Scene, Transition>(); mScenePairTransitions.put(toScene, sceneTransitionMap); } sceneTransitionMap.put(fromScene, transition); }
[ "public", "void", "setTransition", "(", "@", "NonNull", "Scene", "fromScene", ",", "@", "NonNull", "Scene", "toScene", ",", "@", "Nullable", "Transition", "transition", ")", "{", "ArrayMap", "<", "Scene", ",", "Transition", ">", "sceneTransitionMap", "=", "mScenePairTransitions", ".", "get", "(", "toScene", ")", ";", "if", "(", "sceneTransitionMap", "==", "null", ")", "{", "sceneTransitionMap", "=", "new", "ArrayMap", "<", "Scene", ",", "Transition", ">", "(", ")", ";", "mScenePairTransitions", ".", "put", "(", "toScene", ",", "sceneTransitionMap", ")", ";", "}", "sceneTransitionMap", ".", "put", "(", "fromScene", ",", "transition", ")", ";", "}" ]
Sets a specific transition to occur when the given pair of scenes is exited/entered. @param fromScene The scene being exited when the given transition will be run @param toScene The scene being entered when the given transition will be run @param transition The transition that will play when the given scene is entered. A value of null will result in the default behavior of using the default transition instead.
[ "Sets", "a", "specific", "transition", "to", "occur", "when", "the", "given", "pair", "of", "scenes", "is", "exited", "/", "entered", "." ]
train
https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/TransitionManager.java#L137-L144
jnr/jnr-x86asm
src/main/java/jnr/x86asm/SerializerIntrinsics.java
SerializerIntrinsics.mpsadbw
public final void mpsadbw(XMMRegister dst, XMMRegister src, Immediate imm8) { """ Compute Multiple Packed Sums of Absolute Difference (SSE4.1). """ emitX86(INST_MPSADBW, dst, src, imm8); }
java
public final void mpsadbw(XMMRegister dst, XMMRegister src, Immediate imm8) { emitX86(INST_MPSADBW, dst, src, imm8); }
[ "public", "final", "void", "mpsadbw", "(", "XMMRegister", "dst", ",", "XMMRegister", "src", ",", "Immediate", "imm8", ")", "{", "emitX86", "(", "INST_MPSADBW", ",", "dst", ",", "src", ",", "imm8", ")", ";", "}" ]
Compute Multiple Packed Sums of Absolute Difference (SSE4.1).
[ "Compute", "Multiple", "Packed", "Sums", "of", "Absolute", "Difference", "(", "SSE4", ".", "1", ")", "." ]
train
https://github.com/jnr/jnr-x86asm/blob/fdcf68fb3dae49e607a49e33399e3dad1ada5536/src/main/java/jnr/x86asm/SerializerIntrinsics.java#L6061-L6064
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsTabbedPanel.java
CmsTabbedPanel.disableTab
public void disableTab(E tabContent, String reason) { """ Disables the tab with the given index.<p> @param tabContent the content of the tab that should be disabled @param reason the reason why the tab is disabled """ Integer index = new Integer(m_tabPanel.getWidgetIndex(tabContent)); Element tab = getTabElement(index.intValue()); if ((tab != null) && !m_disabledTabIndexes.containsKey(index)) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(tab.getTitle())) { m_disabledTabIndexes.put(index, tab.getTitle()); } else { m_disabledTabIndexes.put(index, ""); } tab.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().tabDisabled()); tab.setTitle(reason); } }
java
public void disableTab(E tabContent, String reason) { Integer index = new Integer(m_tabPanel.getWidgetIndex(tabContent)); Element tab = getTabElement(index.intValue()); if ((tab != null) && !m_disabledTabIndexes.containsKey(index)) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(tab.getTitle())) { m_disabledTabIndexes.put(index, tab.getTitle()); } else { m_disabledTabIndexes.put(index, ""); } tab.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().tabDisabled()); tab.setTitle(reason); } }
[ "public", "void", "disableTab", "(", "E", "tabContent", ",", "String", "reason", ")", "{", "Integer", "index", "=", "new", "Integer", "(", "m_tabPanel", ".", "getWidgetIndex", "(", "tabContent", ")", ")", ";", "Element", "tab", "=", "getTabElement", "(", "index", ".", "intValue", "(", ")", ")", ";", "if", "(", "(", "tab", "!=", "null", ")", "&&", "!", "m_disabledTabIndexes", ".", "containsKey", "(", "index", ")", ")", "{", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "tab", ".", "getTitle", "(", ")", ")", ")", "{", "m_disabledTabIndexes", ".", "put", "(", "index", ",", "tab", ".", "getTitle", "(", ")", ")", ";", "}", "else", "{", "m_disabledTabIndexes", ".", "put", "(", "index", ",", "\"\"", ")", ";", "}", "tab", ".", "addClassName", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "tabbedPanelCss", "(", ")", ".", "tabDisabled", "(", ")", ")", ";", "tab", ".", "setTitle", "(", "reason", ")", ";", "}", "}" ]
Disables the tab with the given index.<p> @param tabContent the content of the tab that should be disabled @param reason the reason why the tab is disabled
[ "Disables", "the", "tab", "with", "the", "given", "index", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsTabbedPanel.java#L375-L388
jglobus/JGlobus
axis/src/main/java/org/globus/axis/transport/HTTPUtils.java
HTTPUtils.setTimeout
public static void setTimeout(Stub stub, int timeout) { """ Sets connection timeout. @param stub The stub to set the property on @param timeout the new timeout value in milliseconds """ if (stub instanceof org.apache.axis.client.Stub) { ((org.apache.axis.client.Stub)stub).setTimeout(timeout); } }
java
public static void setTimeout(Stub stub, int timeout) { if (stub instanceof org.apache.axis.client.Stub) { ((org.apache.axis.client.Stub)stub).setTimeout(timeout); } }
[ "public", "static", "void", "setTimeout", "(", "Stub", "stub", ",", "int", "timeout", ")", "{", "if", "(", "stub", "instanceof", "org", ".", "apache", ".", "axis", ".", "client", ".", "Stub", ")", "{", "(", "(", "org", ".", "apache", ".", "axis", ".", "client", ".", "Stub", ")", "stub", ")", ".", "setTimeout", "(", "timeout", ")", ";", "}", "}" ]
Sets connection timeout. @param stub The stub to set the property on @param timeout the new timeout value in milliseconds
[ "Sets", "connection", "timeout", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/axis/src/main/java/org/globus/axis/transport/HTTPUtils.java#L36-L40
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java
SDNN.layerNorm
public SDVariable layerNorm(SDVariable input, SDVariable gain, SDVariable bias, int... dimensions) { """ Apply Layer Normalization y = gain * standardize(x) + bias @return Output variable """ return layerNorm(null, input, gain, bias, dimensions); }
java
public SDVariable layerNorm(SDVariable input, SDVariable gain, SDVariable bias, int... dimensions) { return layerNorm(null, input, gain, bias, dimensions); }
[ "public", "SDVariable", "layerNorm", "(", "SDVariable", "input", ",", "SDVariable", "gain", ",", "SDVariable", "bias", ",", "int", "...", "dimensions", ")", "{", "return", "layerNorm", "(", "null", ",", "input", ",", "gain", ",", "bias", ",", "dimensions", ")", ";", "}" ]
Apply Layer Normalization y = gain * standardize(x) + bias @return Output variable
[ "Apply", "Layer", "Normalization" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java#L701-L703
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java
EventSerializer.isEvent
private static boolean isEvent(ByteBuffer buffer, Class<?> eventClass) throws IOException { """ Identifies whether the given buffer encodes the given event. Custom events are not supported. <p><strong>Pre-condition</strong>: This buffer must encode some event!</p> @param buffer the buffer to peak into @param eventClass the expected class of the event type @return whether the event class of the <tt>buffer</tt> matches the given <tt>eventClass</tt> """ if (buffer.remaining() < 4) { throw new IOException("Incomplete event"); } final int bufferPos = buffer.position(); final ByteOrder bufferOrder = buffer.order(); buffer.order(ByteOrder.BIG_ENDIAN); try { int type = buffer.getInt(); if (eventClass.equals(EndOfPartitionEvent.class)) { return type == END_OF_PARTITION_EVENT; } else if (eventClass.equals(CheckpointBarrier.class)) { return type == CHECKPOINT_BARRIER_EVENT; } else if (eventClass.equals(EndOfSuperstepEvent.class)) { return type == END_OF_SUPERSTEP_EVENT; } else if (eventClass.equals(CancelCheckpointMarker.class)) { return type == CANCEL_CHECKPOINT_MARKER_EVENT; } else { throw new UnsupportedOperationException("Unsupported eventClass = " + eventClass); } } finally { buffer.order(bufferOrder); // restore the original position in the buffer (recall: we only peak into it!) buffer.position(bufferPos); } }
java
private static boolean isEvent(ByteBuffer buffer, Class<?> eventClass) throws IOException { if (buffer.remaining() < 4) { throw new IOException("Incomplete event"); } final int bufferPos = buffer.position(); final ByteOrder bufferOrder = buffer.order(); buffer.order(ByteOrder.BIG_ENDIAN); try { int type = buffer.getInt(); if (eventClass.equals(EndOfPartitionEvent.class)) { return type == END_OF_PARTITION_EVENT; } else if (eventClass.equals(CheckpointBarrier.class)) { return type == CHECKPOINT_BARRIER_EVENT; } else if (eventClass.equals(EndOfSuperstepEvent.class)) { return type == END_OF_SUPERSTEP_EVENT; } else if (eventClass.equals(CancelCheckpointMarker.class)) { return type == CANCEL_CHECKPOINT_MARKER_EVENT; } else { throw new UnsupportedOperationException("Unsupported eventClass = " + eventClass); } } finally { buffer.order(bufferOrder); // restore the original position in the buffer (recall: we only peak into it!) buffer.position(bufferPos); } }
[ "private", "static", "boolean", "isEvent", "(", "ByteBuffer", "buffer", ",", "Class", "<", "?", ">", "eventClass", ")", "throws", "IOException", "{", "if", "(", "buffer", ".", "remaining", "(", ")", "<", "4", ")", "{", "throw", "new", "IOException", "(", "\"Incomplete event\"", ")", ";", "}", "final", "int", "bufferPos", "=", "buffer", ".", "position", "(", ")", ";", "final", "ByteOrder", "bufferOrder", "=", "buffer", ".", "order", "(", ")", ";", "buffer", ".", "order", "(", "ByteOrder", ".", "BIG_ENDIAN", ")", ";", "try", "{", "int", "type", "=", "buffer", ".", "getInt", "(", ")", ";", "if", "(", "eventClass", ".", "equals", "(", "EndOfPartitionEvent", ".", "class", ")", ")", "{", "return", "type", "==", "END_OF_PARTITION_EVENT", ";", "}", "else", "if", "(", "eventClass", ".", "equals", "(", "CheckpointBarrier", ".", "class", ")", ")", "{", "return", "type", "==", "CHECKPOINT_BARRIER_EVENT", ";", "}", "else", "if", "(", "eventClass", ".", "equals", "(", "EndOfSuperstepEvent", ".", "class", ")", ")", "{", "return", "type", "==", "END_OF_SUPERSTEP_EVENT", ";", "}", "else", "if", "(", "eventClass", ".", "equals", "(", "CancelCheckpointMarker", ".", "class", ")", ")", "{", "return", "type", "==", "CANCEL_CHECKPOINT_MARKER_EVENT", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Unsupported eventClass = \"", "+", "eventClass", ")", ";", "}", "}", "finally", "{", "buffer", ".", "order", "(", "bufferOrder", ")", ";", "// restore the original position in the buffer (recall: we only peak into it!)", "buffer", ".", "position", "(", "bufferPos", ")", ";", "}", "}" ]
Identifies whether the given buffer encodes the given event. Custom events are not supported. <p><strong>Pre-condition</strong>: This buffer must encode some event!</p> @param buffer the buffer to peak into @param eventClass the expected class of the event type @return whether the event class of the <tt>buffer</tt> matches the given <tt>eventClass</tt>
[ "Identifies", "whether", "the", "given", "buffer", "encodes", "the", "given", "event", ".", "Custom", "events", "are", "not", "supported", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java#L114-L143
jhy/jsoup
src/main/java/org/jsoup/safety/Whitelist.java
Whitelist.addProtocols
public Whitelist addProtocols(String tag, String attribute, String... protocols) { """ Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to URLs with the defined protocol. <p> E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code> </p> <p> To allow a link to an in-page URL anchor (i.e. <code>&lt;a href="#anchor"&gt;</code>, add a <code>#</code>:<br> E.g.: <code>addProtocols("a", "href", "#")</code> </p> @param tag Tag the URL protocol is for @param attribute Attribute name @param protocols List of valid protocols @return this, for chaining """ Validate.notEmpty(tag); Validate.notEmpty(attribute); Validate.notNull(protocols); TagName tagName = TagName.valueOf(tag); AttributeKey attrKey = AttributeKey.valueOf(attribute); Map<AttributeKey, Set<Protocol>> attrMap; Set<Protocol> protSet; if (this.protocols.containsKey(tagName)) { attrMap = this.protocols.get(tagName); } else { attrMap = new HashMap<>(); this.protocols.put(tagName, attrMap); } if (attrMap.containsKey(attrKey)) { protSet = attrMap.get(attrKey); } else { protSet = new HashSet<>(); attrMap.put(attrKey, protSet); } for (String protocol : protocols) { Validate.notEmpty(protocol); Protocol prot = Protocol.valueOf(protocol); protSet.add(prot); } return this; }
java
public Whitelist addProtocols(String tag, String attribute, String... protocols) { Validate.notEmpty(tag); Validate.notEmpty(attribute); Validate.notNull(protocols); TagName tagName = TagName.valueOf(tag); AttributeKey attrKey = AttributeKey.valueOf(attribute); Map<AttributeKey, Set<Protocol>> attrMap; Set<Protocol> protSet; if (this.protocols.containsKey(tagName)) { attrMap = this.protocols.get(tagName); } else { attrMap = new HashMap<>(); this.protocols.put(tagName, attrMap); } if (attrMap.containsKey(attrKey)) { protSet = attrMap.get(attrKey); } else { protSet = new HashSet<>(); attrMap.put(attrKey, protSet); } for (String protocol : protocols) { Validate.notEmpty(protocol); Protocol prot = Protocol.valueOf(protocol); protSet.add(prot); } return this; }
[ "public", "Whitelist", "addProtocols", "(", "String", "tag", ",", "String", "attribute", ",", "String", "...", "protocols", ")", "{", "Validate", ".", "notEmpty", "(", "tag", ")", ";", "Validate", ".", "notEmpty", "(", "attribute", ")", ";", "Validate", ".", "notNull", "(", "protocols", ")", ";", "TagName", "tagName", "=", "TagName", ".", "valueOf", "(", "tag", ")", ";", "AttributeKey", "attrKey", "=", "AttributeKey", ".", "valueOf", "(", "attribute", ")", ";", "Map", "<", "AttributeKey", ",", "Set", "<", "Protocol", ">", ">", "attrMap", ";", "Set", "<", "Protocol", ">", "protSet", ";", "if", "(", "this", ".", "protocols", ".", "containsKey", "(", "tagName", ")", ")", "{", "attrMap", "=", "this", ".", "protocols", ".", "get", "(", "tagName", ")", ";", "}", "else", "{", "attrMap", "=", "new", "HashMap", "<>", "(", ")", ";", "this", ".", "protocols", ".", "put", "(", "tagName", ",", "attrMap", ")", ";", "}", "if", "(", "attrMap", ".", "containsKey", "(", "attrKey", ")", ")", "{", "protSet", "=", "attrMap", ".", "get", "(", "attrKey", ")", ";", "}", "else", "{", "protSet", "=", "new", "HashSet", "<>", "(", ")", ";", "attrMap", ".", "put", "(", "attrKey", ",", "protSet", ")", ";", "}", "for", "(", "String", "protocol", ":", "protocols", ")", "{", "Validate", ".", "notEmpty", "(", "protocol", ")", ";", "Protocol", "prot", "=", "Protocol", ".", "valueOf", "(", "protocol", ")", ";", "protSet", ".", "add", "(", "prot", ")", ";", "}", "return", "this", ";", "}" ]
Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to URLs with the defined protocol. <p> E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code> </p> <p> To allow a link to an in-page URL anchor (i.e. <code>&lt;a href="#anchor"&gt;</code>, add a <code>#</code>:<br> E.g.: <code>addProtocols("a", "href", "#")</code> </p> @param tag Tag the URL protocol is for @param attribute Attribute name @param protocols List of valid protocols @return this, for chaining
[ "Add", "allowed", "URL", "protocols", "for", "an", "element", "s", "URL", "attribute", ".", "This", "restricts", "the", "possible", "values", "of", "the", "attribute", "to", "URLs", "with", "the", "defined", "protocol", ".", "<p", ">", "E", ".", "g", ".", ":", "<code", ">", "addProtocols", "(", "a", "href", "ftp", "http", "https", ")", "<", "/", "code", ">", "<", "/", "p", ">", "<p", ">", "To", "allow", "a", "link", "to", "an", "in", "-", "page", "URL", "anchor", "(", "i", ".", "e", ".", "<code", ">", "&lt", ";", "a", "href", "=", "#anchor", "&gt", ";", "<", "/", "code", ">", "add", "a", "<code", ">", "#<", "/", "code", ">", ":", "<br", ">", "E", ".", "g", ".", ":", "<code", ">", "addProtocols", "(", "a", "href", "#", ")", "<", "/", "code", ">", "<", "/", "p", ">" ]
train
https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/safety/Whitelist.java#L410-L438
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/memento/MethodCallSavePointPlayer.java
MethodCallSavePointPlayer.playMethodCalls
public synchronized void playMethodCalls(Memento memento, String [] savePoints) { """ Redo the method calls of a target object @param memento the memento to restore MethodCallFact @param savePoints the list of the MethodCallFact save points @throws SummaryException """ String savePoint = null; MethodCallFact methodCallFact = null; SummaryException exceptions = new SummaryException(); //loop thru savepoints for (int i = 0; i < savePoints.length; i++) { savePoint = savePoints[i]; if(savePoint == null || savePoint.length() == 0 || savePoint.trim().length() == 0) continue; Debugger.println(this,"processing savepoint="+savePoint); //get method call fact methodCallFact = (MethodCallFact)memento.restore(savePoint, MethodCallFact.class); try { ObjectProxy.executeMethod(prepareObject(methodCallFact,savePoint), methodCallFact); } catch(Exception e) { exceptions.addException(new SystemException("savePoint="+savePoint+" methodCallFact="+methodCallFact+" exception="+Debugger.stackTrace(e))); throw new SystemException(e); // TODO: } } if(!exceptions.isEmpty()) throw exceptions; }
java
public synchronized void playMethodCalls(Memento memento, String [] savePoints) { String savePoint = null; MethodCallFact methodCallFact = null; SummaryException exceptions = new SummaryException(); //loop thru savepoints for (int i = 0; i < savePoints.length; i++) { savePoint = savePoints[i]; if(savePoint == null || savePoint.length() == 0 || savePoint.trim().length() == 0) continue; Debugger.println(this,"processing savepoint="+savePoint); //get method call fact methodCallFact = (MethodCallFact)memento.restore(savePoint, MethodCallFact.class); try { ObjectProxy.executeMethod(prepareObject(methodCallFact,savePoint), methodCallFact); } catch(Exception e) { exceptions.addException(new SystemException("savePoint="+savePoint+" methodCallFact="+methodCallFact+" exception="+Debugger.stackTrace(e))); throw new SystemException(e); // TODO: } } if(!exceptions.isEmpty()) throw exceptions; }
[ "public", "synchronized", "void", "playMethodCalls", "(", "Memento", "memento", ",", "String", "[", "]", "savePoints", ")", "{", "String", "savePoint", "=", "null", ";", "MethodCallFact", "methodCallFact", "=", "null", ";", "SummaryException", "exceptions", "=", "new", "SummaryException", "(", ")", ";", "//loop thru savepoints\r", "for", "(", "int", "i", "=", "0", ";", "i", "<", "savePoints", ".", "length", ";", "i", "++", ")", "{", "savePoint", "=", "savePoints", "[", "i", "]", ";", "if", "(", "savePoint", "==", "null", "||", "savePoint", ".", "length", "(", ")", "==", "0", "||", "savePoint", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "continue", ";", "Debugger", ".", "println", "(", "this", ",", "\"processing savepoint=\"", "+", "savePoint", ")", ";", "//get method call fact\r", "methodCallFact", "=", "(", "MethodCallFact", ")", "memento", ".", "restore", "(", "savePoint", ",", "MethodCallFact", ".", "class", ")", ";", "try", "{", "ObjectProxy", ".", "executeMethod", "(", "prepareObject", "(", "methodCallFact", ",", "savePoint", ")", ",", "methodCallFact", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "exceptions", ".", "addException", "(", "new", "SystemException", "(", "\"savePoint=\"", "+", "savePoint", "+", "\" methodCallFact=\"", "+", "methodCallFact", "+", "\" exception=\"", "+", "Debugger", ".", "stackTrace", "(", "e", ")", ")", ")", ";", "throw", "new", "SystemException", "(", "e", ")", ";", "// TODO: \r", "}", "}", "if", "(", "!", "exceptions", ".", "isEmpty", "(", ")", ")", "throw", "exceptions", ";", "}" ]
Redo the method calls of a target object @param memento the memento to restore MethodCallFact @param savePoints the list of the MethodCallFact save points @throws SummaryException
[ "Redo", "the", "method", "calls", "of", "a", "target", "object" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/memento/MethodCallSavePointPlayer.java#L38-L70
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java
VirtualMachinesInner.generalizeAsync
public Observable<OperationStatusResponseInner> generalizeAsync(String resourceGroupName, String vmName) { """ Sets the state of the virtual machine to generalized. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatusResponseInner object """ return generalizeWithServiceResponseAsync(resourceGroupName, vmName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
java
public Observable<OperationStatusResponseInner> generalizeAsync(String resourceGroupName, String vmName) { return generalizeWithServiceResponseAsync(resourceGroupName, vmName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatusResponseInner", ">", "generalizeAsync", "(", "String", "resourceGroupName", ",", "String", "vmName", ")", "{", "return", "generalizeWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatusResponseInner", ">", ",", "OperationStatusResponseInner", ">", "(", ")", "{", "@", "Override", "public", "OperationStatusResponseInner", "call", "(", "ServiceResponse", "<", "OperationStatusResponseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Sets the state of the virtual machine to generalized. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatusResponseInner object
[ "Sets", "the", "state", "of", "the", "virtual", "machine", "to", "generalized", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java#L1471-L1478
hankcs/HanLP
src/main/java/com/hankcs/hanlp/model/perceptron/model/StructuredPerceptron.java
StructuredPerceptron.update
public void update(int[] goldIndex, int[] predictIndex) { """ 根据答案和预测更新参数 @param goldIndex 答案的特征函数(非压缩形式) @param predictIndex 预测的特征函数(非压缩形式) """ for (int i = 0; i < goldIndex.length; ++i) { if (goldIndex[i] == predictIndex[i]) continue; else // 预测与答案不一致 { parameter[goldIndex[i]]++; // 奖励正确的特征函数(将它的权值加一) if (predictIndex[i] >= 0 && predictIndex[i] < parameter.length) parameter[predictIndex[i]]--; // 惩罚招致错误的特征函数(将它的权值减一) else { throw new IllegalArgumentException("更新参数时传入了非法的下标"); } } } }
java
public void update(int[] goldIndex, int[] predictIndex) { for (int i = 0; i < goldIndex.length; ++i) { if (goldIndex[i] == predictIndex[i]) continue; else // 预测与答案不一致 { parameter[goldIndex[i]]++; // 奖励正确的特征函数(将它的权值加一) if (predictIndex[i] >= 0 && predictIndex[i] < parameter.length) parameter[predictIndex[i]]--; // 惩罚招致错误的特征函数(将它的权值减一) else { throw new IllegalArgumentException("更新参数时传入了非法的下标"); } } } }
[ "public", "void", "update", "(", "int", "[", "]", "goldIndex", ",", "int", "[", "]", "predictIndex", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "goldIndex", ".", "length", ";", "++", "i", ")", "{", "if", "(", "goldIndex", "[", "i", "]", "==", "predictIndex", "[", "i", "]", ")", "continue", ";", "else", "// 预测与答案不一致", "{", "parameter", "[", "goldIndex", "[", "i", "]", "]", "++", ";", "// 奖励正确的特征函数(将它的权值加一)", "if", "(", "predictIndex", "[", "i", "]", ">=", "0", "&&", "predictIndex", "[", "i", "]", "<", "parameter", ".", "length", ")", "parameter", "[", "predictIndex", "[", "i", "]", "]", "--", ";", "// 惩罚招致错误的特征函数(将它的权值减一)", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"更新参数时传入了非法的下标\");", "", "", "}", "}", "}", "}" ]
根据答案和预测更新参数 @param goldIndex 答案的特征函数(非压缩形式) @param predictIndex 预测的特征函数(非压缩形式)
[ "根据答案和预测更新参数" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/model/StructuredPerceptron.java#L41-L58
Jasig/spring-portlet-contrib
spring-security-portlet-contrib/src/main/java/org/jasig/springframework/security/portlet/PortletFilterChainProxy.java
PortletFilterChainProxy.setFilterChainMap
@Deprecated public void setFilterChainMap(Map<RequestMatcher, List<PortletFilter>> filterChainMap) { """ Sets the mapping of URL patterns to filter chains. The map keys should be the paths and the values should be arrays of {@code PortletFilter} objects. It's VERY important that the type of map used preserves ordering - the order in which the iterator returns the entries must be the same as the order they were added to the map, otherwise you have no way of guaranteeing that the most specific patterns are returned before the more general ones. So make sure the Map used is an instance of {@code LinkedHashMap} or an equivalent, rather than a plain {@code HashMap}, for example. @param filterChainMap the map of path Strings to {@code List&lt;PortletFilter&gt;}s. @deprecated Use the constructor which takes a {@code List&lt;PortletSecurityFilterChain&gt;} instead. """ filterChains = new ArrayList<PortletSecurityFilterChain>(filterChainMap.size()); for (Map.Entry<RequestMatcher,List<PortletFilter>> entry : filterChainMap.entrySet()) { filterChains.add(new DefaultPortletSecurityFilterChain(entry.getKey(), entry.getValue())); } }
java
@Deprecated public void setFilterChainMap(Map<RequestMatcher, List<PortletFilter>> filterChainMap) { filterChains = new ArrayList<PortletSecurityFilterChain>(filterChainMap.size()); for (Map.Entry<RequestMatcher,List<PortletFilter>> entry : filterChainMap.entrySet()) { filterChains.add(new DefaultPortletSecurityFilterChain(entry.getKey(), entry.getValue())); } }
[ "@", "Deprecated", "public", "void", "setFilterChainMap", "(", "Map", "<", "RequestMatcher", ",", "List", "<", "PortletFilter", ">", ">", "filterChainMap", ")", "{", "filterChains", "=", "new", "ArrayList", "<", "PortletSecurityFilterChain", ">", "(", "filterChainMap", ".", "size", "(", ")", ")", ";", "for", "(", "Map", ".", "Entry", "<", "RequestMatcher", ",", "List", "<", "PortletFilter", ">", ">", "entry", ":", "filterChainMap", ".", "entrySet", "(", ")", ")", "{", "filterChains", ".", "add", "(", "new", "DefaultPortletSecurityFilterChain", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "}" ]
Sets the mapping of URL patterns to filter chains. The map keys should be the paths and the values should be arrays of {@code PortletFilter} objects. It's VERY important that the type of map used preserves ordering - the order in which the iterator returns the entries must be the same as the order they were added to the map, otherwise you have no way of guaranteeing that the most specific patterns are returned before the more general ones. So make sure the Map used is an instance of {@code LinkedHashMap} or an equivalent, rather than a plain {@code HashMap}, for example. @param filterChainMap the map of path Strings to {@code List&lt;PortletFilter&gt;}s. @deprecated Use the constructor which takes a {@code List&lt;PortletSecurityFilterChain&gt;} instead.
[ "Sets", "the", "mapping", "of", "URL", "patterns", "to", "filter", "chains", "." ]
train
https://github.com/Jasig/spring-portlet-contrib/blob/719240fa268ddc69900ce9775d9cad3b9c543c6b/spring-security-portlet-contrib/src/main/java/org/jasig/springframework/security/portlet/PortletFilterChainProxy.java#L207-L214
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/ExplicitMessageEncryptionElement.java
ExplicitMessageEncryptionElement.set
public static void set(Message message, ExplicitMessageEncryptionProtocol protocol) { """ Add an EME element containing the specified {@code protocol} namespace to the message. In case there is already an element with that protocol, we do nothing. @param message message @param protocol encryption protocol """ if (!hasProtocol(message, protocol.namespace)) { message.addExtension(new ExplicitMessageEncryptionElement(protocol)); } }
java
public static void set(Message message, ExplicitMessageEncryptionProtocol protocol) { if (!hasProtocol(message, protocol.namespace)) { message.addExtension(new ExplicitMessageEncryptionElement(protocol)); } }
[ "public", "static", "void", "set", "(", "Message", "message", ",", "ExplicitMessageEncryptionProtocol", "protocol", ")", "{", "if", "(", "!", "hasProtocol", "(", "message", ",", "protocol", ".", "namespace", ")", ")", "{", "message", ".", "addExtension", "(", "new", "ExplicitMessageEncryptionElement", "(", "protocol", ")", ")", ";", "}", "}" ]
Add an EME element containing the specified {@code protocol} namespace to the message. In case there is already an element with that protocol, we do nothing. @param message message @param protocol encryption protocol
[ "Add", "an", "EME", "element", "containing", "the", "specified", "{", "@code", "protocol", "}", "namespace", "to", "the", "message", ".", "In", "case", "there", "is", "already", "an", "element", "with", "that", "protocol", "we", "do", "nothing", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/ExplicitMessageEncryptionElement.java#L190-L194
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/visitclass/PreorderVisitor.java
PreorderVisitor.getSizeOfSurroundingTryBlock
public int getSizeOfSurroundingTryBlock(String vmNameOfExceptionClass, int pc) { """ Get lines of code in try block that surround pc @param pc @return number of lines of code in try block """ if (code == null) { throw new IllegalStateException("Not visiting Code"); } return Util.getSizeOfSurroundingTryBlock(constantPool, code, vmNameOfExceptionClass, pc); }
java
public int getSizeOfSurroundingTryBlock(String vmNameOfExceptionClass, int pc) { if (code == null) { throw new IllegalStateException("Not visiting Code"); } return Util.getSizeOfSurroundingTryBlock(constantPool, code, vmNameOfExceptionClass, pc); }
[ "public", "int", "getSizeOfSurroundingTryBlock", "(", "String", "vmNameOfExceptionClass", ",", "int", "pc", ")", "{", "if", "(", "code", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Not visiting Code\"", ")", ";", "}", "return", "Util", ".", "getSizeOfSurroundingTryBlock", "(", "constantPool", ",", "code", ",", "vmNameOfExceptionClass", ",", "pc", ")", ";", "}" ]
Get lines of code in try block that surround pc @param pc @return number of lines of code in try block
[ "Get", "lines", "of", "code", "in", "try", "block", "that", "surround", "pc" ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/visitclass/PreorderVisitor.java#L221-L226
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isGreaterThan
public static void isGreaterThan( int argument, int greaterThanValue, String name ) { """ Check that the argument is greater than the supplied value @param argument The argument @param greaterThanValue the value that is to be used to check the value @param name The name of the argument @throws IllegalArgumentException If argument is not greater than the supplied value """ if (argument <= greaterThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeGreaterThan.text(name, argument, greaterThanValue)); } }
java
public static void isGreaterThan( int argument, int greaterThanValue, String name ) { if (argument <= greaterThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeGreaterThan.text(name, argument, greaterThanValue)); } }
[ "public", "static", "void", "isGreaterThan", "(", "int", "argument", ",", "int", "greaterThanValue", ",", "String", "name", ")", "{", "if", "(", "argument", "<=", "greaterThanValue", ")", "{", "throw", "new", "IllegalArgumentException", "(", "CommonI18n", ".", "argumentMustBeGreaterThan", ".", "text", "(", "name", ",", "argument", ",", "greaterThanValue", ")", ")", ";", "}", "}" ]
Check that the argument is greater than the supplied value @param argument The argument @param greaterThanValue the value that is to be used to check the value @param name The name of the argument @throws IllegalArgumentException If argument is not greater than the supplied value
[ "Check", "that", "the", "argument", "is", "greater", "than", "the", "supplied", "value" ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L73-L79
ironjacamar/ironjacamar
web/src/main/java/org/ironjacamar/web/SecurityActions.java
SecurityActions.createWebAppClassLoader
static WebAppClassLoader createWebAppClassLoader(final ClassLoader cl, final WebAppContext wac) { """ Create a WebClassLoader @param cl The classloader @param wac The web app context @return The class loader """ return AccessController.doPrivileged(new PrivilegedAction<WebAppClassLoader>() { public WebAppClassLoader run() { try { return new WebAppClassLoader(cl, wac); } catch (IOException ioe) { return null; } } }); }
java
static WebAppClassLoader createWebAppClassLoader(final ClassLoader cl, final WebAppContext wac) { return AccessController.doPrivileged(new PrivilegedAction<WebAppClassLoader>() { public WebAppClassLoader run() { try { return new WebAppClassLoader(cl, wac); } catch (IOException ioe) { return null; } } }); }
[ "static", "WebAppClassLoader", "createWebAppClassLoader", "(", "final", "ClassLoader", "cl", ",", "final", "WebAppContext", "wac", ")", "{", "return", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedAction", "<", "WebAppClassLoader", ">", "(", ")", "{", "public", "WebAppClassLoader", "run", "(", ")", "{", "try", "{", "return", "new", "WebAppClassLoader", "(", "cl", ",", "wac", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "return", "null", ";", "}", "}", "}", ")", ";", "}" ]
Create a WebClassLoader @param cl The classloader @param wac The web app context @return The class loader
[ "Create", "a", "WebClassLoader" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/web/src/main/java/org/ironjacamar/web/SecurityActions.java#L152-L168
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.createFieldAccessor
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess) { """ Creates an expression that reads the field. Will either be {@code this.field} or {@code this.getField()} depending on whether or not there's a getter. """ return createFieldAccessor(maker, field, fieldAccess, null); }
java
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess) { return createFieldAccessor(maker, field, fieldAccess, null); }
[ "static", "JCExpression", "createFieldAccessor", "(", "JavacTreeMaker", "maker", ",", "JavacNode", "field", ",", "FieldAccess", "fieldAccess", ")", "{", "return", "createFieldAccessor", "(", "maker", ",", "field", ",", "fieldAccess", ",", "null", ")", ";", "}" ]
Creates an expression that reads the field. Will either be {@code this.field} or {@code this.getField()} depending on whether or not there's a getter.
[ "Creates", "an", "expression", "that", "reads", "the", "field", ".", "Will", "either", "be", "{" ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L941-L943
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java
HTTPBatchClientConnectionInterceptor.prepareHttpRequest
private <T extends CloseableHttpClient> HttpRequestBase prepareHttpRequest(RequestElements intuitRequest) throws FMSException { """ Returns httpRequest instance with configured fields @param intuitRequest @param client @param <T> @return @throws FMSException """ //setTimeout(client, intuitRequest.getContext()); HttpRequestBase httpRequest = extractMethod(intuitRequest, extractURI(intuitRequest)); // populate the headers to HttpRequestBase populateRequestHeaders(httpRequest, intuitRequest.getRequestHeaders()); // authorize the request authorizeRequest(intuitRequest.getContext(), httpRequest); LOG.debug("Request URI : " + httpRequest.getURI()); LOG.debug("Http Method : " + httpRequest.getMethod()); return httpRequest; }
java
private <T extends CloseableHttpClient> HttpRequestBase prepareHttpRequest(RequestElements intuitRequest) throws FMSException { //setTimeout(client, intuitRequest.getContext()); HttpRequestBase httpRequest = extractMethod(intuitRequest, extractURI(intuitRequest)); // populate the headers to HttpRequestBase populateRequestHeaders(httpRequest, intuitRequest.getRequestHeaders()); // authorize the request authorizeRequest(intuitRequest.getContext(), httpRequest); LOG.debug("Request URI : " + httpRequest.getURI()); LOG.debug("Http Method : " + httpRequest.getMethod()); return httpRequest; }
[ "private", "<", "T", "extends", "CloseableHttpClient", ">", "HttpRequestBase", "prepareHttpRequest", "(", "RequestElements", "intuitRequest", ")", "throws", "FMSException", "{", "//setTimeout(client, intuitRequest.getContext());", "HttpRequestBase", "httpRequest", "=", "extractMethod", "(", "intuitRequest", ",", "extractURI", "(", "intuitRequest", ")", ")", ";", "// populate the headers to HttpRequestBase", "populateRequestHeaders", "(", "httpRequest", ",", "intuitRequest", ".", "getRequestHeaders", "(", ")", ")", ";", "// authorize the request", "authorizeRequest", "(", "intuitRequest", ".", "getContext", "(", ")", ",", "httpRequest", ")", ";", "LOG", ".", "debug", "(", "\"Request URI : \"", "+", "httpRequest", ".", "getURI", "(", ")", ")", ";", "LOG", ".", "debug", "(", "\"Http Method : \"", "+", "httpRequest", ".", "getMethod", "(", ")", ")", ";", "return", "httpRequest", ";", "}" ]
Returns httpRequest instance with configured fields @param intuitRequest @param client @param <T> @return @throws FMSException
[ "Returns", "httpRequest", "instance", "with", "configured", "fields" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java#L230-L245
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java
SecStrucCalc.setSecStrucType
private void setSecStrucType(int pos, SecStrucType type) { """ Set the new type only if it has more preference than the current residue SS type. @param pos @param type """ SecStrucState ss = getSecStrucState(pos); if (type.compareTo(ss.getType()) < 0) ss.setType(type); }
java
private void setSecStrucType(int pos, SecStrucType type){ SecStrucState ss = getSecStrucState(pos); if (type.compareTo(ss.getType()) < 0) ss.setType(type); }
[ "private", "void", "setSecStrucType", "(", "int", "pos", ",", "SecStrucType", "type", ")", "{", "SecStrucState", "ss", "=", "getSecStrucState", "(", "pos", ")", ";", "if", "(", "type", ".", "compareTo", "(", "ss", ".", "getType", "(", ")", ")", "<", "0", ")", "ss", ".", "setType", "(", "type", ")", ";", "}" ]
Set the new type only if it has more preference than the current residue SS type. @param pos @param type
[ "Set", "the", "new", "type", "only", "if", "it", "has", "more", "preference", "than", "the", "current", "residue", "SS", "type", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java#L1137-L1140
fcrepo3/fcrepo
fcrepo-security/fcrepo-security-jaas/src/main/java/org/fcrepo/server/security/jaas/AuthFilterJAAS.java
AuthFilterJAAS.authenticate
private Subject authenticate(HttpServletRequest req) { """ Performs the authentication. Once a Subject is obtained, it is stored in the users session. Subsequent requests check for the existence of this object before performing the authentication again. @param req the servlet request. @return a user principal that was extracted from the login context. """ String authorization = req.getHeader("authorization"); if (authorization == null || authorization.trim().isEmpty()) { return null; } // subject from session instead of re-authenticating // can't change username/password for this session. Subject subject = (Subject) req.getSession().getAttribute(authorization); if (subject != null) { return subject; } String auth = null; try { byte[] data = Base64.decode(authorization.substring(6)); auth = new String(data); } catch (IOException e) { logger.error(e.toString()); return null; } String username = auth.substring(0, auth.indexOf(':')); String password = auth.substring(auth.indexOf(':') + 1); if (logger.isDebugEnabled()) { logger.debug("auth username: " + username); } LoginContext loginContext = null; try { CallbackHandler handler = new UsernamePasswordCallbackHandler(username, password); loginContext = new LoginContext(jaasConfigName, handler); loginContext.login(); } catch (LoginException le) { logger.error(le.toString()); return null; } // successfully logged in subject = loginContext.getSubject(); // object accessable by a fixed key for usage req.getSession().setAttribute(SESSION_SUBJECT_KEY, subject); // object accessable only by base64 encoded username:password that was // initially used - prevents some dodgy stuff req.getSession().setAttribute(authorization, subject); return subject; }
java
private Subject authenticate(HttpServletRequest req) { String authorization = req.getHeader("authorization"); if (authorization == null || authorization.trim().isEmpty()) { return null; } // subject from session instead of re-authenticating // can't change username/password for this session. Subject subject = (Subject) req.getSession().getAttribute(authorization); if (subject != null) { return subject; } String auth = null; try { byte[] data = Base64.decode(authorization.substring(6)); auth = new String(data); } catch (IOException e) { logger.error(e.toString()); return null; } String username = auth.substring(0, auth.indexOf(':')); String password = auth.substring(auth.indexOf(':') + 1); if (logger.isDebugEnabled()) { logger.debug("auth username: " + username); } LoginContext loginContext = null; try { CallbackHandler handler = new UsernamePasswordCallbackHandler(username, password); loginContext = new LoginContext(jaasConfigName, handler); loginContext.login(); } catch (LoginException le) { logger.error(le.toString()); return null; } // successfully logged in subject = loginContext.getSubject(); // object accessable by a fixed key for usage req.getSession().setAttribute(SESSION_SUBJECT_KEY, subject); // object accessable only by base64 encoded username:password that was // initially used - prevents some dodgy stuff req.getSession().setAttribute(authorization, subject); return subject; }
[ "private", "Subject", "authenticate", "(", "HttpServletRequest", "req", ")", "{", "String", "authorization", "=", "req", ".", "getHeader", "(", "\"authorization\"", ")", ";", "if", "(", "authorization", "==", "null", "||", "authorization", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "// subject from session instead of re-authenticating", "// can't change username/password for this session.", "Subject", "subject", "=", "(", "Subject", ")", "req", ".", "getSession", "(", ")", ".", "getAttribute", "(", "authorization", ")", ";", "if", "(", "subject", "!=", "null", ")", "{", "return", "subject", ";", "}", "String", "auth", "=", "null", ";", "try", "{", "byte", "[", "]", "data", "=", "Base64", ".", "decode", "(", "authorization", ".", "substring", "(", "6", ")", ")", ";", "auth", "=", "new", "String", "(", "data", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "toString", "(", ")", ")", ";", "return", "null", ";", "}", "String", "username", "=", "auth", ".", "substring", "(", "0", ",", "auth", ".", "indexOf", "(", "'", "'", ")", ")", ";", "String", "password", "=", "auth", ".", "substring", "(", "auth", ".", "indexOf", "(", "'", "'", ")", "+", "1", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"auth username: \"", "+", "username", ")", ";", "}", "LoginContext", "loginContext", "=", "null", ";", "try", "{", "CallbackHandler", "handler", "=", "new", "UsernamePasswordCallbackHandler", "(", "username", ",", "password", ")", ";", "loginContext", "=", "new", "LoginContext", "(", "jaasConfigName", ",", "handler", ")", ";", "loginContext", ".", "login", "(", ")", ";", "}", "catch", "(", "LoginException", "le", ")", "{", "logger", ".", "error", "(", "le", ".", "toString", "(", ")", ")", ";", "return", "null", ";", "}", "// successfully logged in", "subject", "=", "loginContext", ".", "getSubject", "(", ")", ";", "// object accessable by a fixed key for usage", "req", ".", "getSession", "(", ")", ".", "setAttribute", "(", "SESSION_SUBJECT_KEY", ",", "subject", ")", ";", "// object accessable only by base64 encoded username:password that was", "// initially used - prevents some dodgy stuff", "req", ".", "getSession", "(", ")", ".", "setAttribute", "(", "authorization", ",", "subject", ")", ";", "return", "subject", ";", "}" ]
Performs the authentication. Once a Subject is obtained, it is stored in the users session. Subsequent requests check for the existence of this object before performing the authentication again. @param req the servlet request. @return a user principal that was extracted from the login context.
[ "Performs", "the", "authentication", ".", "Once", "a", "Subject", "is", "obtained", "it", "is", "stored", "in", "the", "users", "session", ".", "Subsequent", "requests", "check", "for", "the", "existence", "of", "this", "object", "before", "performing", "the", "authentication", "again", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-jaas/src/main/java/org/fcrepo/server/security/jaas/AuthFilterJAAS.java#L369-L421
alkacon/opencms-core
src/org/opencms/ui/apps/resourcetypes/CmsResourceTypesTable.java
CmsResourceTypesTable.openEditDialog
void openEditDialog(String typeName) { """ Opens the edit dialog.<p> @param typeName type to be edited. """ try { Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent( new CmsEditResourceTypeDialog(window, m_app, OpenCms.getResourceManager().getResourceType(typeName))); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_RESOURCETYPE_EDIT_WINDOW_CAPTION_0)); A_CmsUI.get().addWindow(window); } catch (CmsLoaderException e) { LOG.error("Unable to read resource type by name", e); } }
java
void openEditDialog(String typeName) { try { Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent( new CmsEditResourceTypeDialog(window, m_app, OpenCms.getResourceManager().getResourceType(typeName))); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_RESOURCETYPE_EDIT_WINDOW_CAPTION_0)); A_CmsUI.get().addWindow(window); } catch (CmsLoaderException e) { LOG.error("Unable to read resource type by name", e); } }
[ "void", "openEditDialog", "(", "String", "typeName", ")", "{", "try", "{", "Window", "window", "=", "CmsBasicDialog", ".", "prepareWindow", "(", "DialogWidth", ".", "max", ")", ";", "window", ".", "setContent", "(", "new", "CmsEditResourceTypeDialog", "(", "window", ",", "m_app", ",", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "typeName", ")", ")", ")", ";", "window", ".", "setCaption", "(", "CmsVaadinUtils", ".", "getMessageText", "(", "Messages", ".", "GUI_RESOURCETYPE_EDIT_WINDOW_CAPTION_0", ")", ")", ";", "A_CmsUI", ".", "get", "(", ")", ".", "addWindow", "(", "window", ")", ";", "}", "catch", "(", "CmsLoaderException", "e", ")", "{", "LOG", ".", "error", "(", "\"Unable to read resource type by name\"", ",", "e", ")", ";", "}", "}" ]
Opens the edit dialog.<p> @param typeName type to be edited.
[ "Opens", "the", "edit", "dialog", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/resourcetypes/CmsResourceTypesTable.java#L722-L734
zamrokk/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/MemberServicesImpl.java
MemberServicesImpl.getTCertBatch
public List<TCert> getTCertBatch(GetTCertBatchRequest req) throws GetTCertBatchException { """ Get an array of transaction certificates (tcerts). @param req Request of the form: name, enrollment, num @return enrollment """ logger.debug(String.format("[MemberServicesImpl.getTCertBatch] [%s]", req)); try { // create the proto TCertCreateSetReq.Builder tCertCreateSetReq = TCertCreateSetReq.newBuilder() .setTs(Timestamp.newBuilder().setSeconds(new java.util.Date().getTime())) .setId(Identity.newBuilder().setId(req.getName())) .setNum(req.getNum()); if (req.getAttrs() != null) { for (String attr : req.getAttrs()) { tCertCreateSetReq.addAttributes(TCertAttribute.newBuilder().setAttributeName(attr).build()); } } // serialize proto byte[] buf = tCertCreateSetReq.buildPartial().toByteArray(); // sign the transaction using enrollment key java.security.PrivateKey signKey = cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(req.getEnrollment().getKey())); BigInteger[] sig = cryptoPrimitives.ecdsaSign(signKey, buf); Signature protoSig = Signature.newBuilder().setType(CryptoType.ECDSA).setR(ByteString.copyFrom(sig[0].toString().getBytes())).setS(ByteString.copyFrom(sig[1].toString().getBytes())).build(); tCertCreateSetReq.setSig(protoSig); // send the request TCertCreateSetResp tCertCreateSetResp = tcapClient.createCertificateSet(tCertCreateSetReq.build()); logger.debug("[MemberServicesImpl.getTCertBatch] tCertCreateSetResp : [%s]" + tCertCreateSetResp.toByteString()); return processTCertBatch(req, tCertCreateSetResp); } catch (Exception e) { throw new GetTCertBatchException("Failed to get tcerts", e); } }
java
public List<TCert> getTCertBatch(GetTCertBatchRequest req) throws GetTCertBatchException { logger.debug(String.format("[MemberServicesImpl.getTCertBatch] [%s]", req)); try { // create the proto TCertCreateSetReq.Builder tCertCreateSetReq = TCertCreateSetReq.newBuilder() .setTs(Timestamp.newBuilder().setSeconds(new java.util.Date().getTime())) .setId(Identity.newBuilder().setId(req.getName())) .setNum(req.getNum()); if (req.getAttrs() != null) { for (String attr : req.getAttrs()) { tCertCreateSetReq.addAttributes(TCertAttribute.newBuilder().setAttributeName(attr).build()); } } // serialize proto byte[] buf = tCertCreateSetReq.buildPartial().toByteArray(); // sign the transaction using enrollment key java.security.PrivateKey signKey = cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(req.getEnrollment().getKey())); BigInteger[] sig = cryptoPrimitives.ecdsaSign(signKey, buf); Signature protoSig = Signature.newBuilder().setType(CryptoType.ECDSA).setR(ByteString.copyFrom(sig[0].toString().getBytes())).setS(ByteString.copyFrom(sig[1].toString().getBytes())).build(); tCertCreateSetReq.setSig(protoSig); // send the request TCertCreateSetResp tCertCreateSetResp = tcapClient.createCertificateSet(tCertCreateSetReq.build()); logger.debug("[MemberServicesImpl.getTCertBatch] tCertCreateSetResp : [%s]" + tCertCreateSetResp.toByteString()); return processTCertBatch(req, tCertCreateSetResp); } catch (Exception e) { throw new GetTCertBatchException("Failed to get tcerts", e); } }
[ "public", "List", "<", "TCert", ">", "getTCertBatch", "(", "GetTCertBatchRequest", "req", ")", "throws", "GetTCertBatchException", "{", "logger", ".", "debug", "(", "String", ".", "format", "(", "\"[MemberServicesImpl.getTCertBatch] [%s]\"", ",", "req", ")", ")", ";", "try", "{", "// create the proto", "TCertCreateSetReq", ".", "Builder", "tCertCreateSetReq", "=", "TCertCreateSetReq", ".", "newBuilder", "(", ")", ".", "setTs", "(", "Timestamp", ".", "newBuilder", "(", ")", ".", "setSeconds", "(", "new", "java", ".", "util", ".", "Date", "(", ")", ".", "getTime", "(", ")", ")", ")", ".", "setId", "(", "Identity", ".", "newBuilder", "(", ")", ".", "setId", "(", "req", ".", "getName", "(", ")", ")", ")", ".", "setNum", "(", "req", ".", "getNum", "(", ")", ")", ";", "if", "(", "req", ".", "getAttrs", "(", ")", "!=", "null", ")", "{", "for", "(", "String", "attr", ":", "req", ".", "getAttrs", "(", ")", ")", "{", "tCertCreateSetReq", ".", "addAttributes", "(", "TCertAttribute", ".", "newBuilder", "(", ")", ".", "setAttributeName", "(", "attr", ")", ".", "build", "(", ")", ")", ";", "}", "}", "// serialize proto", "byte", "[", "]", "buf", "=", "tCertCreateSetReq", ".", "buildPartial", "(", ")", ".", "toByteArray", "(", ")", ";", "// sign the transaction using enrollment key", "java", ".", "security", ".", "PrivateKey", "signKey", "=", "cryptoPrimitives", ".", "ecdsaKeyFromPrivate", "(", "Hex", ".", "decode", "(", "req", ".", "getEnrollment", "(", ")", ".", "getKey", "(", ")", ")", ")", ";", "BigInteger", "[", "]", "sig", "=", "cryptoPrimitives", ".", "ecdsaSign", "(", "signKey", ",", "buf", ")", ";", "Signature", "protoSig", "=", "Signature", ".", "newBuilder", "(", ")", ".", "setType", "(", "CryptoType", ".", "ECDSA", ")", ".", "setR", "(", "ByteString", ".", "copyFrom", "(", "sig", "[", "0", "]", ".", "toString", "(", ")", ".", "getBytes", "(", ")", ")", ")", ".", "setS", "(", "ByteString", ".", "copyFrom", "(", "sig", "[", "1", "]", ".", "toString", "(", ")", ".", "getBytes", "(", ")", ")", ")", ".", "build", "(", ")", ";", "tCertCreateSetReq", ".", "setSig", "(", "protoSig", ")", ";", "// send the request", "TCertCreateSetResp", "tCertCreateSetResp", "=", "tcapClient", ".", "createCertificateSet", "(", "tCertCreateSetReq", ".", "build", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"[MemberServicesImpl.getTCertBatch] tCertCreateSetResp : [%s]\"", "+", "tCertCreateSetResp", ".", "toByteString", "(", ")", ")", ";", "return", "processTCertBatch", "(", "req", ",", "tCertCreateSetResp", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "GetTCertBatchException", "(", "\"Failed to get tcerts\"", ",", "e", ")", ";", "}", "}" ]
Get an array of transaction certificates (tcerts). @param req Request of the form: name, enrollment, num @return enrollment
[ "Get", "an", "array", "of", "transaction", "certificates", "(", "tcerts", ")", "." ]
train
https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/MemberServicesImpl.java#L243-L276