repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
aws/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/buffered/AmazonSQSBufferedAsyncClient.java
AmazonSQSBufferedAsyncClient.getQBuffer
private synchronized QueueBuffer getQBuffer(String qUrl) { QueueBuffer toReturn = buffers.get(qUrl); if (null == toReturn) { QueueBufferConfig config = new QueueBufferConfig(bufferConfigExemplar); toReturn = new QueueBuffer(config, qUrl, realSQS); buffers.put(qUrl, toReturn); } return toReturn; }
java
private synchronized QueueBuffer getQBuffer(String qUrl) { QueueBuffer toReturn = buffers.get(qUrl); if (null == toReturn) { QueueBufferConfig config = new QueueBufferConfig(bufferConfigExemplar); toReturn = new QueueBuffer(config, qUrl, realSQS); buffers.put(qUrl, toReturn); } return toReturn; }
[ "private", "synchronized", "QueueBuffer", "getQBuffer", "(", "String", "qUrl", ")", "{", "QueueBuffer", "toReturn", "=", "buffers", ".", "get", "(", "qUrl", ")", ";", "if", "(", "null", "==", "toReturn", ")", "{", "QueueBufferConfig", "config", "=", "new", ...
Returns (creating it if necessary) a queue buffer for a particular queue Since we are only storing a limited number of queue buffers, it is possible that as a result of calling this method the least recently used queue buffer will be removed from our queue buffer cache @return a queue buffer associated with the provided queue URL. Never null
[ "Returns", "(", "creating", "it", "if", "necessary", ")", "a", "queue", "buffer", "for", "a", "particular", "queue", "Since", "we", "are", "only", "storing", "a", "limited", "number", "of", "queue", "buffers", "it", "is", "possible", "that", "as", "a", "...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/buffered/AmazonSQSBufferedAsyncClient.java#L378-L386
molgenis/molgenis
molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlRepositoryCollection.java
PostgreSqlRepositoryCollection.updateEnumOptions
private void updateEnumOptions(EntityType entityType, Attribute attr, Attribute updatedAttr) { if (attr.getDataType() == ENUM) { if (updatedAttr.getDataType() == ENUM) { // update check constraint dropCheckConstraint(entityType, attr); createCheckConstraint(entityType, updatedAttr); } else { // drop check constraint dropCheckConstraint(entityType, attr); } } else { if (updatedAttr.getDataType() == ENUM) { createCheckConstraint(entityType, updatedAttr); } } }
java
private void updateEnumOptions(EntityType entityType, Attribute attr, Attribute updatedAttr) { if (attr.getDataType() == ENUM) { if (updatedAttr.getDataType() == ENUM) { // update check constraint dropCheckConstraint(entityType, attr); createCheckConstraint(entityType, updatedAttr); } else { // drop check constraint dropCheckConstraint(entityType, attr); } } else { if (updatedAttr.getDataType() == ENUM) { createCheckConstraint(entityType, updatedAttr); } } }
[ "private", "void", "updateEnumOptions", "(", "EntityType", "entityType", ",", "Attribute", "attr", ",", "Attribute", "updatedAttr", ")", "{", "if", "(", "attr", ".", "getDataType", "(", ")", "==", "ENUM", ")", "{", "if", "(", "updatedAttr", ".", "getDataType...
Updates check constraint based on enum value changes. @param entityType entity meta data @param attr current attribute @param updatedAttr updated attribute
[ "Updates", "check", "constraint", "based", "on", "enum", "value", "changes", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlRepositoryCollection.java#L434-L449
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java
ProcessUtil.getMBeanServerConnection
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent); final JMXConnector connector = JMXConnectorFactory.connect(serviceURL); final MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent); final JMXConnector connector = JMXConnectorFactory.connect(serviceURL); final MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "MBeanServerConnection", "getMBeanServerConnection", "(", "Process", "p", ",", "boolean", "startAgent", ")", "{", "try", "{", "final", "JMXServiceURL", "serviceURL", "=", "getLocalConnectorAddress", "(", "p", ",", "startAgent", ")", ";", "final",...
Connects to a child JVM process @param p the process to which to connect @param startAgent whether to installed the JMX agent in the target process if not already in place @return an {@link MBeanServerConnection} to the process's MBean server
[ "Connects", "to", "a", "child", "JVM", "process" ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java#L67-L76
transloadit/java-sdk
src/main/java/com/transloadit/sdk/Transloadit.java
Transloadit.listTemplates
public ListResponse listTemplates(Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new ListResponse(request.get("/templates", options)); }
java
public ListResponse listTemplates(Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new ListResponse(request.get("/templates", options)); }
[ "public", "ListResponse", "listTemplates", "(", "Map", "<", "String", ",", "Object", ">", "options", ")", "throws", "RequestException", ",", "LocalOperationException", "{", "Request", "request", "=", "new", "Request", "(", "this", ")", ";", "return", "new", "L...
Returns a list of all templates under the user account @param options {@link Map} extra options to send along with the request. @return {@link ListResponse} @throws RequestException if request to transloadit server fails. @throws LocalOperationException if something goes wrong while running non-http operations.
[ "Returns", "a", "list", "of", "all", "templates", "under", "the", "user", "account" ]
train
https://github.com/transloadit/java-sdk/blob/9326c540a66f77b3d907d0b2c05bff1145ca14f7/src/main/java/com/transloadit/sdk/Transloadit.java#L240-L244
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/labeler/OmsLabeler.java
OmsLabeler.getNeighbours
private int getNeighbours( int[] src1d, int i, int ox, int oy, int d_w, int d_h ) { int x, y, result; x = (i % d_w) + ox; // d_w and d_h are assumed to be set to the y = (i / d_w) + oy; // width and height of scr1d if ((x < 0) || (x >= d_w) || (y < 0) || (y >= d_h)) { result = 0; } else { result = src1d[y * d_w + x] & 0x000000ff; } return result; }
java
private int getNeighbours( int[] src1d, int i, int ox, int oy, int d_w, int d_h ) { int x, y, result; x = (i % d_w) + ox; // d_w and d_h are assumed to be set to the y = (i / d_w) + oy; // width and height of scr1d if ((x < 0) || (x >= d_w) || (y < 0) || (y >= d_h)) { result = 0; } else { result = src1d[y * d_w + x] & 0x000000ff; } return result; }
[ "private", "int", "getNeighbours", "(", "int", "[", "]", "src1d", ",", "int", "i", ",", "int", "ox", ",", "int", "oy", ",", "int", "d_w", ",", "int", "d_h", ")", "{", "int", "x", ",", "y", ",", "result", ";", "x", "=", "(", "i", "%", "d_w", ...
getNeighbours will get the pixel value of i's neighbour that's ox and oy away from i, if the point is outside the image, then 0 is returned. This version gets from source image. @param d_w @param d_h
[ "getNeighbours", "will", "get", "the", "pixel", "value", "of", "i", "s", "neighbour", "that", "s", "ox", "and", "oy", "away", "from", "i", "if", "the", "point", "is", "outside", "the", "image", "then", "0", "is", "returned", ".", "This", "version", "ge...
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/labeler/OmsLabeler.java#L248-L260
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/LowLevelMultiViewOps.java
LowLevelMultiViewOps.computeNormalization
public static void computeNormalization(List<Point2D_F64> points, NormalizationPoint2D normalize ) { double meanX = 0; double meanY = 0; for( Point2D_F64 p : points ) { meanX += p.x; meanY += p.y; } meanX /= points.size(); meanY /= points.size(); double stdX = 0; double stdY = 0; for( Point2D_F64 p : points ) { double dx = p.x - meanX; double dy = p.y - meanY; stdX += dx*dx; stdY += dy*dy; } normalize.meanX = meanX; normalize.meanY = meanY; normalize.stdX = Math.sqrt(stdX/points.size()); normalize.stdY = Math.sqrt(stdY/points.size()); }
java
public static void computeNormalization(List<Point2D_F64> points, NormalizationPoint2D normalize ) { double meanX = 0; double meanY = 0; for( Point2D_F64 p : points ) { meanX += p.x; meanY += p.y; } meanX /= points.size(); meanY /= points.size(); double stdX = 0; double stdY = 0; for( Point2D_F64 p : points ) { double dx = p.x - meanX; double dy = p.y - meanY; stdX += dx*dx; stdY += dy*dy; } normalize.meanX = meanX; normalize.meanY = meanY; normalize.stdX = Math.sqrt(stdX/points.size()); normalize.stdY = Math.sqrt(stdY/points.size()); }
[ "public", "static", "void", "computeNormalization", "(", "List", "<", "Point2D_F64", ">", "points", ",", "NormalizationPoint2D", "normalize", ")", "{", "double", "meanX", "=", "0", ";", "double", "meanY", "=", "0", ";", "for", "(", "Point2D_F64", "p", ":", ...
<p>Computes a transform which will normalize the points such that they have zero mean and a standard deviation of one </p> <p> Y. Ma, S. Soatto, J. Kosecka, and S. S. Sastry, "An Invitation to 3-D Vision" Springer-Verlad, 2004 </p> @param points Input: List of observed points. Not modified. @param normalize Output: 3x3 normalization matrix for first set of points. Modified.
[ "<p", ">", "Computes", "a", "transform", "which", "will", "normalize", "the", "points", "such", "that", "they", "have", "zero", "mean", "and", "a", "standard", "deviation", "of", "one", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/LowLevelMultiViewOps.java#L47-L75
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxRequest.java
BoxRequest.send
public final T send() throws BoxException { Exception ex = null; T result = null; try { result = onSend(); } catch (Exception e){ ex = e; } // We catch the exception so that onSendCompleted can be called in case additional actions need to be taken onSendCompleted(new BoxResponse(result, ex, this)); if (ex != null) { if (ex instanceof BoxException){ throw (BoxException)ex; } else { throw new BoxException("unexpected exception ",ex); } } return result; }
java
public final T send() throws BoxException { Exception ex = null; T result = null; try { result = onSend(); } catch (Exception e){ ex = e; } // We catch the exception so that onSendCompleted can be called in case additional actions need to be taken onSendCompleted(new BoxResponse(result, ex, this)); if (ex != null) { if (ex instanceof BoxException){ throw (BoxException)ex; } else { throw new BoxException("unexpected exception ",ex); } } return result; }
[ "public", "final", "T", "send", "(", ")", "throws", "BoxException", "{", "Exception", "ex", "=", "null", ";", "T", "result", "=", "null", ";", "try", "{", "result", "=", "onSend", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ex", ...
Synchronously make the request to Box and handle the response appropriately. @return the expected BoxObject if the request is successful. @throws BoxException thrown if there was a problem with handling the request.
[ "Synchronously", "make", "the", "request", "to", "Box", "and", "handle", "the", "response", "appropriately", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxRequest.java#L189-L208
samskivert/samskivert
src/main/java/com/samskivert/jdbc/BaseLiaison.java
BaseLiaison.appendColumns
protected void appendColumns (Iterable<String> columns, StringBuilder buf) { int ii = 0; for (String column : columns) { if (ii++ > 0) { buf.append(", "); } buf.append(columnSQL(column)); } }
java
protected void appendColumns (Iterable<String> columns, StringBuilder buf) { int ii = 0; for (String column : columns) { if (ii++ > 0) { buf.append(", "); } buf.append(columnSQL(column)); } }
[ "protected", "void", "appendColumns", "(", "Iterable", "<", "String", ">", "columns", ",", "StringBuilder", "buf", ")", "{", "int", "ii", "=", "0", ";", "for", "(", "String", "column", ":", "columns", ")", "{", "if", "(", "ii", "++", ">", "0", ")", ...
Escapes {@code columns} with {@link #columnSQL}, appends (comma-sepped) to {@code buf}.
[ "Escapes", "{" ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/jdbc/BaseLiaison.java#L346-L354
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java
Utils.waitUntilReady
public static boolean waitUntilReady(BlockingQueue<Object> queue, long amount, TimeUnit timeUnit) { try { Object obj = queue.poll(amount, timeUnit); if (obj instanceof Boolean) { return (Boolean) obj; } else if (obj instanceof Throwable) { throw (Throwable) obj; } return false; } catch (Throwable t) { throw KubernetesClientException.launderThrowable(t); } }
java
public static boolean waitUntilReady(BlockingQueue<Object> queue, long amount, TimeUnit timeUnit) { try { Object obj = queue.poll(amount, timeUnit); if (obj instanceof Boolean) { return (Boolean) obj; } else if (obj instanceof Throwable) { throw (Throwable) obj; } return false; } catch (Throwable t) { throw KubernetesClientException.launderThrowable(t); } }
[ "public", "static", "boolean", "waitUntilReady", "(", "BlockingQueue", "<", "Object", ">", "queue", ",", "long", "amount", ",", "TimeUnit", "timeUnit", ")", "{", "try", "{", "Object", "obj", "=", "queue", ".", "poll", "(", "amount", ",", "timeUnit", ")", ...
Wait until an other thread signals the completion of a task. If an exception is passed, it will be propagated to the caller. @param queue The communication channel. @param amount The amount of time to wait. @param timeUnit The time unit. @return a boolean value indicating resource is ready or not.
[ "Wait", "until", "an", "other", "thread", "signals", "the", "completion", "of", "a", "task", ".", "If", "an", "exception", "is", "passed", "it", "will", "be", "propagated", "to", "the", "caller", ".", "@param", "queue", "The", "communication", "channel", "...
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java#L127-L139
alkacon/opencms-core
src/org/opencms/workplace/galleries/CmsAjaxLinkGallery.java
CmsAjaxLinkGallery.buildJsonItemSpecificPart
@Override protected void buildJsonItemSpecificPart(JSONObject jsonObj, CmsResource res, String sitePath) { // file target String pointer; try { pointer = new String(getCms().readFile(res).getContents()); if (CmsStringUtil.isEmptyOrWhitespaceOnly(pointer)) { pointer = getJsp().link(getCms().getSitePath(res)); } jsonObj.append("pointer", pointer); } catch (CmsException e) { // reading the resource or property value failed LOG.error(e.getLocalizedMessage(), e); } catch (JSONException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } }
java
@Override protected void buildJsonItemSpecificPart(JSONObject jsonObj, CmsResource res, String sitePath) { // file target String pointer; try { pointer = new String(getCms().readFile(res).getContents()); if (CmsStringUtil.isEmptyOrWhitespaceOnly(pointer)) { pointer = getJsp().link(getCms().getSitePath(res)); } jsonObj.append("pointer", pointer); } catch (CmsException e) { // reading the resource or property value failed LOG.error(e.getLocalizedMessage(), e); } catch (JSONException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } }
[ "@", "Override", "protected", "void", "buildJsonItemSpecificPart", "(", "JSONObject", "jsonObj", ",", "CmsResource", "res", ",", "String", "sitePath", ")", "{", "// file target", "String", "pointer", ";", "try", "{", "pointer", "=", "new", "String", "(", "getCms...
Fills the JSON object with the specific information used for pointer file resource type.<p> <ul> <li><code>pointer</code>: the content of the pointer resource. This could be an external or internal link.</li> </ul> @see org.opencms.workplace.galleries.A_CmsAjaxGallery#buildJsonItemSpecificPart(JSONObject jsonObj, CmsResource res, String sitePath)
[ "Fills", "the", "JSON", "object", "with", "the", "specific", "information", "used", "for", "pointer", "file", "resource", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/galleries/CmsAjaxLinkGallery.java#L158-L178
dmak/jaxb-xew-plugin
src/main/java/com/sun/tools/xjc/addon/xew/config/AbstractConfigurablePlugin.java
AbstractConfigurablePlugin.parseArgument
@Override public int parseArgument(Options opts, String[] args, int i) throws BadCommandLineException { initLoggerIfNecessary(opts); int recognized = 0; String arg = args[i]; logger.trace("Argument[" + i + "] = " + arg); if (arg.equals(getArgumentName(ConfigurationOption.APPLY_PLURAL_FORM.optionName()))) { globalConfiguration.setApplyPluralForm(true); return 1; } else if ((recognized = parseArgument(args, i, ConfigurationOption.CONTROL)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.SUMMARY)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.COLLECTION_INTERFACE)) == 0 // longer option name comes first && (recognized = parseArgument(args, i, ConfigurationOption.COLLECTION_IMPLEMENTATION)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.INSTANTIATION_MODE)) == 0) { if (arg.startsWith(getArgumentName(""))) { throw new BadCommandLineException("Invalid argument " + arg); } } return recognized; }
java
@Override public int parseArgument(Options opts, String[] args, int i) throws BadCommandLineException { initLoggerIfNecessary(opts); int recognized = 0; String arg = args[i]; logger.trace("Argument[" + i + "] = " + arg); if (arg.equals(getArgumentName(ConfigurationOption.APPLY_PLURAL_FORM.optionName()))) { globalConfiguration.setApplyPluralForm(true); return 1; } else if ((recognized = parseArgument(args, i, ConfigurationOption.CONTROL)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.SUMMARY)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.COLLECTION_INTERFACE)) == 0 // longer option name comes first && (recognized = parseArgument(args, i, ConfigurationOption.COLLECTION_IMPLEMENTATION)) == 0 && (recognized = parseArgument(args, i, ConfigurationOption.INSTANTIATION_MODE)) == 0) { if (arg.startsWith(getArgumentName(""))) { throw new BadCommandLineException("Invalid argument " + arg); } } return recognized; }
[ "@", "Override", "public", "int", "parseArgument", "(", "Options", "opts", ",", "String", "[", "]", "args", ",", "int", "i", ")", "throws", "BadCommandLineException", "{", "initLoggerIfNecessary", "(", "opts", ")", ";", "int", "recognized", "=", "0", ";", ...
Parse and apply plugin configuration options. @return number of consumed argument options
[ "Parse", "and", "apply", "plugin", "configuration", "options", "." ]
train
https://github.com/dmak/jaxb-xew-plugin/blob/d564d6bf8e50c46b056cdb4b46d1d4bee4adfbe3/src/main/java/com/sun/tools/xjc/addon/xew/config/AbstractConfigurablePlugin.java#L150-L174
Stratio/deep-spark
deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java
UtilAerospike.getAerospikeRecordFromCell
public static Pair<Object, AerospikeRecord> getAerospikeRecordFromCell(Cells cells) throws IllegalAccessException, InstantiationException, InvocationTargetException { Map<String, Object> bins = new HashMap<>(); Object key = null; for (Cell cell : cells.getCells()) { if(key == null) { if(cell.isKey()) { key = cell.getValue(); } } else { if(cell.isKey()) { throw new InvocationTargetException(new Exception("Aerospike records must have only one key")); } } bins.put(cell.getCellName(), cell.getValue()); } if(key == null) { throw new InvocationTargetException(new Exception("Aerospike records must have one primary key")); } // Expiration time = 0, defaults to namespace configuration ("default-ttl") Record record = new Record(bins, 0, 0); return Pair.create(key, new AerospikeRecord(record)); }
java
public static Pair<Object, AerospikeRecord> getAerospikeRecordFromCell(Cells cells) throws IllegalAccessException, InstantiationException, InvocationTargetException { Map<String, Object> bins = new HashMap<>(); Object key = null; for (Cell cell : cells.getCells()) { if(key == null) { if(cell.isKey()) { key = cell.getValue(); } } else { if(cell.isKey()) { throw new InvocationTargetException(new Exception("Aerospike records must have only one key")); } } bins.put(cell.getCellName(), cell.getValue()); } if(key == null) { throw new InvocationTargetException(new Exception("Aerospike records must have one primary key")); } // Expiration time = 0, defaults to namespace configuration ("default-ttl") Record record = new Record(bins, 0, 0); return Pair.create(key, new AerospikeRecord(record)); }
[ "public", "static", "Pair", "<", "Object", ",", "AerospikeRecord", ">", "getAerospikeRecordFromCell", "(", "Cells", "cells", ")", "throws", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTargetException", "{", "Map", "<", "String", ",", "Obje...
Converts from and entity class with deep's anotations to AerospikeRecord. @param cells @return @throws IllegalAccessException @throws InstantiationException @throws InvocationTargetException
[ "Converts", "from", "and", "entity", "class", "with", "deep", "s", "anotations", "to", "AerospikeRecord", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java#L242-L264
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/task/TaskBaseMetric.java
TaskBaseMetric.updateTime
public void updateTime(String streamId, String name, long start, long end, int count, boolean mergeTopology) { if (start > 0 && count > 0) { AsmMetric existingMetric = findMetric(streamId, name, MetricType.HISTOGRAM, mergeTopology); if (existingMetric instanceof AsmHistogram) { AsmHistogram histogram = (AsmHistogram) existingMetric; if (histogram.okToUpdate(end)) { long elapsed = ((end - start) * TimeUtils.US_PER_MS) / count; if (elapsed >= 0) { histogram.update(elapsed); histogram.setLastUpdateTime(end); } } } } }
java
public void updateTime(String streamId, String name, long start, long end, int count, boolean mergeTopology) { if (start > 0 && count > 0) { AsmMetric existingMetric = findMetric(streamId, name, MetricType.HISTOGRAM, mergeTopology); if (existingMetric instanceof AsmHistogram) { AsmHistogram histogram = (AsmHistogram) existingMetric; if (histogram.okToUpdate(end)) { long elapsed = ((end - start) * TimeUtils.US_PER_MS) / count; if (elapsed >= 0) { histogram.update(elapsed); histogram.setLastUpdateTime(end); } } } } }
[ "public", "void", "updateTime", "(", "String", "streamId", ",", "String", "name", ",", "long", "start", ",", "long", "end", ",", "int", "count", ",", "boolean", "mergeTopology", ")", "{", "if", "(", "start", ">", "0", "&&", "count", ">", "0", ")", "{...
almost the same implementation of above update, but improves performance for histograms
[ "almost", "the", "same", "implementation", "of", "above", "update", "but", "improves", "performance", "for", "histograms" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/task/TaskBaseMetric.java#L87-L102
groupon/monsoon
collectors/jmx/src/main/java/com/groupon/lex/metrics/jmx/MetricListener.java
MetricListener.onNewMbean
private synchronized void onNewMbean(ObjectName obj) { if (detected_groups_.keySet().contains(obj)) { LOG.log(Level.WARNING, "skipping registration of {0}: already present", obj); return; } MBeanGroup instance = new MBeanGroup(obj, resolvedMap); detected_groups_.put(obj, instance); LOG.log(Level.FINE, "registered metrics for {0}: {1}", new Object[]{obj, instance}); }
java
private synchronized void onNewMbean(ObjectName obj) { if (detected_groups_.keySet().contains(obj)) { LOG.log(Level.WARNING, "skipping registration of {0}: already present", obj); return; } MBeanGroup instance = new MBeanGroup(obj, resolvedMap); detected_groups_.put(obj, instance); LOG.log(Level.FINE, "registered metrics for {0}: {1}", new Object[]{obj, instance}); }
[ "private", "synchronized", "void", "onNewMbean", "(", "ObjectName", "obj", ")", "{", "if", "(", "detected_groups_", ".", "keySet", "(", ")", ".", "contains", "(", "obj", ")", ")", "{", "LOG", ".", "log", "(", "Level", ".", "WARNING", ",", "\"skipping reg...
Respond to MBeans being added. @param obj The name of the MBean being added.
[ "Respond", "to", "MBeans", "being", "added", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/collectors/jmx/src/main/java/com/groupon/lex/metrics/jmx/MetricListener.java#L141-L150
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.responseToToken
protected Token responseToToken(Map<String, String> response) { return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET)); }
java
protected Token responseToToken(Map<String, String> response) { return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET)); }
[ "protected", "Token", "responseToToken", "(", "Map", "<", "String", ",", "String", ">", "response", ")", "{", "return", "new", "Token", "(", "response", ".", "get", "(", "OAUTH_TOKEN", ")", ",", "response", ".", "get", "(", "OAUTH_TOKEN_SECRET", ")", ")", ...
Parses a service response and creates a token @param response the response @return the token
[ "Parses", "a", "service", "response", "and", "creates", "a", "token" ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L147-L149
apereo/cas
core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java
WebUtils.putServiceIntoFlowScope
public static void putServiceIntoFlowScope(final RequestContext context, final Service service) { context.getFlowScope().put(PARAMETER_SERVICE, service); }
java
public static void putServiceIntoFlowScope(final RequestContext context, final Service service) { context.getFlowScope().put(PARAMETER_SERVICE, service); }
[ "public", "static", "void", "putServiceIntoFlowScope", "(", "final", "RequestContext", "context", ",", "final", "Service", "service", ")", "{", "context", ".", "getFlowScope", "(", ")", ".", "put", "(", "PARAMETER_SERVICE", ",", "service", ")", ";", "}" ]
Put service into flowscope. @param context the context @param service the service
[ "Put", "service", "into", "flowscope", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java#L299-L301
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/EventHelper.java
EventHelper.onOpenDocument
@Override public final void onOpenDocument(PdfWriter writer, Document document) { super.onOpenDocument(writer, document); template = writer.getDirectContent().createTemplate(document.getPageSize().getWidth(), document.getPageSize().getHeight()); if (!getSettings().containsKey(PAGEFOOTERSTYLEKEY)) { getSettings().put(PAGEFOOTERSTYLEKEY, PAGEFOOTERSTYLE); } if (!getSettings().containsKey(PAGEFOOTERTABLEKEY)) { float tot = ItextHelper.ptsToMm(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()); getSettings().put(PAGEFOOTERTABLEKEY, new StringBuilder("Table(columns=3,widths=") .append(Math.round(tot * getSettings().getFloatProperty(0.85f, "footerleftwidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.14f, "footermiddlewidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.01f, "footerrightwidthpercentage"))).append(')').toString() ); } }
java
@Override public final void onOpenDocument(PdfWriter writer, Document document) { super.onOpenDocument(writer, document); template = writer.getDirectContent().createTemplate(document.getPageSize().getWidth(), document.getPageSize().getHeight()); if (!getSettings().containsKey(PAGEFOOTERSTYLEKEY)) { getSettings().put(PAGEFOOTERSTYLEKEY, PAGEFOOTERSTYLE); } if (!getSettings().containsKey(PAGEFOOTERTABLEKEY)) { float tot = ItextHelper.ptsToMm(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()); getSettings().put(PAGEFOOTERTABLEKEY, new StringBuilder("Table(columns=3,widths=") .append(Math.round(tot * getSettings().getFloatProperty(0.85f, "footerleftwidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.14f, "footermiddlewidthpercentage"))).append('|') .append(Math.round(tot * getSettings().getFloatProperty(0.01f, "footerrightwidthpercentage"))).append(')').toString() ); } }
[ "@", "Override", "public", "final", "void", "onOpenDocument", "(", "PdfWriter", "writer", ",", "Document", "document", ")", "{", "super", ".", "onOpenDocument", "(", "writer", ",", "document", ")", ";", "template", "=", "writer", ".", "getDirectContent", "(", ...
prepares template for printing header and footer @param writer @param document
[ "prepares", "template", "for", "printing", "header", "and", "footer" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/EventHelper.java#L130-L145
ehcache/ehcache3
impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java
CacheEventListenerConfigurationBuilder.newEventListenerConfiguration
public static CacheEventListenerConfigurationBuilder newEventListenerConfiguration( Class<? extends CacheEventListener<?, ?>> listenerClass, EventType eventType, EventType... eventTypes){ return new CacheEventListenerConfigurationBuilder(EnumSet.of(eventType, eventTypes), listenerClass); }
java
public static CacheEventListenerConfigurationBuilder newEventListenerConfiguration( Class<? extends CacheEventListener<?, ?>> listenerClass, EventType eventType, EventType... eventTypes){ return new CacheEventListenerConfigurationBuilder(EnumSet.of(eventType, eventTypes), listenerClass); }
[ "public", "static", "CacheEventListenerConfigurationBuilder", "newEventListenerConfiguration", "(", "Class", "<", "?", "extends", "CacheEventListener", "<", "?", ",", "?", ">", ">", "listenerClass", ",", "EventType", "eventType", ",", "EventType", "...", "eventTypes", ...
Creates a new builder instance using the given {@link CacheEventListener} subclass and the {@link EventType}s it will listen to. <p> <ul> <li>{@link EventOrdering} defaults to {@link EventOrdering#UNORDERED}</li> <li>{@link EventFiring} defaults to {@link EventFiring#ASYNCHRONOUS}</li> </ul> @param listenerClass the {@code CacheEventListener} subclass @param eventType the mandatory event type to listen to @param eventTypes optional additional event types to listen to @return the new builder instance
[ "Creates", "a", "new", "builder", "instance", "using", "the", "given", "{", "@link", "CacheEventListener", "}", "subclass", "and", "the", "{", "@link", "EventType", "}", "s", "it", "will", "listen", "to", ".", "<p", ">", "<ul", ">", "<li", ">", "{", "@...
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java#L81-L84
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/parsers/JSONPathParser.java
JSONPathParser.parseToMap
@Override public Map<String, Object> parseToMap(String input) { try { JsonNode document = mapper.readValue(input, JsonNode.class); return flattener.flatten(document); } catch (Exception e) { throw new ParseException(e, "Unable to parse row [%s]", input); } }
java
@Override public Map<String, Object> parseToMap(String input) { try { JsonNode document = mapper.readValue(input, JsonNode.class); return flattener.flatten(document); } catch (Exception e) { throw new ParseException(e, "Unable to parse row [%s]", input); } }
[ "@", "Override", "public", "Map", "<", "String", ",", "Object", ">", "parseToMap", "(", "String", "input", ")", "{", "try", "{", "JsonNode", "document", "=", "mapper", ".", "readValue", "(", "input", ",", "JsonNode", ".", "class", ")", ";", "return", "...
@param input JSON string. The root must be a JSON object, not an array. e.g., {"valid": "true"} and {"valid":[1,2,3]} are supported but [{"invalid": "true"}] and [1,2,3] are not. @return A map of field names and values
[ "@param", "input", "JSON", "string", ".", "The", "root", "must", "be", "a", "JSON", "object", "not", "an", "array", ".", "e", ".", "g", ".", "{", "valid", ":", "true", "}", "and", "{", "valid", ":", "[", "1", "2", "3", "]", "}", "are", "support...
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/parsers/JSONPathParser.java#L66-L76
OpenLiberty/open-liberty
dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/ELHelper.java
ELHelper.processLdapSearchScope
protected LdapSearchScope processLdapSearchScope(String name, String expression, LdapSearchScope value, boolean immediateOnly) { LdapSearchScope result; boolean immediate = false; /* * The expression language value takes precedence over the direct setting. */ if (expression.isEmpty()) { /* * Direct setting. */ result = value; } else { /* * Evaluate the EL expression to get the value. */ Object obj = evaluateElExpression(expression); if (obj instanceof LdapSearchScope) { result = (LdapSearchScope) obj; immediate = isImmediateExpression(expression); } else if (obj instanceof String) { result = LdapSearchScope.valueOf(((String) obj).toUpperCase()); immediate = isImmediateExpression(expression); } else { throw new IllegalArgumentException("Expected '" + name + "' to evaluate to an LdapSearchScope type."); } } return (immediateOnly && !immediate) ? null : result; }
java
protected LdapSearchScope processLdapSearchScope(String name, String expression, LdapSearchScope value, boolean immediateOnly) { LdapSearchScope result; boolean immediate = false; /* * The expression language value takes precedence over the direct setting. */ if (expression.isEmpty()) { /* * Direct setting. */ result = value; } else { /* * Evaluate the EL expression to get the value. */ Object obj = evaluateElExpression(expression); if (obj instanceof LdapSearchScope) { result = (LdapSearchScope) obj; immediate = isImmediateExpression(expression); } else if (obj instanceof String) { result = LdapSearchScope.valueOf(((String) obj).toUpperCase()); immediate = isImmediateExpression(expression); } else { throw new IllegalArgumentException("Expected '" + name + "' to evaluate to an LdapSearchScope type."); } } return (immediateOnly && !immediate) ? null : result; }
[ "protected", "LdapSearchScope", "processLdapSearchScope", "(", "String", "name", ",", "String", "expression", ",", "LdapSearchScope", "value", ",", "boolean", "immediateOnly", ")", "{", "LdapSearchScope", "result", ";", "boolean", "immediate", "=", "false", ";", "/*...
This method will process a configuration value for LdapSearchScope setting in {@link LdapIdentityStoreDefinition}. It will first check to see if there is an EL expression. It there is, it will return the evaluated expression; otherwise, it will return the non-EL value. @param name The name of the property. Used for error messages. @param expression The EL expression returned from from the identity store definition. @param value The non-EL value. @param immediateOnly Return null if the value is a deferred EL expression. @return Either the evaluated EL expression or the non-EL value.
[ "This", "method", "will", "process", "a", "configuration", "value", "for", "LdapSearchScope", "setting", "in", "{", "@link", "LdapIdentityStoreDefinition", "}", ".", "It", "will", "first", "check", "to", "see", "if", "there", "is", "an", "EL", "expression", "....
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/ELHelper.java#L188-L217
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java
KeyChainGroup.getActiveKeyChain
public final DeterministicKeyChain getActiveKeyChain(Script.ScriptType outputScriptType, long keyRotationTimeSecs) { checkState(isSupportsDeterministicChains(), "doesn't support deterministic chains"); for (DeterministicKeyChain chain : ImmutableList.copyOf(chains).reverse()) if (chain.getOutputScriptType() == outputScriptType && chain.getEarliestKeyCreationTime() >= keyRotationTimeSecs) return chain; return null; }
java
public final DeterministicKeyChain getActiveKeyChain(Script.ScriptType outputScriptType, long keyRotationTimeSecs) { checkState(isSupportsDeterministicChains(), "doesn't support deterministic chains"); for (DeterministicKeyChain chain : ImmutableList.copyOf(chains).reverse()) if (chain.getOutputScriptType() == outputScriptType && chain.getEarliestKeyCreationTime() >= keyRotationTimeSecs) return chain; return null; }
[ "public", "final", "DeterministicKeyChain", "getActiveKeyChain", "(", "Script", ".", "ScriptType", "outputScriptType", ",", "long", "keyRotationTimeSecs", ")", "{", "checkState", "(", "isSupportsDeterministicChains", "(", ")", ",", "\"doesn't support deterministic chains\"", ...
Returns the key chain that's used for generation of fresh/current keys of the given type. If it's not the default type and no active chain for this type exists, {@code null} is returned. No upgrade or downgrade is tried.
[ "Returns", "the", "key", "chain", "that", "s", "used", "for", "generation", "of", "fresh", "/", "current", "keys", "of", "the", "given", "type", ".", "If", "it", "s", "not", "the", "default", "type", "and", "no", "active", "chain", "for", "this", "type...
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L411-L418
codeprimate-software/cp-elements
src/main/java/org/cp/elements/util/zip/ZipUtils.java
ZipUtils.newZipEntry
protected static ZipEntry newZipEntry(File zipDirectory, File file) { Assert.notNull(file, "File is required"); ZipEntry zipEntry = new ZipEntry(resolveZipEntryName(zipDirectory, file)); zipEntry.setSize(file.getTotalSpace()); zipEntry.setTime(file.lastModified()); return zipEntry; }
java
protected static ZipEntry newZipEntry(File zipDirectory, File file) { Assert.notNull(file, "File is required"); ZipEntry zipEntry = new ZipEntry(resolveZipEntryName(zipDirectory, file)); zipEntry.setSize(file.getTotalSpace()); zipEntry.setTime(file.lastModified()); return zipEntry; }
[ "protected", "static", "ZipEntry", "newZipEntry", "(", "File", "zipDirectory", ",", "File", "file", ")", "{", "Assert", ".", "notNull", "(", "file", ",", "\"File is required\"", ")", ";", "ZipEntry", "zipEntry", "=", "new", "ZipEntry", "(", "resolveZipEntryName"...
Constructs a new {@link ZipEntry} from the given {@link File}. @param zipDirectory {@link File} referring to the directory being zipped. @param file {@link File} used to construct the new {@link ZipEntry}. @return a new {@link ZipEntry} constructed from the given {@link File}. @throws IllegalArgumentException if {@link File} is {@literal null}. @see #resolveZipEntryName(File, File) @see java.util.zip.ZipEntry @see java.io.File
[ "Constructs", "a", "new", "{", "@link", "ZipEntry", "}", "from", "the", "given", "{", "@link", "File", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/zip/ZipUtils.java#L63-L73
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java
DirectoryFlowLoader.loadProjectFlow
@Override public ValidationReport loadProjectFlow(final Project project, final File projectDir) { this.propsList = new ArrayList<>(); this.flowPropsList = new ArrayList<>(); this.jobPropsMap = new HashMap<>(); this.nodeMap = new HashMap<>(); this.duplicateJobs = new HashSet<>(); this.nodeDependencies = new HashMap<>(); this.rootNodes = new HashSet<>(); this.flowDependencies = new HashMap<>(); // Load all the props files and create the Node objects loadProjectFromDir(projectDir.getPath(), projectDir, null); // Create edges and find missing dependencies resolveDependencies(); // Create the flows. buildFlowsFromDependencies(); // Resolve embedded flows resolveEmbeddedFlows(); FlowLoaderUtils.checkJobProperties(project.getId(), this.props, this.jobPropsMap, this.errors); return FlowLoaderUtils.generateFlowLoaderReport(this.errors); }
java
@Override public ValidationReport loadProjectFlow(final Project project, final File projectDir) { this.propsList = new ArrayList<>(); this.flowPropsList = new ArrayList<>(); this.jobPropsMap = new HashMap<>(); this.nodeMap = new HashMap<>(); this.duplicateJobs = new HashSet<>(); this.nodeDependencies = new HashMap<>(); this.rootNodes = new HashSet<>(); this.flowDependencies = new HashMap<>(); // Load all the props files and create the Node objects loadProjectFromDir(projectDir.getPath(), projectDir, null); // Create edges and find missing dependencies resolveDependencies(); // Create the flows. buildFlowsFromDependencies(); // Resolve embedded flows resolveEmbeddedFlows(); FlowLoaderUtils.checkJobProperties(project.getId(), this.props, this.jobPropsMap, this.errors); return FlowLoaderUtils.generateFlowLoaderReport(this.errors); }
[ "@", "Override", "public", "ValidationReport", "loadProjectFlow", "(", "final", "Project", "project", ",", "final", "File", "projectDir", ")", "{", "this", ".", "propsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "this", ".", "flowPropsList", "=", "ne...
Loads all project flows from the directory. @param project The project. @param projectDir The directory to load flows from. @return the validation report.
[ "Loads", "all", "project", "flows", "from", "the", "directory", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/DirectoryFlowLoader.java#L119-L146
ops4j/org.ops4j.pax.swissbox
pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ServiceLookup.java
ServiceLookup.getService
public static <T> T getService( BundleContext bc, Class<T> type, Map<String, String> props ) { return getService( bc, type, DEFAULT_TIMEOUT, props ); }
java
public static <T> T getService( BundleContext bc, Class<T> type, Map<String, String> props ) { return getService( bc, type, DEFAULT_TIMEOUT, props ); }
[ "public", "static", "<", "T", ">", "T", "getService", "(", "BundleContext", "bc", ",", "Class", "<", "T", ">", "type", ",", "Map", "<", "String", ",", "String", ">", "props", ")", "{", "return", "getService", "(", "bc", ",", "type", ",", "DEFAULT_TIM...
Returns a service matching the given criteria. @param <T> class implemented or extended by the service @param bc bundle context for accessing the OSGi registry @param type class implemented or extended by the service @param props properties to be matched by the service @return matching service (not null) @throws ServiceLookupException when no matching service has been found after the timeout
[ "Returns", "a", "service", "matching", "the", "given", "criteria", "." ]
train
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ServiceLookup.java#L85-L88
apereo/cas
core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/handler/support/AbstractPreAndPostProcessingAuthenticationHandler.java
AbstractPreAndPostProcessingAuthenticationHandler.createHandlerResult
protected AuthenticationHandlerExecutionResult createHandlerResult(final @NonNull Credential credential, final @NonNull Principal principal, final @NonNull List<MessageDescriptor> warnings) { return new DefaultAuthenticationHandlerExecutionResult(this, new BasicCredentialMetaData(credential), principal, warnings); }
java
protected AuthenticationHandlerExecutionResult createHandlerResult(final @NonNull Credential credential, final @NonNull Principal principal, final @NonNull List<MessageDescriptor> warnings) { return new DefaultAuthenticationHandlerExecutionResult(this, new BasicCredentialMetaData(credential), principal, warnings); }
[ "protected", "AuthenticationHandlerExecutionResult", "createHandlerResult", "(", "final", "@", "NonNull", "Credential", "credential", ",", "final", "@", "NonNull", "Principal", "principal", ",", "final", "@", "NonNull", "List", "<", "MessageDescriptor", ">", "warnings",...
Helper method to construct a handler result on successful authentication events. @param credential the credential on which the authentication was successfully performed. Note that this credential instance may be different from what was originally provided as transformation of the username may have occurred, if one is in fact defined. @param principal the resolved principal @param warnings the warnings @return the constructed handler result
[ "Helper", "method", "to", "construct", "a", "handler", "result", "on", "successful", "authentication", "events", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/handler/support/AbstractPreAndPostProcessingAuthenticationHandler.java#L68-L72
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/BarcodeDatamatrix.java
BarcodeDatamatrix.createAwtImage
public java.awt.Image createAwtImage(Color foreground, Color background) { if (image == null) return null; int f = foreground.getRGB(); int g = background.getRGB(); Canvas canvas = new Canvas(); int w = width + 2 * ws; int h = height + 2 * ws; int pix[] = new int[w * h]; int stride = (w + 7) / 8; int ptr = 0; for (int k = 0; k < h; ++k) { int p = k * stride; for (int j = 0; j < w; ++j) { int b = image[p + (j / 8)] & 0xff; b <<= j % 8; pix[ptr++] = (b & 0x80) == 0 ? g : f; } } java.awt.Image img = canvas.createImage(new MemoryImageSource(w, h, pix, 0, w)); return img; }
java
public java.awt.Image createAwtImage(Color foreground, Color background) { if (image == null) return null; int f = foreground.getRGB(); int g = background.getRGB(); Canvas canvas = new Canvas(); int w = width + 2 * ws; int h = height + 2 * ws; int pix[] = new int[w * h]; int stride = (w + 7) / 8; int ptr = 0; for (int k = 0; k < h; ++k) { int p = k * stride; for (int j = 0; j < w; ++j) { int b = image[p + (j / 8)] & 0xff; b <<= j % 8; pix[ptr++] = (b & 0x80) == 0 ? g : f; } } java.awt.Image img = canvas.createImage(new MemoryImageSource(w, h, pix, 0, w)); return img; }
[ "public", "java", ".", "awt", ".", "Image", "createAwtImage", "(", "Color", "foreground", ",", "Color", "background", ")", "{", "if", "(", "image", "==", "null", ")", "return", "null", ";", "int", "f", "=", "foreground", ".", "getRGB", "(", ")", ";", ...
Creates a <CODE>java.awt.Image</CODE>. A successful call to the method <CODE>generate()</CODE> before calling this method is required. @param foreground the color of the bars @param background the color of the background @return the image
[ "Creates", "a", "<CODE", ">", "java", ".", "awt", ".", "Image<", "/", "CODE", ">", ".", "A", "successful", "call", "to", "the", "method", "<CODE", ">", "generate", "()", "<", "/", "CODE", ">", "before", "calling", "this", "method", "is", "required", ...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/BarcodeDatamatrix.java#L774-L796
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setWanReplicationConfigs
public Config setWanReplicationConfigs(Map<String, WanReplicationConfig> wanReplicationConfigs) { this.wanReplicationConfigs.clear(); this.wanReplicationConfigs.putAll(wanReplicationConfigs); for (final Entry<String, WanReplicationConfig> entry : this.wanReplicationConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setWanReplicationConfigs(Map<String, WanReplicationConfig> wanReplicationConfigs) { this.wanReplicationConfigs.clear(); this.wanReplicationConfigs.putAll(wanReplicationConfigs); for (final Entry<String, WanReplicationConfig> entry : this.wanReplicationConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setWanReplicationConfigs", "(", "Map", "<", "String", ",", "WanReplicationConfig", ">", "wanReplicationConfigs", ")", "{", "this", ".", "wanReplicationConfigs", ".", "clear", "(", ")", ";", "this", ".", "wanReplicationConfigs", ".", "putAll", ...
Sets the map of WAN replication configurations, mapped by config name. @param wanReplicationConfigs the WAN replication configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "WAN", "replication", "configurations", "mapped", "by", "config", "name", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L2423-L2430
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.getExtensions
public VirtualMachineExtensionsListResultInner getExtensions(String resourceGroupName, String vmName, String expand) { return getExtensionsWithServiceResponseAsync(resourceGroupName, vmName, expand).toBlocking().single().body(); }
java
public VirtualMachineExtensionsListResultInner getExtensions(String resourceGroupName, String vmName, String expand) { return getExtensionsWithServiceResponseAsync(resourceGroupName, vmName, expand).toBlocking().single().body(); }
[ "public", "VirtualMachineExtensionsListResultInner", "getExtensions", "(", "String", "resourceGroupName", ",", "String", "vmName", ",", "String", "expand", ")", "{", "return", "getExtensionsWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmName", ",", "expand", ...
The operation to get all extensions of a Virtual Machine. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine containing the extension. @param expand The expand expression to apply on the 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 VirtualMachineExtensionsListResultInner object if successful.
[ "The", "operation", "to", "get", "all", "extensions", "of", "a", "Virtual", "Machine", "." ]
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#L288-L290
jenkinsci/ssh-slaves-plugin
src/main/java/com/trilead/ssh2/jenkins/SFTPClient.java
SFTPClient.mkdirs
public void mkdirs(String path, int posixPermission) throws IOException { SFTPv3FileAttributes atts = _stat(path); if (atts!=null && atts.isDirectory()) return; int idx = path.lastIndexOf('/'); if (idx>0) mkdirs(path.substring(0,idx), posixPermission); try { mkdir(path, posixPermission); } catch (IOException e) { throw new IOException("Failed to mkdir "+path,e); } }
java
public void mkdirs(String path, int posixPermission) throws IOException { SFTPv3FileAttributes atts = _stat(path); if (atts!=null && atts.isDirectory()) return; int idx = path.lastIndexOf('/'); if (idx>0) mkdirs(path.substring(0,idx), posixPermission); try { mkdir(path, posixPermission); } catch (IOException e) { throw new IOException("Failed to mkdir "+path,e); } }
[ "public", "void", "mkdirs", "(", "String", "path", ",", "int", "posixPermission", ")", "throws", "IOException", "{", "SFTPv3FileAttributes", "atts", "=", "_stat", "(", "path", ")", ";", "if", "(", "atts", "!=", "null", "&&", "atts", ".", "isDirectory", "("...
Makes sure that the directory exists, by creating it if necessary. @param path directory path. @param posixPermission POSIX permissions. @throws IOException if it is not possible to access to the directory.
[ "Makes", "sure", "that", "the", "directory", "exists", "by", "creating", "it", "if", "necessary", "." ]
train
https://github.com/jenkinsci/ssh-slaves-plugin/blob/95f528730fc1e01b25983459927b7516ead3ee00/src/main/java/com/trilead/ssh2/jenkins/SFTPClient.java#L80-L94
steveash/bushwhacker
bushwhacker/src/main/java/com/github/steveash/bushwhacker/Bushwhacker.java
Bushwhacker.tryForRules
public static Bushwhacker tryForRules(String rulesFileNameOnClasspath) { try { return forRules(rulesFileNameOnClasspath); } catch (IOException e) { return logAndMakeNoOp(rulesFileNameOnClasspath, e); } }
java
public static Bushwhacker tryForRules(String rulesFileNameOnClasspath) { try { return forRules(rulesFileNameOnClasspath); } catch (IOException e) { return logAndMakeNoOp(rulesFileNameOnClasspath, e); } }
[ "public", "static", "Bushwhacker", "tryForRules", "(", "String", "rulesFileNameOnClasspath", ")", "{", "try", "{", "return", "forRules", "(", "rulesFileNameOnClasspath", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "logAndMakeNoOp", "(", ...
Convenient wrapper of #forRules that swallows any exception (logging it to warn first) then returns a NoOp implementation of Bushwhacker. This is convenient when you are using Bushwhacker in its typical usage scenario and want it to silently fail @param rulesFileNameOnClasspath @return
[ "Convenient", "wrapper", "of", "#forRules", "that", "swallows", "any", "exception", "(", "logging", "it", "to", "warn", "first", ")", "then", "returns", "a", "NoOp", "implementation", "of", "Bushwhacker", ".", "This", "is", "convenient", "when", "you", "are", ...
train
https://github.com/steveash/bushwhacker/blob/93958dea1f4e1d881e863970fd12b857278813c1/bushwhacker/src/main/java/com/github/steveash/bushwhacker/Bushwhacker.java#L71-L77
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqlceiling
public static void sqlceiling(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "ceil(", "ceiling", parsedArgs); }
java
public static void sqlceiling(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "ceil(", "ceiling", parsedArgs); }
[ "public", "static", "void", "sqlceiling", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"ceil(\"", ",", "\"ceiling\"", ",", "...
ceiling to ceil translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "ceiling", "to", "ceil", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L87-L89
aws/aws-sdk-java
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/ArrayPropertiesDetail.java
ArrayPropertiesDetail.withStatusSummary
public ArrayPropertiesDetail withStatusSummary(java.util.Map<String, Integer> statusSummary) { setStatusSummary(statusSummary); return this; }
java
public ArrayPropertiesDetail withStatusSummary(java.util.Map<String, Integer> statusSummary) { setStatusSummary(statusSummary); return this; }
[ "public", "ArrayPropertiesDetail", "withStatusSummary", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "Integer", ">", "statusSummary", ")", "{", "setStatusSummary", "(", "statusSummary", ")", ";", "return", "this", ";", "}" ]
<p> A summary of the number of array job children in each available job status. This parameter is returned for parent array jobs. </p> @param statusSummary A summary of the number of array job children in each available job status. This parameter is returned for parent array jobs. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "summary", "of", "the", "number", "of", "array", "job", "children", "in", "each", "available", "job", "status", ".", "This", "parameter", "is", "returned", "for", "parent", "array", "jobs", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/ArrayPropertiesDetail.java#L93-L96
WinRoad-NET/htmldoclet4jdk8
src/main/java/net/winroad/htmldoclet4jdk8/HtmlDoclet.java
HtmlDoclet.generateWRAPIDetailFiles
protected void generateWRAPIDetailFiles(RootDoc root, WRDoc wrDoc) { List<String> tagList = new ArrayList<String>(wrDoc.getWRTags()); for (String tag : tagList) { List<OpenAPI> openAPIList = wrDoc.getTaggedOpenAPIs().get(tag); Set<String> filesGenerated = new HashSet<String>(); for (OpenAPI openAPI : openAPIList) { Map<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("openAPI", openAPI); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); String oasJSONStr = null; try { oasJSONStr = mapper.writeValueAsString(this.convertToOAS(openAPI, this.configurationEx.branchname)); } catch (JsonProcessingException e) { logger.error(e); } hashMap.put("OASV3", oasJSONStr); String tagsStr = openAPI.getTags().toString(); // trim '[' and ']' hashMap.put("tags", tagsStr.substring(1, tagsStr.length() - 1)); hashMap.put("generatedTime", wrDoc.getDocGeneratedTime()); hashMap.put( "branchName", this.configurationEx.branchname); hashMap.put( "systemName", this.configurationEx.systemname); if (StringUtils.isWhitespace(this.configurationEx.buildid) || this.configurationEx.buildid.equalsIgnoreCase("time")) { hashMap.put("buildID", wrDoc.getDocGeneratedTime()); } else { hashMap.put( "buildID", this.configurationEx.buildid); } this.logger.info("buildid:" + hashMap.get("buildID")); String filename = generateWRAPIFileName(openAPI.getRequestMapping()); hashMap.put("filePath", filename); if (!filesGenerated.contains(filename)) { this.configurationEx .getWriterFactory() .getFreemarkerWriter() .generateHtmlFile("wrAPIDetail.ftl", hashMap, this.configurationEx.destDirName, filename); filesGenerated.add(filename); } } } }
java
protected void generateWRAPIDetailFiles(RootDoc root, WRDoc wrDoc) { List<String> tagList = new ArrayList<String>(wrDoc.getWRTags()); for (String tag : tagList) { List<OpenAPI> openAPIList = wrDoc.getTaggedOpenAPIs().get(tag); Set<String> filesGenerated = new HashSet<String>(); for (OpenAPI openAPI : openAPIList) { Map<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("openAPI", openAPI); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); String oasJSONStr = null; try { oasJSONStr = mapper.writeValueAsString(this.convertToOAS(openAPI, this.configurationEx.branchname)); } catch (JsonProcessingException e) { logger.error(e); } hashMap.put("OASV3", oasJSONStr); String tagsStr = openAPI.getTags().toString(); // trim '[' and ']' hashMap.put("tags", tagsStr.substring(1, tagsStr.length() - 1)); hashMap.put("generatedTime", wrDoc.getDocGeneratedTime()); hashMap.put( "branchName", this.configurationEx.branchname); hashMap.put( "systemName", this.configurationEx.systemname); if (StringUtils.isWhitespace(this.configurationEx.buildid) || this.configurationEx.buildid.equalsIgnoreCase("time")) { hashMap.put("buildID", wrDoc.getDocGeneratedTime()); } else { hashMap.put( "buildID", this.configurationEx.buildid); } this.logger.info("buildid:" + hashMap.get("buildID")); String filename = generateWRAPIFileName(openAPI.getRequestMapping()); hashMap.put("filePath", filename); if (!filesGenerated.contains(filename)) { this.configurationEx .getWriterFactory() .getFreemarkerWriter() .generateHtmlFile("wrAPIDetail.ftl", hashMap, this.configurationEx.destDirName, filename); filesGenerated.add(filename); } } } }
[ "protected", "void", "generateWRAPIDetailFiles", "(", "RootDoc", "root", ",", "WRDoc", "wrDoc", ")", "{", "List", "<", "String", ">", "tagList", "=", "new", "ArrayList", "<", "String", ">", "(", "wrDoc", ".", "getWRTags", "(", ")", ")", ";", "for", "(", ...
Generate the tag documentation. @param root the RootDoc of source to document. @param wrDoc the data structure representing the doc to generate.
[ "Generate", "the", "tag", "documentation", "." ]
train
https://github.com/WinRoad-NET/htmldoclet4jdk8/blob/1e0aa93c12e0228fb0f7a1b4f8e89d9a17cbe5c7/src/main/java/net/winroad/htmldoclet4jdk8/HtmlDoclet.java#L234-L282
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/parsing/StateParser.java
StateParser.parseLine
public static SubstitutedLine parseLine(String str, ParsingStateCallbackHandler callbackHandler, ParsingState initialState, boolean strict) throws CommandFormatException { return parseLine(str, callbackHandler, initialState, strict, null); }
java
public static SubstitutedLine parseLine(String str, ParsingStateCallbackHandler callbackHandler, ParsingState initialState, boolean strict) throws CommandFormatException { return parseLine(str, callbackHandler, initialState, strict, null); }
[ "public", "static", "SubstitutedLine", "parseLine", "(", "String", "str", ",", "ParsingStateCallbackHandler", "callbackHandler", ",", "ParsingState", "initialState", ",", "boolean", "strict", ")", "throws", "CommandFormatException", "{", "return", "parseLine", "(", "str...
Returns the string which was actually parsed with all the substitutions performed. NB: No CommandCOntext being provided, variables can't be resolved. variables should be already resolved when calling this parse method.
[ "Returns", "the", "string", "which", "was", "actually", "parsed", "with", "all", "the", "substitutions", "performed", ".", "NB", ":", "No", "CommandCOntext", "being", "provided", "variables", "can", "t", "be", "resolved", ".", "variables", "should", "be", "alr...
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/parsing/StateParser.java#L94-L96
feedzai/pdb
src/main/java/com/feedzai/commons/sql/abstraction/dml/result/ResultColumn.java
ResultColumn.toBlob
public <T> T toBlob() throws DatabaseEngineRuntimeException { if (isNull()) { return null; } InputStream is; if (val instanceof Blob) { try { is = ((Blob) val).getBinaryStream(); } catch (final SQLException e) { throw new DatabaseEngineRuntimeException("Error getting blob input stream", e); } } else if (val instanceof byte[]) { is = new ByteArrayInputStream((byte[]) val); }
java
public <T> T toBlob() throws DatabaseEngineRuntimeException { if (isNull()) { return null; } InputStream is; if (val instanceof Blob) { try { is = ((Blob) val).getBinaryStream(); } catch (final SQLException e) { throw new DatabaseEngineRuntimeException("Error getting blob input stream", e); } } else if (val instanceof byte[]) { is = new ByteArrayInputStream((byte[]) val); }
[ "public", "<", "T", ">", "T", "toBlob", "(", ")", "throws", "DatabaseEngineRuntimeException", "{", "if", "(", "isNull", "(", ")", ")", "{", "return", "null", ";", "}", "InputStream", "is", ";", "if", "(", "val", "instanceof", "Blob", ")", "{", "try", ...
Converts this result (in the form of blob) to the specified object type. @param <T> The type to convert. @return The instance that was in the form of blob. @throws DatabaseEngineRuntimeException If the value is not a blob or if something goes wrong when reading the object.
[ "Converts", "this", "result", "(", "in", "the", "form", "of", "blob", ")", "to", "the", "specified", "object", "type", "." ]
train
https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/dml/result/ResultColumn.java#L180-L194
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.encodedOutputStreamPrintWriter
public static PrintWriter encodedOutputStreamPrintWriter(OutputStream stream, String encoding, boolean autoFlush) throws IOException { // PrintWriter doesn't allow encoding to be null; or to have charset and flush if (encoding == null) { return new PrintWriter(stream, autoFlush); } else { return new PrintWriter(new OutputStreamWriter(stream, encoding), autoFlush); } }
java
public static PrintWriter encodedOutputStreamPrintWriter(OutputStream stream, String encoding, boolean autoFlush) throws IOException { // PrintWriter doesn't allow encoding to be null; or to have charset and flush if (encoding == null) { return new PrintWriter(stream, autoFlush); } else { return new PrintWriter(new OutputStreamWriter(stream, encoding), autoFlush); } }
[ "public", "static", "PrintWriter", "encodedOutputStreamPrintWriter", "(", "OutputStream", "stream", ",", "String", "encoding", ",", "boolean", "autoFlush", ")", "throws", "IOException", "{", "// PrintWriter doesn't allow encoding to be null; or to have charset and flush\r", "if",...
Create a Reader with an explicit encoding around an InputStream. This static method will treat null as meaning to use the platform default, unlike the Java library methods that disallow a null encoding. @param stream An InputStream @param encoding A charset encoding @return A Reader @throws IOException If any IO problem
[ "Create", "a", "Reader", "with", "an", "explicit", "encoding", "around", "an", "InputStream", ".", "This", "static", "method", "will", "treat", "null", "as", "meaning", "to", "use", "the", "platform", "default", "unlike", "the", "Java", "library", "methods", ...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L1358-L1366
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/audit/audit_stats.java
audit_stats.get
public static audit_stats get(nitro_service service, options option) throws Exception{ audit_stats obj = new audit_stats(); audit_stats[] response = (audit_stats[])obj.stat_resources(service,option); return response[0]; }
java
public static audit_stats get(nitro_service service, options option) throws Exception{ audit_stats obj = new audit_stats(); audit_stats[] response = (audit_stats[])obj.stat_resources(service,option); return response[0]; }
[ "public", "static", "audit_stats", "get", "(", "nitro_service", "service", ",", "options", "option", ")", "throws", "Exception", "{", "audit_stats", "obj", "=", "new", "audit_stats", "(", ")", ";", "audit_stats", "[", "]", "response", "=", "(", "audit_stats", ...
Use this API to fetch the statistics of all audit_stats resources that are configured on netscaler.
[ "Use", "this", "API", "to", "fetch", "the", "statistics", "of", "all", "audit_stats", "resources", "that", "are", "configured", "on", "netscaler", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/audit/audit_stats.java#L323-L327
RuedigerMoeller/kontraktor
examples/misc/pub-sub/tcp-based/src/main/java/pubsub/point2point/MediatorActor.java
MediatorActor.askSubscribers
public void askSubscribers( Actor sender, String topic, Object message, Callback cb ) { List<ReceiverActor> subscriber = topic2Subscriber.get(topic); if ( subscriber != null ) { List<IPromise> results = subscriber.stream() .filter(subs -> !subs.equals(sender)) .map(subs -> subs.receiveAsk(topic, message)) .collect(Collectors.toList()); try { all((List) results).await(5000); // is non-blocking } catch (Exception ex) { // timeout goes here Log.Info(this, "timeout in broadcast"); } results.forEach( promise -> cb.pipe(promise.get())); cb.finish(); // important to release callback mapping in remoting ! } }
java
public void askSubscribers( Actor sender, String topic, Object message, Callback cb ) { List<ReceiverActor> subscriber = topic2Subscriber.get(topic); if ( subscriber != null ) { List<IPromise> results = subscriber.stream() .filter(subs -> !subs.equals(sender)) .map(subs -> subs.receiveAsk(topic, message)) .collect(Collectors.toList()); try { all((List) results).await(5000); // is non-blocking } catch (Exception ex) { // timeout goes here Log.Info(this, "timeout in broadcast"); } results.forEach( promise -> cb.pipe(promise.get())); cb.finish(); // important to release callback mapping in remoting ! } }
[ "public", "void", "askSubscribers", "(", "Actor", "sender", ",", "String", "topic", ",", "Object", "message", ",", "Callback", "cb", ")", "{", "List", "<", "ReceiverActor", ">", "subscriber", "=", "topic2Subscriber", ".", "get", "(", "topic", ")", ";", "if...
send a message to all and stream the result of each receiver back to sender @param sender @param topic @param message @param cb
[ "send", "a", "message", "to", "all", "and", "stream", "the", "result", "of", "each", "receiver", "back", "to", "sender" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/examples/misc/pub-sub/tcp-based/src/main/java/pubsub/point2point/MediatorActor.java#L80-L96
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
ToStringBuilder.reflectionToString
@GwtIncompatible("incompatible method") public static String reflectionToString(final Object object, final ToStringStyle style) { return ReflectionToStringBuilder.toString(object, style); }
java
@GwtIncompatible("incompatible method") public static String reflectionToString(final Object object, final ToStringStyle style) { return ReflectionToStringBuilder.toString(object, style); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "String", "reflectionToString", "(", "final", "Object", "object", ",", "final", "ToStringStyle", "style", ")", "{", "return", "ReflectionToStringBuilder", ".", "toString", "(", "object", ...
<p>Uses <code>ReflectionToStringBuilder</code> to generate a <code>toString</code> for the specified object.</p> @param object the Object to be output @param style the style of the <code>toString</code> to create, may be <code>null</code> @return the String result @see ReflectionToStringBuilder#toString(Object,ToStringStyle)
[ "<p", ">", "Uses", "<code", ">", "ReflectionToStringBuilder<", "/", "code", ">", "to", "generate", "a", "<code", ">", "toString<", "/", "code", ">", "for", "the", "specified", "object", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java#L165-L168
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/alias/CmsAliasTableController.java
CmsAliasTableController.editAliasPath
public void editAliasPath(CmsAliasTableRow row, String path) { row.editAliasPath(path); row.setEdited(true); validate(); }
java
public void editAliasPath(CmsAliasTableRow row, String path) { row.editAliasPath(path); row.setEdited(true); validate(); }
[ "public", "void", "editAliasPath", "(", "CmsAliasTableRow", "row", ",", "String", "path", ")", "{", "row", ".", "editAliasPath", "(", "path", ")", ";", "row", ".", "setEdited", "(", "true", ")", ";", "validate", "(", ")", ";", "}" ]
This method is called after the alias path of an alias has been edited.<p> @param row the edited row @param path the new alias path
[ "This", "method", "is", "called", "after", "the", "alias", "path", "of", "an", "alias", "has", "been", "edited", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/alias/CmsAliasTableController.java#L166-L172
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabasesInner.java
DatabasesInner.beginUpgradeDataWarehouseAsync
public Observable<Void> beginUpgradeDataWarehouseAsync(String resourceGroupName, String serverName, String databaseName) { return beginUpgradeDataWarehouseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginUpgradeDataWarehouseAsync(String resourceGroupName, String serverName, String databaseName) { return beginUpgradeDataWarehouseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginUpgradeDataWarehouseAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ")", "{", "return", "beginUpgradeDataWarehouseWithServiceResponseAsync", "(", "resourceGroupName", ","...
Upgrades a data warehouse. @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 to be upgraded. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Upgrades", "a", "data", "warehouse", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabasesInner.java#L254-L261
VoltDB/voltdb
src/frontend/org/voltdb/jni/ExecutionEngineJNI.java
ExecutionEngineJNI.storeLargeTempTableBlock
public boolean storeLargeTempTableBlock(long siteId, long blockCounter, ByteBuffer block) { LargeBlockTask task = LargeBlockTask.getStoreTask(new BlockId(siteId, blockCounter), block); return executeLargeBlockTaskSynchronously(task); }
java
public boolean storeLargeTempTableBlock(long siteId, long blockCounter, ByteBuffer block) { LargeBlockTask task = LargeBlockTask.getStoreTask(new BlockId(siteId, blockCounter), block); return executeLargeBlockTaskSynchronously(task); }
[ "public", "boolean", "storeLargeTempTableBlock", "(", "long", "siteId", ",", "long", "blockCounter", ",", "ByteBuffer", "block", ")", "{", "LargeBlockTask", "task", "=", "LargeBlockTask", ".", "getStoreTask", "(", "new", "BlockId", "(", "siteId", ",", "blockCounte...
Store a large temp table block to disk. @param siteId The site id of the block to store to disk @param blockCounter The serial number of the block to store to disk @param block A directly-allocated ByteBuffer of the block @return true if operation succeeded, false otherwise
[ "Store", "a", "large", "temp", "table", "block", "to", "disk", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jni/ExecutionEngineJNI.java#L878-L881
looly/hutool
hutool-core/src/main/java/cn/hutool/core/text/csv/CsvUtil.java
CsvUtil.getWriter
public static CsvWriter getWriter(File file, Charset charset, boolean isAppend) { return new CsvWriter(file, charset, isAppend); }
java
public static CsvWriter getWriter(File file, Charset charset, boolean isAppend) { return new CsvWriter(file, charset, isAppend); }
[ "public", "static", "CsvWriter", "getWriter", "(", "File", "file", ",", "Charset", "charset", ",", "boolean", "isAppend", ")", "{", "return", "new", "CsvWriter", "(", "file", ",", "charset", ",", "isAppend", ")", ";", "}" ]
获取CSV生成器(写出器),使用默认配置 @param file File CSV文件 @param charset 编码 @param isAppend 是否追加
[ "获取CSV生成器(写出器),使用默认配置" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/csv/CsvUtil.java#L74-L76
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/decomposition/TriangularSolver_DDRM.java
TriangularSolver_DDRM.solveL
public static void solveL( double L[] , double []b , int n ) { // for( int i = 0; i < n; i++ ) { // double sum = b[i]; // for( int k=0; k<i; k++ ) { // sum -= L[i*n+k]* b[k]; // } // b[i] = sum / L[i*n+i]; // } for( int i = 0; i < n; i++ ) { double sum = b[i]; int indexL = i*n; for( int k=0; k<i; k++ ) { sum -= L[indexL++]* b[k]; } b[i] = sum / L[indexL]; } }
java
public static void solveL( double L[] , double []b , int n ) { // for( int i = 0; i < n; i++ ) { // double sum = b[i]; // for( int k=0; k<i; k++ ) { // sum -= L[i*n+k]* b[k]; // } // b[i] = sum / L[i*n+i]; // } for( int i = 0; i < n; i++ ) { double sum = b[i]; int indexL = i*n; for( int k=0; k<i; k++ ) { sum -= L[indexL++]* b[k]; } b[i] = sum / L[indexL]; } }
[ "public", "static", "void", "solveL", "(", "double", "L", "[", "]", ",", "double", "[", "]", "b", ",", "int", "n", ")", "{", "// for( int i = 0; i < n; i++ ) {", "// double sum = b[i];", "// for( int k=0; k<i; k++ ) {", "// sum ...
<p> Solves for non-singular lower triangular matrices using forward substitution. <br> b = L<sup>-1</sup>b<br> <br> where b is a vector, L is an n by n matrix.<br> </p> @param L An n by n non-singular lower triangular matrix. Not modified. @param b A vector of length n. Modified. @param n The size of the matrices.
[ "<p", ">", "Solves", "for", "non", "-", "singular", "lower", "triangular", "matrices", "using", "forward", "substitution", ".", "<br", ">", "b", "=", "L<sup", ">", "-", "1<", "/", "sup", ">", "b<br", ">", "<br", ">", "where", "b", "is", "a", "vector"...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/decomposition/TriangularSolver_DDRM.java#L89-L106
jmrozanec/cron-utils
src/main/java/com/cronutils/descriptor/refactor/SecondsDescriptor.java
SecondsDescriptor.describe
protected String describe(final FieldExpression fieldExpression, final boolean and) { Preconditions.checkNotNull(fieldExpression, "CronFieldExpression should not be null!"); if (fieldExpression instanceof Always) { return describe(fieldExpression, and); } if (fieldExpression instanceof And) { return describe((And) fieldExpression); } if (fieldExpression instanceof Between) { return describe(fieldExpression, and); } if (fieldExpression instanceof Every) { return describe((Every) fieldExpression, and); } if (fieldExpression instanceof On) { return describe((On) fieldExpression, and); } return StringUtils.EMPTY; }
java
protected String describe(final FieldExpression fieldExpression, final boolean and) { Preconditions.checkNotNull(fieldExpression, "CronFieldExpression should not be null!"); if (fieldExpression instanceof Always) { return describe(fieldExpression, and); } if (fieldExpression instanceof And) { return describe((And) fieldExpression); } if (fieldExpression instanceof Between) { return describe(fieldExpression, and); } if (fieldExpression instanceof Every) { return describe((Every) fieldExpression, and); } if (fieldExpression instanceof On) { return describe((On) fieldExpression, and); } return StringUtils.EMPTY; }
[ "protected", "String", "describe", "(", "final", "FieldExpression", "fieldExpression", ",", "final", "boolean", "and", ")", "{", "Preconditions", ".", "checkNotNull", "(", "fieldExpression", ",", "\"CronFieldExpression should not be null!\"", ")", ";", "if", "(", "fie...
Given a CronFieldExpression, provide a String with a human readable description. Will identify CronFieldExpression subclasses and delegate. @param fieldExpression - CronFieldExpression instance - not null @param and - boolean expression that indicates if description should fit an "and" context @return human readable description - String
[ "Given", "a", "CronFieldExpression", "provide", "a", "String", "with", "a", "human", "readable", "description", ".", "Will", "identify", "CronFieldExpression", "subclasses", "and", "delegate", "." ]
train
https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/descriptor/refactor/SecondsDescriptor.java#L50-L68
Ordinastie/MalisisCore
src/main/java/net/malisis/core/MalisisCore.java
MalisisCore.openConfigurationGui
@SideOnly(Side.CLIENT) public static boolean openConfigurationGui(IMalisisMod mod) { Settings settings = mod.getSettings(); if (settings == null) return false; new ConfigurationGui(mod, settings).display(true); return true; }
java
@SideOnly(Side.CLIENT) public static boolean openConfigurationGui(IMalisisMod mod) { Settings settings = mod.getSettings(); if (settings == null) return false; new ConfigurationGui(mod, settings).display(true); return true; }
[ "@", "SideOnly", "(", "Side", ".", "CLIENT", ")", "public", "static", "boolean", "openConfigurationGui", "(", "IMalisisMod", "mod", ")", "{", "Settings", "settings", "=", "mod", ".", "getSettings", "(", ")", ";", "if", "(", "settings", "==", "null", ")", ...
Open the configuration GUI for the {@link IMalisisMod}. @param mod the mod to open the GUI for @return true, if a the mod had {@link Settings} and the GUI was opened, false otherwise
[ "Open", "the", "configuration", "GUI", "for", "the", "{", "@link", "IMalisisMod", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/MalisisCore.java#L299-L309
RestComm/jain-slee.sip
resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/Utils.java
Utils.getRequestUri
public static URI getRequestUri(Response response, AddressFactory addressFactory) throws ParseException { final ContactHeader contact = ((ContactHeader) response.getHeader(ContactHeader.NAME)); return (contact != null) ? (URI) contact.getAddress().getURI().clone() : null; }
java
public static URI getRequestUri(Response response, AddressFactory addressFactory) throws ParseException { final ContactHeader contact = ((ContactHeader) response.getHeader(ContactHeader.NAME)); return (contact != null) ? (URI) contact.getAddress().getURI().clone() : null; }
[ "public", "static", "URI", "getRequestUri", "(", "Response", "response", ",", "AddressFactory", "addressFactory", ")", "throws", "ParseException", "{", "final", "ContactHeader", "contact", "=", "(", "(", "ContactHeader", ")", "response", ".", "getHeader", "(", "Co...
Forges Request-URI using contact and To name par to address URI, this is required on dialog fork, this is how target is determined @param response @return @throws ParseException
[ "Forges", "Request", "-", "URI", "using", "contact", "and", "To", "name", "par", "to", "address", "URI", "this", "is", "required", "on", "dialog", "fork", "this", "is", "how", "target", "is", "determined" ]
train
https://github.com/RestComm/jain-slee.sip/blob/2c173af0a760cb0ea13fe0ffa58c0f82b14731f9/resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/Utils.java#L144-L147
signit-wesign/java-sdk
src/main/java/cn/signit/sdk/SignitClient.java
SignitClient.verify
public static boolean verify(String appId, String appSecretKey, byte[] body, HttpServletRequest request) throws IOException { HmacSignatureBuilder builder = new HmacSignatureBuilder(); String signitSignature = request.getHeader("X-Signit-Signature"); builder.scheme(request.getHeader("X-Signit-Scheme")) .apiKey(appId) .apiSecret(appSecretKey.getBytes()) .method(request.getMethod() .toUpperCase()) .payload(body) .contentType(request.getContentType()) .host(Validator.isEmpty(request.getHeader("X-Signit-Host")) ? "" : request.getHeader("X-Signit-Host")) .resource(Validator.isEmpty(request.getHeader("X-Signit-Resource")) ? "" : request.getHeader("X-Signit-Resource")) .nonce(Validator.isEmpty(request.getHeader("X-Signit-Nonce")) ? "" : request.getHeader("X-Signit-Nonce")) .date(Validator.isEmpty(request.getHeader("X-Signit-Date")) ? "" : request.getHeader("X-Signit-Date")); String selfBuiltHmac = builder.getDefaultAlgorithm() + " " + appId + ":" + builder.buildAsBase64(); return selfBuiltHmac.equals(signitSignature); }
java
public static boolean verify(String appId, String appSecretKey, byte[] body, HttpServletRequest request) throws IOException { HmacSignatureBuilder builder = new HmacSignatureBuilder(); String signitSignature = request.getHeader("X-Signit-Signature"); builder.scheme(request.getHeader("X-Signit-Scheme")) .apiKey(appId) .apiSecret(appSecretKey.getBytes()) .method(request.getMethod() .toUpperCase()) .payload(body) .contentType(request.getContentType()) .host(Validator.isEmpty(request.getHeader("X-Signit-Host")) ? "" : request.getHeader("X-Signit-Host")) .resource(Validator.isEmpty(request.getHeader("X-Signit-Resource")) ? "" : request.getHeader("X-Signit-Resource")) .nonce(Validator.isEmpty(request.getHeader("X-Signit-Nonce")) ? "" : request.getHeader("X-Signit-Nonce")) .date(Validator.isEmpty(request.getHeader("X-Signit-Date")) ? "" : request.getHeader("X-Signit-Date")); String selfBuiltHmac = builder.getDefaultAlgorithm() + " " + appId + ":" + builder.buildAsBase64(); return selfBuiltHmac.equals(signitSignature); }
[ "public", "static", "boolean", "verify", "(", "String", "appId", ",", "String", "appSecretKey", ",", "byte", "[", "]", "body", ",", "HttpServletRequest", "request", ")", "throws", "IOException", "{", "HmacSignatureBuilder", "builder", "=", "new", "HmacSignatureBui...
客户端验证服务器的webhook响应数据 @param appId APP ID @param appSecretKey APP Secret @param body webhook响应具体数据。考虑到request中只能获取到body一次,故而需要在方法外获取并传递给此方法 @param request 服务端向客户端发起的请求 @throws IOException 数据流异常 @return 验证结果: true-是服务器发送给客户端的数据;false-验证失败 @since 2.0.0
[ "客户端验证服务器的webhook响应数据" ]
train
https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/SignitClient.java#L369-L389
alkacon/opencms-core
src/org/opencms/staticexport/CmsStaticExportManager.java
CmsStaticExportManager.getRfsName
public String getRfsName(CmsObject cms, String vfsName) { return getRfsName(cms, vfsName, null, null); }
java
public String getRfsName(CmsObject cms, String vfsName) { return getRfsName(cms, vfsName, null, null); }
[ "public", "String", "getRfsName", "(", "CmsObject", "cms", ",", "String", "vfsName", ")", "{", "return", "getRfsName", "(", "cms", ",", "vfsName", ",", "null", ",", "null", ")", ";", "}" ]
Returns the static export rfs name for a given vfs resource.<p> @param cms an initialized cms context @param vfsName the name of the vfs resource @return the static export rfs name for a give vfs resource @see #getVfsName(CmsObject, String) @see #getRfsName(CmsObject, String, String, String)
[ "Returns", "the", "static", "export", "rfs", "name", "for", "a", "given", "vfs", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportManager.java#L1311-L1314
biojava/biojava
biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java
Utils.roundToDecimals
public final static double roundToDecimals(double d, int c) { if(c < 0) return d; double p = Math.pow(10,c); d = d * p; double tmp = Math.round(d); return tmp/p; }
java
public final static double roundToDecimals(double d, int c) { if(c < 0) return d; double p = Math.pow(10,c); d = d * p; double tmp = Math.round(d); return tmp/p; }
[ "public", "final", "static", "double", "roundToDecimals", "(", "double", "d", ",", "int", "c", ")", "{", "if", "(", "c", "<", "0", ")", "return", "d", ";", "double", "p", "=", "Math", ".", "pow", "(", "10", ",", "c", ")", ";", "d", "=", "d", ...
Returns a value with the desired number of decimal places. @param d value to round @param c number of decimal places desired. Must be greater or equal to zero, otherwise, the given value d would be returned without any modification. @return a value with the given number of decimal places.
[ "Returns", "a", "value", "with", "the", "desired", "number", "of", "decimal", "places", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java#L51-L57
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/priority/Tree.java
Tree.changeNodePriority
public synchronized boolean changeNodePriority(int streamID, int newPriority) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "changeNodePriority entry: streamID to change: " + streamID + " new Priority: " + newPriority); } Node nodeToChange = root.findNode(streamID); Node parentNode = nodeToChange.getParent(); if ((nodeToChange == null) || (parentNode == null)) { return false; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "node to change: " + nodeToChange + " has parent node of: " + parentNode); } // change the priority, clear the write counts and sort the nodes at that level in the tree nodeToChange.setPriority(newPriority); parentNode.clearDependentsWriteCount(); parentNode.sortDependents(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "changeNodePriority exit: node changed: " + nodeToChange.toStringDetails()); } return true; }
java
public synchronized boolean changeNodePriority(int streamID, int newPriority) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "changeNodePriority entry: streamID to change: " + streamID + " new Priority: " + newPriority); } Node nodeToChange = root.findNode(streamID); Node parentNode = nodeToChange.getParent(); if ((nodeToChange == null) || (parentNode == null)) { return false; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "node to change: " + nodeToChange + " has parent node of: " + parentNode); } // change the priority, clear the write counts and sort the nodes at that level in the tree nodeToChange.setPriority(newPriority); parentNode.clearDependentsWriteCount(); parentNode.sortDependents(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "changeNodePriority exit: node changed: " + nodeToChange.toStringDetails()); } return true; }
[ "public", "synchronized", "boolean", "changeNodePriority", "(", "int", "streamID", ",", "int", "newPriority", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debu...
Change the priority of the desired stream/node. Reset all the sibling weighted priorities and re-sort the siblings, since once on priority changes, all priority ratios need to be updated and changed. @param streamID @param newPriority @return the Node that was changed, null if the node could not be found
[ "Change", "the", "priority", "of", "the", "desired", "stream", "/", "node", ".", "Reset", "all", "the", "sibling", "weighted", "priorities", "and", "re", "-", "sort", "the", "siblings", "since", "once", "on", "priority", "changes", "all", "priority", "ratios...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/priority/Tree.java#L225-L252
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.plus
public static Month plus(final Month self, int months) { int monthsPerYear = Month.values().length; int val = ((self.getValue() + months - 1) % monthsPerYear) + 1; return Month.of(val > 0 ? val : monthsPerYear + val); }
java
public static Month plus(final Month self, int months) { int monthsPerYear = Month.values().length; int val = ((self.getValue() + months - 1) % monthsPerYear) + 1; return Month.of(val > 0 ? val : monthsPerYear + val); }
[ "public", "static", "Month", "plus", "(", "final", "Month", "self", ",", "int", "months", ")", "{", "int", "monthsPerYear", "=", "Month", ".", "values", "(", ")", ".", "length", ";", "int", "val", "=", "(", "(", "self", ".", "getValue", "(", ")", "...
Returns the {@link java.time.Month} that is {@code months} months after this month. @param self a Month @param months the number of months move forward @return the Month @since 2.5.0
[ "Returns", "the", "{", "@link", "java", ".", "time", ".", "Month", "}", "that", "is", "{", "@code", "months", "}", "months", "after", "this", "month", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L2029-L2033
Erudika/para
para-server/src/main/java/com/erudika/para/security/CachedCsrfTokenRepository.java
CachedCsrfTokenRepository.saveToken
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) { String ident = getIdentifierFromCookie(request); if (ident != null) { String key = ident.concat(parameterName); CsrfToken token = loadToken(request); if (token == null) { token = generateToken(null); if (Config.isCacheEnabled()) { cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC); } else { localCache.put(key, new Object[]{token, System.currentTimeMillis()}); } } storeTokenAsCookie(token, request, response); } }
java
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) { String ident = getIdentifierFromCookie(request); if (ident != null) { String key = ident.concat(parameterName); CsrfToken token = loadToken(request); if (token == null) { token = generateToken(null); if (Config.isCacheEnabled()) { cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC); } else { localCache.put(key, new Object[]{token, System.currentTimeMillis()}); } } storeTokenAsCookie(token, request, response); } }
[ "public", "void", "saveToken", "(", "CsrfToken", "t", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "{", "String", "ident", "=", "getIdentifierFromCookie", "(", "request", ")", ";", "if", "(", "ident", "!=", "null", ")", "{...
Saves a CSRF token in cache. @param t (ignored) @param request HTTP request @param response HTTP response
[ "Saves", "a", "CSRF", "token", "in", "cache", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/security/CachedCsrfTokenRepository.java#L76-L91
eurekaclinical/protempa
protempa-framework/src/main/java/org/protempa/graph/DirectedGraph.java
DirectedGraph.setEdge
public void setEdge(Object vertex1, Object vertex2, Weight weight) { VertexMetadata vm1 = (VertexMetadata) vertices.get(vertex1); VertexMetadata vm2 = (VertexMetadata) vertices.get(vertex2); if (vm1 == null || vm2 == null) { return; } int index1 = vm1.index; int index2 = vm2.index; Edge e = new Edge(vertex1, vertex2, weight); Edge prev = edges[index1][index2]; edges[index1][index2] = e; edgesArr = null; edgeModCount++; if (prev == null) { edgeCount++; } }
java
public void setEdge(Object vertex1, Object vertex2, Weight weight) { VertexMetadata vm1 = (VertexMetadata) vertices.get(vertex1); VertexMetadata vm2 = (VertexMetadata) vertices.get(vertex2); if (vm1 == null || vm2 == null) { return; } int index1 = vm1.index; int index2 = vm2.index; Edge e = new Edge(vertex1, vertex2, weight); Edge prev = edges[index1][index2]; edges[index1][index2] = e; edgesArr = null; edgeModCount++; if (prev == null) { edgeCount++; } }
[ "public", "void", "setEdge", "(", "Object", "vertex1", ",", "Object", "vertex2", ",", "Weight", "weight", ")", "{", "VertexMetadata", "vm1", "=", "(", "VertexMetadata", ")", "vertices", ".", "get", "(", "vertex1", ")", ";", "VertexMetadata", "vm2", "=", "(...
Set the edge between two vertices. If the two given vertices don't exist, nothing happens. A <code>null</code> <code>weight</code> unsets the edge. @param vertex1 a vertex. @param vertex2 a vertex. @param weight the value of the edge.
[ "Set", "the", "edge", "between", "two", "vertices", ".", "If", "the", "two", "given", "vertices", "don", "t", "exist", "nothing", "happens", ".", "A", "<code", ">", "null<", "/", "code", ">", "<code", ">", "weight<", "/", "code", ">", "unsets", "the", ...
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/graph/DirectedGraph.java#L246-L262
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/blockdata/BlockDataHandler.java
BlockDataHandler.setData
public static <T> void setData(String identifier, IBlockAccess world, BlockPos pos, T data, boolean sendToClients) { World w = instance.world(world); ChunkData<T> chunkData = instance.<T> chunkData(identifier, w, pos); if (chunkData == null) chunkData = instance.<T> createChunkData(identifier, instance.world(world), pos); //MalisisCore.message("SetData " + identifier + " for " + pos + " > " + data); chunkData.setData(pos, data); if (sendToClients && !w.isRemote) { ByteBuf buf = chunkData.toBytes(Unpooled.buffer()); Utils.getLoadedChunk(w, pos).ifPresent(chunk -> BlockDataMessage.sendBlockData(chunk, identifier, buf)); } }
java
public static <T> void setData(String identifier, IBlockAccess world, BlockPos pos, T data, boolean sendToClients) { World w = instance.world(world); ChunkData<T> chunkData = instance.<T> chunkData(identifier, w, pos); if (chunkData == null) chunkData = instance.<T> createChunkData(identifier, instance.world(world), pos); //MalisisCore.message("SetData " + identifier + " for " + pos + " > " + data); chunkData.setData(pos, data); if (sendToClients && !w.isRemote) { ByteBuf buf = chunkData.toBytes(Unpooled.buffer()); Utils.getLoadedChunk(w, pos).ifPresent(chunk -> BlockDataMessage.sendBlockData(chunk, identifier, buf)); } }
[ "public", "static", "<", "T", ">", "void", "setData", "(", "String", "identifier", ",", "IBlockAccess", "world", ",", "BlockPos", "pos", ",", "T", "data", ",", "boolean", "sendToClients", ")", "{", "World", "w", "=", "instance", ".", "world", "(", "world...
Sets the custom data to be stored at the {@link BlockPos} for the specified identifier and eventually sends the data to the clients watching the chunk. @param <T> the generic type @param identifier the identifier @param world the world @param pos the pos @param data the data @param sendToClients the send to clients
[ "Sets", "the", "custom", "data", "to", "be", "stored", "at", "the", "{", "@link", "BlockPos", "}", "for", "the", "specified", "identifier", "and", "eventually", "sends", "the", "data", "to", "the", "clients", "watching", "the", "chunk", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/blockdata/BlockDataHandler.java#L321-L335
stripe/stripe-android
stripe/src/main/java/com/stripe/android/model/ModelUtils.java
ModelUtils.hasYearPassed
static boolean hasYearPassed(int year, @NonNull Calendar now) { int normalized = normalizeYear(year, now); return normalized < now.get(Calendar.YEAR); }
java
static boolean hasYearPassed(int year, @NonNull Calendar now) { int normalized = normalizeYear(year, now); return normalized < now.get(Calendar.YEAR); }
[ "static", "boolean", "hasYearPassed", "(", "int", "year", ",", "@", "NonNull", "Calendar", "now", ")", "{", "int", "normalized", "=", "normalizeYear", "(", "year", ",", "now", ")", ";", "return", "normalized", "<", "now", ".", "get", "(", "Calendar", "."...
Determines whether or not the input year has already passed. @param year the input year, as a two or four-digit integer @param now, the current time @return {@code true} if the input year has passed the year of the specified current time {@code false} otherwise.
[ "Determines", "whether", "or", "not", "the", "input", "year", "has", "already", "passed", "." ]
train
https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/model/ModelUtils.java#L52-L55
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
Model.convertTimestamp
@Deprecated protected static ValidationBuilder convertTimestamp(String attributeName, String format){ return ModelDelegate.convertTimestamp(modelClass(), attributeName, format); }
java
@Deprecated protected static ValidationBuilder convertTimestamp(String attributeName, String format){ return ModelDelegate.convertTimestamp(modelClass(), attributeName, format); }
[ "@", "Deprecated", "protected", "static", "ValidationBuilder", "convertTimestamp", "(", "String", "attributeName", ",", "String", "format", ")", "{", "return", "ModelDelegate", ".", "convertTimestamp", "(", "modelClass", "(", ")", ",", "attributeName", ",", "format"...
Converts a named attribute to <code>java.sql.Timestamp</code> if possible. Acts as a validator if cannot make a conversion. @param attributeName name of attribute to convert to <code>java.sql.Timestamp</code>. @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} @return message passing for custom validation message. @deprecated use {@link #timestampFormat(String, String...) instead
[ "Converts", "a", "named", "attribute", "to", "<code", ">", "java", ".", "sql", ".", "Timestamp<", "/", "code", ">", "if", "possible", ".", "Acts", "as", "a", "validator", "if", "cannot", "make", "a", "conversion", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L2094-L2097
kiswanij/jk-util
src/main/java/com/jk/util/JKDateTimeUtil.java
JKDateTimeUtil.getSecondsDifference
public static long getSecondsDifference(Date startDate, Date endDate) { long startTime = startDate.getTime(); long endTime = endDate.getTime(); long diffTime = endTime - startTime; long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diffTime); return diffInSeconds; }
java
public static long getSecondsDifference(Date startDate, Date endDate) { long startTime = startDate.getTime(); long endTime = endDate.getTime(); long diffTime = endTime - startTime; long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diffTime); return diffInSeconds; }
[ "public", "static", "long", "getSecondsDifference", "(", "Date", "startDate", ",", "Date", "endDate", ")", "{", "long", "startTime", "=", "startDate", ".", "getTime", "(", ")", ";", "long", "endTime", "=", "endDate", ".", "getTime", "(", ")", ";", "long", ...
Gets the seconds difference. @param startDate the start date @param endDate the end date @return the seconds difference
[ "Gets", "the", "seconds", "difference", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L442-L448
lessthanoptimal/BoofCV
main/boofcv-io/src/main/java/boofcv/io/image/impl/ImplConvertRaster.java
ImplConvertRaster.bufferedToGray
public static void bufferedToGray(BufferedImage src, GrayI16 dst) { final int width = src.getWidth(); final int height = src.getHeight(); short[] data = dst.data; if (src.getType() == BufferedImage.TYPE_BYTE_GRAY || src.getType() == BufferedImage.TYPE_USHORT_GRAY ) { // If the buffered image is a gray scale image there is a bug where getRGB distorts // the image. See Bug ID: 5051418 , it has been around since 2004. Fuckers... WritableRaster raster = src.getRaster(); //CONCURRENT_REMOVE_BELOW int hack[] = new int[1]; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { //CONCURRENT_INLINE int hack[] = new int[1]; int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++) { raster.getPixel(x, y, hack); data[index++] = (short) hack[0]; } } //CONCURRENT_ABOVE }); } else { // this will be totally garbage. just here so that some unit test will pass //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++) { int argb = src.getRGB(x, y); data[index++] = (short) ((((argb >>> 16) & 0xFF) + ((argb >>> 8) & 0xFF) + (argb & 0xFF)) / 3); } } //CONCURRENT_ABOVE }); } }
java
public static void bufferedToGray(BufferedImage src, GrayI16 dst) { final int width = src.getWidth(); final int height = src.getHeight(); short[] data = dst.data; if (src.getType() == BufferedImage.TYPE_BYTE_GRAY || src.getType() == BufferedImage.TYPE_USHORT_GRAY ) { // If the buffered image is a gray scale image there is a bug where getRGB distorts // the image. See Bug ID: 5051418 , it has been around since 2004. Fuckers... WritableRaster raster = src.getRaster(); //CONCURRENT_REMOVE_BELOW int hack[] = new int[1]; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { //CONCURRENT_INLINE int hack[] = new int[1]; int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++) { raster.getPixel(x, y, hack); data[index++] = (short) hack[0]; } } //CONCURRENT_ABOVE }); } else { // this will be totally garbage. just here so that some unit test will pass //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++) { int argb = src.getRGB(x, y); data[index++] = (short) ((((argb >>> 16) & 0xFF) + ((argb >>> 8) & 0xFF) + (argb & 0xFF)) / 3); } } //CONCURRENT_ABOVE }); } }
[ "public", "static", "void", "bufferedToGray", "(", "BufferedImage", "src", ",", "GrayI16", "dst", ")", "{", "final", "int", "width", "=", "src", ".", "getWidth", "(", ")", ";", "final", "int", "height", "=", "src", ".", "getHeight", "(", ")", ";", "sho...
<p> Converts a buffered image into an 16bit intensity image using the BufferedImage's RGB interface. </p> <p> This is much slower than working directly with the BufferedImage's internal raster and should be avoided if possible. </p> @param src Input image. @param dst Output image.
[ "<p", ">", "Converts", "a", "buffered", "image", "into", "an", "16bit", "intensity", "image", "using", "the", "BufferedImage", "s", "RGB", "interface", ".", "<", "/", "p", ">", "<p", ">", "This", "is", "much", "slower", "than", "working", "directly", "wi...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/impl/ImplConvertRaster.java#L634-L672
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/DojoHttpTransport.java
DojoHttpTransport.beforeModule
protected String beforeModule(HttpServletRequest request, ModuleInfo info) { StringBuffer sb = new StringBuffer(); if (!info.isScript()) { // Text module. Wrap in AMD define function call sb.append("define("); //$NON-NLS-1$ if (RequestUtil.isExportModuleName(request)) { sb.append("'").append(info.getModuleId()).append("',"); //$NON-NLS-1$ //$NON-NLS-2$ } } return sb.toString(); }
java
protected String beforeModule(HttpServletRequest request, ModuleInfo info) { StringBuffer sb = new StringBuffer(); if (!info.isScript()) { // Text module. Wrap in AMD define function call sb.append("define("); //$NON-NLS-1$ if (RequestUtil.isExportModuleName(request)) { sb.append("'").append(info.getModuleId()).append("',"); //$NON-NLS-1$ //$NON-NLS-2$ } } return sb.toString(); }
[ "protected", "String", "beforeModule", "(", "HttpServletRequest", "request", ",", "ModuleInfo", "info", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "!", "info", ".", "isScript", "(", ")", ")", "{", "// Text module. ...
Handles {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_FIRST_MODULE} and {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_SUBSEQUENT_MODULE} layer listener events. @param request the http request object @param info the {@link com.ibm.jaggr.core.transport.IHttpTransport.ModuleInfo} object for the module @return the layer contribution
[ "Handles", "{", "@link", "com", ".", "ibm", ".", "jaggr", ".", "core", ".", "transport", ".", "IHttpTransport", ".", "LayerContributionType#BEFORE_FIRST_MODULE", "}", "and", "{", "@link", "com", ".", "ibm", ".", "jaggr", ".", "core", ".", "transport", ".", ...
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/DojoHttpTransport.java#L218-L228
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
DecimalFormat.addAffixes
private void addAffixes(char[] container, char[] prefix, char[] suffix) { // We add affixes only if needed (affix length > 0). int pl = prefix.length; int sl = suffix.length; if (pl != 0) prependPrefix(prefix, pl, container); if (sl != 0) appendSuffix(suffix, sl, container); }
java
private void addAffixes(char[] container, char[] prefix, char[] suffix) { // We add affixes only if needed (affix length > 0). int pl = prefix.length; int sl = suffix.length; if (pl != 0) prependPrefix(prefix, pl, container); if (sl != 0) appendSuffix(suffix, sl, container); }
[ "private", "void", "addAffixes", "(", "char", "[", "]", "container", ",", "char", "[", "]", "prefix", ",", "char", "[", "]", "suffix", ")", "{", "// We add affixes only if needed (affix length > 0).", "int", "pl", "=", "prefix", ".", "length", ";", "int", "s...
private void addAffixes(boolean isNegative, char[] container) {
[ "private", "void", "addAffixes", "(", "boolean", "isNegative", "char", "[]", "container", ")", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java#L1324-L1332
marvinlabs/android-slideshow-widget
library/src/main/java/com/marvinlabs/widget/slideshow/adapter/BitmapAdapter.java
BitmapAdapter.onBitmapLoaded
protected void onBitmapLoaded(int position, Bitmap bitmap) { BitmapCache bc = cachedBitmaps.get(position); if (bc != null) { bc.status = bitmap == null ? SlideStatus.NOT_AVAILABLE : SlideStatus.READY; bc.bitmap = new WeakReference<Bitmap>(bitmap); } }
java
protected void onBitmapLoaded(int position, Bitmap bitmap) { BitmapCache bc = cachedBitmaps.get(position); if (bc != null) { bc.status = bitmap == null ? SlideStatus.NOT_AVAILABLE : SlideStatus.READY; bc.bitmap = new WeakReference<Bitmap>(bitmap); } }
[ "protected", "void", "onBitmapLoaded", "(", "int", "position", ",", "Bitmap", "bitmap", ")", "{", "BitmapCache", "bc", "=", "cachedBitmaps", ".", "get", "(", "position", ")", ";", "if", "(", "bc", "!=", "null", ")", "{", "bc", ".", "status", "=", "bitm...
This function should be called by subclasses once they have actually loaded the bitmap. @param position the position of the item @param bitmap the bitmap that has been loaded
[ "This", "function", "should", "be", "called", "by", "subclasses", "once", "they", "have", "actually", "loaded", "the", "bitmap", "." ]
train
https://github.com/marvinlabs/android-slideshow-widget/blob/0d8ddca9a8f62787d78b5eb7f184cabfee569d8d/library/src/main/java/com/marvinlabs/widget/slideshow/adapter/BitmapAdapter.java#L79-L85
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/ListIndexedIterating.java
ListIndexedIterating.sawOpcodeLoop
private void sawOpcodeLoop(final int seen) { try { stack.mergeJumps(this); switch (state) { case SAW_NOTHING: if ((seen == Const.IINC) && (getIntConstant() == 1)) { loopReg = getRegisterOperand(); state = State.SAW_IINC; } break; case SAW_IINC: if ((seen == Const.GOTO) || (seen == Const.GOTO_W)) { int branchTarget = getBranchTarget(); int pc = getPC(); if (branchTarget < pc) { possibleForLoops.add(new ForLoop(branchTarget, pc, loopReg)); } } state = State.SAW_NOTHING; break; } if ((seen == Const.INVOKEINTERFACE) && Values.SLASHED_JAVA_UTIL_LIST.equals(getClassConstantOperand()) && "size".equals(getNameConstantOperand()) && SignatureBuilder.SIG_VOID_TO_INT.equals(getSigConstantOperand())) { sawListSize = true; } } finally { stack.sawOpcode(this, seen); } }
java
private void sawOpcodeLoop(final int seen) { try { stack.mergeJumps(this); switch (state) { case SAW_NOTHING: if ((seen == Const.IINC) && (getIntConstant() == 1)) { loopReg = getRegisterOperand(); state = State.SAW_IINC; } break; case SAW_IINC: if ((seen == Const.GOTO) || (seen == Const.GOTO_W)) { int branchTarget = getBranchTarget(); int pc = getPC(); if (branchTarget < pc) { possibleForLoops.add(new ForLoop(branchTarget, pc, loopReg)); } } state = State.SAW_NOTHING; break; } if ((seen == Const.INVOKEINTERFACE) && Values.SLASHED_JAVA_UTIL_LIST.equals(getClassConstantOperand()) && "size".equals(getNameConstantOperand()) && SignatureBuilder.SIG_VOID_TO_INT.equals(getSigConstantOperand())) { sawListSize = true; } } finally { stack.sawOpcode(this, seen); } }
[ "private", "void", "sawOpcodeLoop", "(", "final", "int", "seen", ")", "{", "try", "{", "stack", ".", "mergeJumps", "(", "this", ")", ";", "switch", "(", "state", ")", "{", "case", "SAW_NOTHING", ":", "if", "(", "(", "seen", "==", "Const", ".", "IINC"...
the first pass of the method opcode to collet for loops information @param seen the currently parsed opcode
[ "the", "first", "pass", "of", "the", "method", "opcode", "to", "collet", "for", "loops", "information" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/ListIndexedIterating.java#L155-L186
exoplatform/jcr
exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/xml/PropertyWriteUtil.java
PropertyWriteUtil.writeAttributes
public static void writeAttributes(XMLStreamWriter xmlStreamWriter, HierarchicalProperty property) throws XMLStreamException { Map<String, String> attributes = property.getAttributes(); Iterator<String> keyIter = attributes.keySet().iterator(); while (keyIter.hasNext()) { String attrName = keyIter.next(); String attrValue = attributes.get(attrName); xmlStreamWriter.writeAttribute(attrName, attrValue); } }
java
public static void writeAttributes(XMLStreamWriter xmlStreamWriter, HierarchicalProperty property) throws XMLStreamException { Map<String, String> attributes = property.getAttributes(); Iterator<String> keyIter = attributes.keySet().iterator(); while (keyIter.hasNext()) { String attrName = keyIter.next(); String attrValue = attributes.get(attrName); xmlStreamWriter.writeAttribute(attrName, attrValue); } }
[ "public", "static", "void", "writeAttributes", "(", "XMLStreamWriter", "xmlStreamWriter", ",", "HierarchicalProperty", "property", ")", "throws", "XMLStreamException", "{", "Map", "<", "String", ",", "String", ">", "attributes", "=", "property", ".", "getAttributes", ...
Writes property attributes into XML. @param xmlStreamWriter XML writer @param property property @throws XMLStreamException {@link XMLStreamException}
[ "Writes", "property", "attributes", "into", "XML", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/xml/PropertyWriteUtil.java#L148-L159
NextFaze/power-adapters
power-adapters/src/main/java/com/nextfaze/poweradapters/DividerAdapterBuilder.java
DividerAdapterBuilder.innerView
@NonNull public DividerAdapterBuilder innerView(@NonNull ViewFactory viewFactory) { mInnerItem = new Item(checkNotNull(viewFactory, "viewFactory"), false); return this; }
java
@NonNull public DividerAdapterBuilder innerView(@NonNull ViewFactory viewFactory) { mInnerItem = new Item(checkNotNull(viewFactory, "viewFactory"), false); return this; }
[ "@", "NonNull", "public", "DividerAdapterBuilder", "innerView", "(", "@", "NonNull", "ViewFactory", "viewFactory", ")", "{", "mInnerItem", "=", "new", "Item", "(", "checkNotNull", "(", "viewFactory", ",", "\"viewFactory\"", ")", ",", "false", ")", ";", "return",...
Sets the divider that appears between all of the wrapped adapters items.
[ "Sets", "the", "divider", "that", "appears", "between", "all", "of", "the", "wrapped", "adapters", "items", "." ]
train
https://github.com/NextFaze/power-adapters/blob/cdf00b1b723ed9d6bcd549ae9741a19dd59651e1/power-adapters/src/main/java/com/nextfaze/poweradapters/DividerAdapterBuilder.java#L64-L68
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/Tesseract1.java
Tesseract1.doOCR
@Override public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException { return doOCR(imageList, null, rect); }
java
@Override public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException { return doOCR(imageList, null, rect); }
[ "@", "Override", "public", "String", "doOCR", "(", "List", "<", "IIOImage", ">", "imageList", ",", "Rectangle", "rect", ")", "throws", "TesseractException", "{", "return", "doOCR", "(", "imageList", ",", "null", ",", "rect", ")", ";", "}" ]
Performs OCR operation. @param imageList a list of <code>IIOImage</code> objects @param rect the bounding rectangle defines the region of the image to be recognized. A rectangle of zero dimension or <code>null</code> indicates the whole image. @return the recognized text @throws TesseractException
[ "Performs", "OCR", "operation", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/Tesseract1.java#L273-L276
opengeospatial/teamengine
teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java
XMLValidatingParser.checkXMLRules
public boolean checkXMLRules(Document doc, Document instruction) throws Exception { if (doc == null || doc.getDocumentElement() == null) return false; Element e = instruction.getDocumentElement(); PrintWriter logger = new PrintWriter(System.out); Document parsedDoc = parse(doc, e, logger); return (parsedDoc != null); }
java
public boolean checkXMLRules(Document doc, Document instruction) throws Exception { if (doc == null || doc.getDocumentElement() == null) return false; Element e = instruction.getDocumentElement(); PrintWriter logger = new PrintWriter(System.out); Document parsedDoc = parse(doc, e, logger); return (parsedDoc != null); }
[ "public", "boolean", "checkXMLRules", "(", "Document", "doc", ",", "Document", "instruction", ")", "throws", "Exception", "{", "if", "(", "doc", "==", "null", "||", "doc", ".", "getDocumentElement", "(", ")", "==", "null", ")", "return", "false", ";", "Ele...
A method to validate a pool of schemas outside of the request element. @param Document doc The file document to validate @param Document instruction The xml encapsulated schema information (file locations) @return false if there were errors, true if none.
[ "A", "method", "to", "validate", "a", "pool", "of", "schemas", "outside", "of", "the", "request", "element", "." ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L335-L344
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.setMetaClass
public static void setMetaClass(Object self, MetaClass metaClass) { if (metaClass instanceof HandleMetaClass) metaClass = ((HandleMetaClass)metaClass).getAdaptee(); if (self instanceof Class) { GroovySystem.getMetaClassRegistry().setMetaClass((Class) self, metaClass); } else { ((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass(self, metaClass); } }
java
public static void setMetaClass(Object self, MetaClass metaClass) { if (metaClass instanceof HandleMetaClass) metaClass = ((HandleMetaClass)metaClass).getAdaptee(); if (self instanceof Class) { GroovySystem.getMetaClassRegistry().setMetaClass((Class) self, metaClass); } else { ((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass(self, metaClass); } }
[ "public", "static", "void", "setMetaClass", "(", "Object", "self", ",", "MetaClass", "metaClass", ")", "{", "if", "(", "metaClass", "instanceof", "HandleMetaClass", ")", "metaClass", "=", "(", "(", "HandleMetaClass", ")", "metaClass", ")", ".", "getAdaptee", "...
Set the metaclass for an object. @param self the object whose metaclass we want to set @param metaClass the new metaclass value @since 1.6.0
[ "Set", "the", "metaclass", "for", "an", "object", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17292-L17301
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.get_user
public String get_user(Map<String, String> data) { String id = data.get("email"); return get("user/" + id, EMPTY_STRING); }
java
public String get_user(Map<String, String> data) { String id = data.get("email"); return get("user/" + id, EMPTY_STRING); }
[ "public", "String", "get_user", "(", "Map", "<", "String", ",", "String", ">", "data", ")", "{", "String", "id", "=", "data", ".", "get", "(", "\"email\"", ")", ";", "return", "get", "(", "\"user/\"", "+", "id", ",", "EMPTY_STRING", ")", ";", "}" ]
/* Get Access a specific user Information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} email: Email address of the already existing user in the SendinBlue contacts [Mandatory]
[ "/", "*", "Get", "Access", "a", "specific", "user", "Information", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L796-L799
thinkaurelius/titan
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/configuration/backend/KCVSConfiguration.java
KCVSConfiguration.get
@Override public <O> O get(final String key, final Class<O> datatype) { StaticBuffer column = string2StaticBuffer(key); final KeySliceQuery query = new KeySliceQuery(rowKey,column, BufferUtil.nextBiggerBuffer(column)); StaticBuffer result = BackendOperation.execute(new BackendOperation.Transactional<StaticBuffer>() { @Override public StaticBuffer call(StoreTransaction txh) throws BackendException { List<Entry> entries = store.getSlice(query,txh); if (entries.isEmpty()) return null; return entries.get(0).getValueAs(StaticBuffer.STATIC_FACTORY); } @Override public String toString() { return "getConfiguration"; } }, txProvider, times, maxOperationWaitTime); if (result==null) return null; return staticBuffer2Object(result, datatype); }
java
@Override public <O> O get(final String key, final Class<O> datatype) { StaticBuffer column = string2StaticBuffer(key); final KeySliceQuery query = new KeySliceQuery(rowKey,column, BufferUtil.nextBiggerBuffer(column)); StaticBuffer result = BackendOperation.execute(new BackendOperation.Transactional<StaticBuffer>() { @Override public StaticBuffer call(StoreTransaction txh) throws BackendException { List<Entry> entries = store.getSlice(query,txh); if (entries.isEmpty()) return null; return entries.get(0).getValueAs(StaticBuffer.STATIC_FACTORY); } @Override public String toString() { return "getConfiguration"; } }, txProvider, times, maxOperationWaitTime); if (result==null) return null; return staticBuffer2Object(result, datatype); }
[ "@", "Override", "public", "<", "O", ">", "O", "get", "(", "final", "String", "key", ",", "final", "Class", "<", "O", ">", "datatype", ")", "{", "StaticBuffer", "column", "=", "string2StaticBuffer", "(", "key", ")", ";", "final", "KeySliceQuery", "query"...
Reads the configuration property for this StoreManager @param key Key identifying the configuration property @return Value stored for the key or null if the configuration property has not (yet) been defined. @throws com.thinkaurelius.titan.diskstorage.BackendException
[ "Reads", "the", "configuration", "property", "for", "this", "StoreManager" ]
train
https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/configuration/backend/KCVSConfiguration.java#L84-L103
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java
ViterbiBuilder.repairBrokenLatticeAfter
private void repairBrokenLatticeAfter(ViterbiLattice lattice, int nodeEndIndex) { ViterbiNode[][] nodeEndIndices = lattice.getEndIndexArr(); for (int endIndex = nodeEndIndex + 1; endIndex < nodeEndIndices.length; endIndex++) { if (nodeEndIndices[endIndex] != null) { ViterbiNode glueBase = findGlueNodeCandidate(nodeEndIndex, nodeEndIndices[endIndex], endIndex); if (glueBase != null) { int delta = endIndex - nodeEndIndex; String glueBaseSurface = glueBase.getSurface(); String surface = glueBaseSurface.substring(glueBaseSurface.length() - delta); ViterbiNode glueNode = createGlueNode(nodeEndIndex, glueBase, surface); lattice.addNode(glueNode, nodeEndIndex, nodeEndIndex + glueNode.getSurface().length()); return; } } } }
java
private void repairBrokenLatticeAfter(ViterbiLattice lattice, int nodeEndIndex) { ViterbiNode[][] nodeEndIndices = lattice.getEndIndexArr(); for (int endIndex = nodeEndIndex + 1; endIndex < nodeEndIndices.length; endIndex++) { if (nodeEndIndices[endIndex] != null) { ViterbiNode glueBase = findGlueNodeCandidate(nodeEndIndex, nodeEndIndices[endIndex], endIndex); if (glueBase != null) { int delta = endIndex - nodeEndIndex; String glueBaseSurface = glueBase.getSurface(); String surface = glueBaseSurface.substring(glueBaseSurface.length() - delta); ViterbiNode glueNode = createGlueNode(nodeEndIndex, glueBase, surface); lattice.addNode(glueNode, nodeEndIndex, nodeEndIndex + glueNode.getSurface().length()); return; } } } }
[ "private", "void", "repairBrokenLatticeAfter", "(", "ViterbiLattice", "lattice", ",", "int", "nodeEndIndex", ")", "{", "ViterbiNode", "[", "]", "[", "]", "nodeEndIndices", "=", "lattice", ".", "getEndIndexArr", "(", ")", ";", "for", "(", "int", "endIndex", "="...
Tries to repair the lattice by creating and adding an additional Viterbi node to the RIGHT of the newly inserted user dictionary entry by using the substring of the node in the lattice that overlaps the least @param lattice @param nodeEndIndex
[ "Tries", "to", "repair", "the", "lattice", "by", "creating", "and", "adding", "an", "additional", "Viterbi", "node", "to", "the", "RIGHT", "of", "the", "newly", "inserted", "user", "dictionary", "entry", "by", "using", "the", "substring", "of", "the", "node"...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java#L260-L276
restfb/restfb
src/main/java/com/restfb/DefaultFacebookClient.java
DefaultFacebookClient.makeRequest
protected String makeRequest(String endpoint, Parameter... parameters) { return makeRequest(endpoint, false, false, null, parameters); }
java
protected String makeRequest(String endpoint, Parameter... parameters) { return makeRequest(endpoint, false, false, null, parameters); }
[ "protected", "String", "makeRequest", "(", "String", "endpoint", ",", "Parameter", "...", "parameters", ")", "{", "return", "makeRequest", "(", "endpoint", ",", "false", ",", "false", ",", "null", ",", "parameters", ")", ";", "}" ]
Coordinates the process of executing the API request GET/POST and processing the response we receive from the endpoint. @param endpoint Facebook Graph API endpoint. @param parameters Arbitrary number of parameters to send along to Facebook as part of the API call. @return The JSON returned by Facebook for the API call. @throws FacebookException If an error occurs while making the Facebook API POST or processing the response.
[ "Coordinates", "the", "process", "of", "executing", "the", "API", "request", "GET", "/", "POST", "and", "processing", "the", "response", "we", "receive", "from", "the", "endpoint", "." ]
train
https://github.com/restfb/restfb/blob/fb77ba5486d1339e7deb81b9830670fa209b1047/src/main/java/com/restfb/DefaultFacebookClient.java#L723-L725
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.perspectiveLH
public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspectiveLH(fovy, aspect, zNear, zFar, false, dest); }
java
public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspectiveLH(fovy, aspect, zNear, zFar, false, dest); }
[ "public", "Matrix4f", "perspectiveLH", "(", "float", "fovy", ",", "float", "aspect", ",", "float", "zNear", ",", "float", "zFar", ",", "Matrix4f", "dest", ")", "{", "return", "perspectiveLH", "(", "fovy", ",", "aspect", ",", "zNear", ",", "zFar", ",", "f...
Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system using OpenGL's NDC z range of <code>[-1..+1]</code> to this matrix and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, then the new matrix will be <code>M * P</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * P * v</code>, the perspective projection will be applied first! <p> In order to set the matrix to a perspective frustum transformation without post-multiplying, use {@link #setPerspectiveLH(float, float, float, float) setPerspectiveLH}. @see #setPerspectiveLH(float, float, float, float) @param fovy the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) @param aspect the aspect ratio (i.e. width / height; must be greater than zero) @param zNear near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. @param zFar far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. @param dest will hold the result @return dest
[ "Apply", "a", "symmetric", "perspective", "projection", "frustum", "transformation", "for", "a", "left", "-", "handed", "coordinate", "system", "using", "OpenGL", "s", "NDC", "z", "range", "of", "<code", ">", "[", "-", "1", "..", "+", "1", "]", "<", "/",...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L10177-L10179
synchronoss/cpo-api
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
CassandraCpoAdapter.insertObject
@Override public <T> long insertObject(String name, T obj, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { return processUpdateGroup(obj, CpoAdapter.CREATE_GROUP, name, wheres, orderBy, nativeExpressions); }
java
@Override public <T> long insertObject(String name, T obj, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { return processUpdateGroup(obj, CpoAdapter.CREATE_GROUP, name, wheres, orderBy, nativeExpressions); }
[ "@", "Override", "public", "<", "T", ">", "long", "insertObject", "(", "String", "name", ",", "T", "obj", ",", "Collection", "<", "CpoWhere", ">", "wheres", ",", "Collection", "<", "CpoOrderBy", ">", "orderBy", ",", "Collection", "<", "CpoNativeFunction", ...
Creates the Object in the datasource. The assumption is that the object does not exist in the datasource. This method creates and stores the object in the datasource <p/> <pre>Example: <code> <p/> class SomeObject so = new SomeObject(); class CpoAdapter cpo = null; <p/> try { cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } <p/> if (cpo!=null) { so.setId(1); so.setName("SomeName"); try{ cpo.insertObject("IDNameInsert",so); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param name The String name of the CREATE Function Group that will be used to create the object in the datasource. null signifies that the default rules will be used which is equivalent to insertObject(Object obj); @param obj This is an object that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return The number of objects created in the datasource @throws CpoException Thrown if there are errors accessing the datasource
[ "Creates", "the", "Object", "in", "the", "datasource", ".", "The", "assumption", "is", "that", "the", "object", "does", "not", "exist", "in", "the", "datasource", ".", "This", "method", "creates", "and", "stores", "the", "object", "in", "the", "datasource", ...
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L243-L246
needle4j/needle4j
src/main/java/org/needle4j/db/operation/AbstractDBOperation.java
AbstractDBOperation.openConnection
protected void openConnection() throws SQLException { if (connection == null) { try { Class.forName(configuration.getJdbcDriver()); } catch (NullPointerException npe) { throw new RuntimeException("error while lookup jdbc driver class. jdbc driver is not configured.", npe); } catch (ClassNotFoundException e) { throw new RuntimeException("jdbc driver not found", e); } connection = DriverManager.getConnection(configuration.getJdbcUrl(), configuration.getJdbcUser(), configuration.getJdbcPassword()); connection.setAutoCommit(false); } }
java
protected void openConnection() throws SQLException { if (connection == null) { try { Class.forName(configuration.getJdbcDriver()); } catch (NullPointerException npe) { throw new RuntimeException("error while lookup jdbc driver class. jdbc driver is not configured.", npe); } catch (ClassNotFoundException e) { throw new RuntimeException("jdbc driver not found", e); } connection = DriverManager.getConnection(configuration.getJdbcUrl(), configuration.getJdbcUser(), configuration.getJdbcPassword()); connection.setAutoCommit(false); } }
[ "protected", "void", "openConnection", "(", ")", "throws", "SQLException", "{", "if", "(", "connection", "==", "null", ")", "{", "try", "{", "Class", ".", "forName", "(", "configuration", ".", "getJdbcDriver", "(", ")", ")", ";", "}", "catch", "(", "Null...
Establish a connection to the given database. @throws SQLException if a database access error occurs
[ "Establish", "a", "connection", "to", "the", "given", "database", "." ]
train
https://github.com/needle4j/needle4j/blob/55fbcdeed72be5cf26e4404b0fe40282792b51f2/src/main/java/org/needle4j/db/operation/AbstractDBOperation.java#L43-L57
rometools/rome
rome-utils/src/main/java/com/rometools/utils/Lists.java
Lists.sizeIs
public static boolean sizeIs(final List<?> list, final int size) { if (size == 0) { return list == null || list.isEmpty(); } else { return list != null && list.size() == size; } }
java
public static boolean sizeIs(final List<?> list, final int size) { if (size == 0) { return list == null || list.isEmpty(); } else { return list != null && list.size() == size; } }
[ "public", "static", "boolean", "sizeIs", "(", "final", "List", "<", "?", ">", "list", ",", "final", "int", "size", ")", "{", "if", "(", "size", "==", "0", ")", "{", "return", "list", "==", "null", "||", "list", ".", "isEmpty", "(", ")", ";", "}",...
Checks whether the list has the given size. A null list is treated like a list without entries. @param list The list to check @param size The size to check @return true when the list has the given size or when size = 0 and the list is null, false otherwise
[ "Checks", "whether", "the", "list", "has", "the", "given", "size", ".", "A", "null", "list", "is", "treated", "like", "a", "list", "without", "entries", "." ]
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-utils/src/main/java/com/rometools/utils/Lists.java#L94-L100
logic-ng/LogicNG
src/main/java/org/logicng/graphs/datastructures/HypergraphNode.java
HypergraphNode.computeTentativeNewLocation
public double computeTentativeNewLocation(final Map<HypergraphNode<T>, Integer> nodeOrdering) { double newLocation = 0; for (final HypergraphEdge<T> edge : this.edges) newLocation += edge.centerOfGravity(nodeOrdering); return newLocation / this.edges.size(); }
java
public double computeTentativeNewLocation(final Map<HypergraphNode<T>, Integer> nodeOrdering) { double newLocation = 0; for (final HypergraphEdge<T> edge : this.edges) newLocation += edge.centerOfGravity(nodeOrdering); return newLocation / this.edges.size(); }
[ "public", "double", "computeTentativeNewLocation", "(", "final", "Map", "<", "HypergraphNode", "<", "T", ">", ",", "Integer", ">", "nodeOrdering", ")", "{", "double", "newLocation", "=", "0", ";", "for", "(", "final", "HypergraphEdge", "<", "T", ">", "edge",...
Computes the tentative new location for this node (see Aloul, Markov, and Sakallah). @param nodeOrdering the node ordering for which the COG is computed @return the tentative new location for this node
[ "Computes", "the", "tentative", "new", "location", "for", "this", "node", "(", "see", "Aloul", "Markov", "and", "Sakallah", ")", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/graphs/datastructures/HypergraphNode.java#L97-L102
networknt/light-4j
dump/src/main/java/com/networknt/dump/CookiesDumper.java
CookiesDumper.dumpResponse
@Override public void dumpResponse(Map<String, Object> result) { Map<String, Cookie> cookiesMap = exchange.getResponseCookies(); dumpCookies(cookiesMap, "responseCookies"); this.putDumpInfoTo(result); }
java
@Override public void dumpResponse(Map<String, Object> result) { Map<String, Cookie> cookiesMap = exchange.getResponseCookies(); dumpCookies(cookiesMap, "responseCookies"); this.putDumpInfoTo(result); }
[ "@", "Override", "public", "void", "dumpResponse", "(", "Map", "<", "String", ",", "Object", ">", "result", ")", "{", "Map", "<", "String", ",", "Cookie", ">", "cookiesMap", "=", "exchange", ".", "getResponseCookies", "(", ")", ";", "dumpCookies", "(", "...
impl of dumping response cookies to result @param result A map you want to put dump information to
[ "impl", "of", "dumping", "response", "cookies", "to", "result" ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/dump/src/main/java/com/networknt/dump/CookiesDumper.java#L50-L55
threerings/narya
core/src/main/java/com/threerings/presents/dobj/DObject.java
DObject.requestEntryUpdate
protected <T extends DSet.Entry> void requestEntryUpdate ( String name, DSet<T> set, T entry, Transport transport) { // if we're on the authoritative server, we update the set immediately T oldEntry = null; if (isAuthoritative()) { oldEntry = set.update(entry); if (oldEntry == null) { log.warning("Set update had no old entry", "name", name, "entry", entry, new Exception()); } } // dispatch an entry updated event postEvent(new EntryUpdatedEvent<T>(_oid, name, entry). setOldEntry(oldEntry).setTransport(transport)); }
java
protected <T extends DSet.Entry> void requestEntryUpdate ( String name, DSet<T> set, T entry, Transport transport) { // if we're on the authoritative server, we update the set immediately T oldEntry = null; if (isAuthoritative()) { oldEntry = set.update(entry); if (oldEntry == null) { log.warning("Set update had no old entry", "name", name, "entry", entry, new Exception()); } } // dispatch an entry updated event postEvent(new EntryUpdatedEvent<T>(_oid, name, entry). setOldEntry(oldEntry).setTransport(transport)); }
[ "protected", "<", "T", "extends", "DSet", ".", "Entry", ">", "void", "requestEntryUpdate", "(", "String", "name", ",", "DSet", "<", "T", ">", "set", ",", "T", "entry", ",", "Transport", "transport", ")", "{", "// if we're on the authoritative server, we update t...
Calls by derived instances when a set updater method was called.
[ "Calls", "by", "derived", "instances", "when", "a", "set", "updater", "method", "was", "called", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/DObject.java#L931-L946
spotify/docgenerator
scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java
JacksonJerseyAnnotationProcessor.computeMethodArguments
private List<ResourceArgument> computeMethodArguments(final ExecutableElement ee) { final List<ResourceArgument> arguments = Lists.newArrayList(); for (VariableElement ve : ee.getParameters()) { final PathParam pathAnnotation = ve.getAnnotation(PathParam.class); final String argName; if (pathAnnotation != null) { argName = pathAnnotation.value(); } else { argName = ve.getSimpleName().toString(); } arguments.add(new ResourceArgument(argName, makeTypeDescriptor(ve.asType()))); } return arguments; }
java
private List<ResourceArgument> computeMethodArguments(final ExecutableElement ee) { final List<ResourceArgument> arguments = Lists.newArrayList(); for (VariableElement ve : ee.getParameters()) { final PathParam pathAnnotation = ve.getAnnotation(PathParam.class); final String argName; if (pathAnnotation != null) { argName = pathAnnotation.value(); } else { argName = ve.getSimpleName().toString(); } arguments.add(new ResourceArgument(argName, makeTypeDescriptor(ve.asType()))); } return arguments; }
[ "private", "List", "<", "ResourceArgument", ">", "computeMethodArguments", "(", "final", "ExecutableElement", "ee", ")", "{", "final", "List", "<", "ResourceArgument", ">", "arguments", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "VariableEleme...
Given an {@link ExecutableElement} representing the method, compute it's arguments.
[ "Given", "an", "{" ]
train
https://github.com/spotify/docgenerator/blob/a7965f6d4a1546864a3f8584b86841cef9ac2f65/scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java#L150-L163
beanshell/beanshell
src/main/java/bsh/BSHMethodDeclaration.java
BSHMethodDeclaration.evalReturnType
Class evalReturnType( CallStack callstack, Interpreter interpreter ) throws EvalError { insureNodesParsed(); if ( returnTypeNode != null ) return returnTypeNode.evalReturnType( callstack, interpreter ); else return null; }
java
Class evalReturnType( CallStack callstack, Interpreter interpreter ) throws EvalError { insureNodesParsed(); if ( returnTypeNode != null ) return returnTypeNode.evalReturnType( callstack, interpreter ); else return null; }
[ "Class", "evalReturnType", "(", "CallStack", "callstack", ",", "Interpreter", "interpreter", ")", "throws", "EvalError", "{", "insureNodesParsed", "(", ")", ";", "if", "(", "returnTypeNode", "!=", "null", ")", "return", "returnTypeNode", ".", "evalReturnType", "("...
Evaluate the return type node. @return the type or null indicating loosely typed return
[ "Evaluate", "the", "return", "type", "node", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/BSHMethodDeclaration.java#L85-L93
infinispan/infinispan
counter/src/main/java/org/infinispan/counter/util/Utils.java
Utils.validateStrongCounterBounds
public static void validateStrongCounterBounds(long lowerBound, long initialValue, long upperBound) { if (lowerBound > initialValue || initialValue > upperBound) { throw log.invalidInitialValueForBoundedCounter(lowerBound, upperBound, initialValue); } else if (lowerBound == upperBound) { throw log.invalidSameLowerAndUpperBound(lowerBound, upperBound); } }
java
public static void validateStrongCounterBounds(long lowerBound, long initialValue, long upperBound) { if (lowerBound > initialValue || initialValue > upperBound) { throw log.invalidInitialValueForBoundedCounter(lowerBound, upperBound, initialValue); } else if (lowerBound == upperBound) { throw log.invalidSameLowerAndUpperBound(lowerBound, upperBound); } }
[ "public", "static", "void", "validateStrongCounterBounds", "(", "long", "lowerBound", ",", "long", "initialValue", ",", "long", "upperBound", ")", "{", "if", "(", "lowerBound", ">", "initialValue", "||", "initialValue", ">", "upperBound", ")", "{", "throw", "log...
Validates the lower and upper bound for a strong counter. <p> It throws a {@link CounterConfigurationException} is not valid. @param lowerBound The counter's lower bound value. @param initialValue The counter's initial value. @param upperBound The counter's upper bound value. @throws CounterConfigurationException if the upper or lower bound aren't valid.
[ "Validates", "the", "lower", "and", "upper", "bound", "for", "a", "strong", "counter", ".", "<p", ">", "It", "throws", "a", "{", "@link", "CounterConfigurationException", "}", "is", "not", "valid", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/counter/src/main/java/org/infinispan/counter/util/Utils.java#L34-L40
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java
IntegralImageOps.block_zero
public static double block_zero(GrayF64 integral , int x0 , int y0 , int x1 , int y1 ) { return ImplIntegralImageOps.block_zero(integral,x0,y0,x1,y1); }
java
public static double block_zero(GrayF64 integral , int x0 , int y0 , int x1 , int y1 ) { return ImplIntegralImageOps.block_zero(integral,x0,y0,x1,y1); }
[ "public", "static", "double", "block_zero", "(", "GrayF64", "integral", ",", "int", "x0", ",", "int", "y0", ",", "int", "x1", ",", "int", "y1", ")", "{", "return", "ImplIntegralImageOps", ".", "block_zero", "(", "integral", ",", "x0", ",", "y0", ",", "...
<p> Computes the value of a block inside an integral image and treats pixels outside of the image as zero. The block is defined as follows: x0 &lt; x &le; x1 and y0 &lt; y &le; y1. </p> @param integral Integral image. @param x0 Lower bound of the block. Exclusive. @param y0 Lower bound of the block. Exclusive. @param x1 Upper bound of the block. Inclusive. @param y1 Upper bound of the block. Inclusive. @return Value inside the block.
[ "<p", ">", "Computes", "the", "value", "of", "a", "block", "inside", "an", "integral", "image", "and", "treats", "pixels", "outside", "of", "the", "image", "as", "zero", ".", "The", "block", "is", "defined", "as", "follows", ":", "x0", "&lt", ";", "x",...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java#L462-L465
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteGroupBadge
public void deleteGroupBadge(Integer groupId, Integer badgeId) throws IOException { String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL + "/" + badgeId; retrieve().method(DELETE).to(tailUrl, Void.class); }
java
public void deleteGroupBadge(Integer groupId, Integer badgeId) throws IOException { String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL + "/" + badgeId; retrieve().method(DELETE).to(tailUrl, Void.class); }
[ "public", "void", "deleteGroupBadge", "(", "Integer", "groupId", ",", "Integer", "badgeId", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabGroup", ".", "URL", "+", "\"/\"", "+", "groupId", "+", "GitlabBadge", ".", "URL", "+", "\"/\"", "+...
Delete group badge @param groupId The id of the group for which the badge should be deleted @param badgeId The id of the badge that should be deleted @throws IOException on GitLab API call error
[ "Delete", "group", "badge" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2745-L2749
nutzam/nutzboot
nutzboot-demo/nutzboot-demo-simple/nutzboot-demo-simple-tio/src/main/java/io/nutz/demo/simple/tio/SimpleListener.java
SimpleListener.onBeforeClose
@Override public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) { log.debug("连接关闭前触发onBeforeClose"); }
java
@Override public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) { log.debug("连接关闭前触发onBeforeClose"); }
[ "@", "Override", "public", "void", "onBeforeClose", "(", "ChannelContext", "channelContext", ",", "Throwable", "throwable", ",", "String", "remark", ",", "boolean", "isRemove", ")", "{", "log", ".", "debug", "(", "\"连接关闭前触发onBeforeClose\");", "", "", "}" ]
连接关闭前触发本方法 @param channelContext the channelcontext @param throwable the throwable 有可能为空 @param remark the remark 有可能为空 @param isRemove @author tanyaowu
[ "连接关闭前触发本方法" ]
train
https://github.com/nutzam/nutzboot/blob/fd33fd4fdce058eab594f28e4d3202f997e3c66a/nutzboot-demo/nutzboot-demo-simple/nutzboot-demo-simple-tio/src/main/java/io/nutz/demo/simple/tio/SimpleListener.java#L63-L66
CODAIT/stocator
src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java
COSInputStream.readFully
@Override public void readFully(long position, byte[] buffer, int offset, int length) throws IOException { checkNotClosed(); validatePositionedReadArgs(position, buffer, offset, length); if (length == 0) { return; } int nread = 0; synchronized (this) { long oldPos = getPos(); try { seek(position); while (nread < length) { int nbytes = read(buffer, offset + nread, length - nread); if (nbytes < 0) { throw new EOFException("EOF_IN_READ_FULLY"); } nread += nbytes; } } finally { seekQuietly(oldPos); } } }
java
@Override public void readFully(long position, byte[] buffer, int offset, int length) throws IOException { checkNotClosed(); validatePositionedReadArgs(position, buffer, offset, length); if (length == 0) { return; } int nread = 0; synchronized (this) { long oldPos = getPos(); try { seek(position); while (nread < length) { int nbytes = read(buffer, offset + nread, length - nread); if (nbytes < 0) { throw new EOFException("EOF_IN_READ_FULLY"); } nread += nbytes; } } finally { seekQuietly(oldPos); } } }
[ "@", "Override", "public", "void", "readFully", "(", "long", "position", ",", "byte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "checkNotClosed", "(", ")", ";", "validatePositionedReadArgs", "(", "posi...
Subclass {@code readFully()} operation which only seeks at the start of the series of operations; seeking back at the end. This is significantly higher performance if multiple read attempts are needed to fetch the data, as it does not break the HTTP connection. To maintain thread safety requirements, this operation is synchronized for the duration of the sequence. {@inheritDoc}
[ "Subclass", "{", "@code", "readFully", "()", "}", "operation", "which", "only", "seeks", "at", "the", "start", "of", "the", "series", "of", "operations", ";", "seeking", "back", "at", "the", "end", "." ]
train
https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java#L550-L574
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java
XmlStringBuilder.optLongAttribute
public XmlStringBuilder optLongAttribute(String name, Long value) { if (value != null && value >= 0) { attribute(name, Long.toString(value)); } return this; }
java
public XmlStringBuilder optLongAttribute(String name, Long value) { if (value != null && value >= 0) { attribute(name, Long.toString(value)); } return this; }
[ "public", "XmlStringBuilder", "optLongAttribute", "(", "String", "name", ",", "Long", "value", ")", "{", "if", "(", "value", "!=", "null", "&&", "value", ">=", "0", ")", "{", "attribute", "(", "name", ",", "Long", ".", "toString", "(", "value", ")", ")...
Add the given attribute if value not null and {@code value => 0}. @param name @param value @return a reference to this object
[ "Add", "the", "given", "attribute", "if", "value", "not", "null", "and", "{", "@code", "value", "=", ">", "0", "}", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java#L351-L356
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java
DateFunctions.strToZoneName
public static Expression strToZoneName(Expression expression, String zoneName) { return x("STR_TO_ZONE_NAME(" + expression.toString() + ", \"" + zoneName + "\")"); }
java
public static Expression strToZoneName(Expression expression, String zoneName) { return x("STR_TO_ZONE_NAME(" + expression.toString() + ", \"" + zoneName + "\")"); }
[ "public", "static", "Expression", "strToZoneName", "(", "Expression", "expression", ",", "String", "zoneName", ")", "{", "return", "x", "(", "\"STR_TO_ZONE_NAME(\"", "+", "expression", ".", "toString", "(", ")", "+", "\", \\\"\"", "+", "zoneName", "+", "\"\\\")\...
Returned expression results in a conversion of the supported time stamp string to the named time zone.
[ "Returned", "expression", "results", "in", "a", "conversion", "of", "the", "supported", "time", "stamp", "string", "to", "the", "named", "time", "zone", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L318-L320
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/ftp/FTPFileSystem.java
FTPFileSystem.isFile
private boolean isFile(FTPClient client, Path file) { try { return !getFileStatus(client, file).isDir(); } catch (FileNotFoundException e) { return false; // file does not exist } catch (IOException ioe) { throw new FTPException("File check failed", ioe); } }
java
private boolean isFile(FTPClient client, Path file) { try { return !getFileStatus(client, file).isDir(); } catch (FileNotFoundException e) { return false; // file does not exist } catch (IOException ioe) { throw new FTPException("File check failed", ioe); } }
[ "private", "boolean", "isFile", "(", "FTPClient", "client", ",", "Path", "file", ")", "{", "try", "{", "return", "!", "getFileStatus", "(", "client", ",", "file", ")", ".", "isDir", "(", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "...
Convenience method, so that we don't open a new connection when using this method from within another method. Otherwise every API invocation incurs the overhead of opening/closing a TCP connection.
[ "Convenience", "method", "so", "that", "we", "don", "t", "open", "a", "new", "connection", "when", "using", "this", "method", "from", "within", "another", "method", ".", "Otherwise", "every", "API", "invocation", "incurs", "the", "overhead", "of", "opening", ...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/ftp/FTPFileSystem.java#L494-L502
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/lang/BitStrings.java
BitStrings.or
public static String or(final String first, final String second) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < first.length(); i++) { if ('0' == first.charAt(i) && '0' == second.charAt(i)) { buffer.append('0'); } else { buffer.append('1'); } } return buffer.toString(); }
java
public static String or(final String first, final String second) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < first.length(); i++) { if ('0' == first.charAt(i) && '0' == second.charAt(i)) { buffer.append('0'); } else { buffer.append('1'); } } return buffer.toString(); }
[ "public", "static", "String", "or", "(", "final", "String", "first", ",", "final", "String", "second", ")", "{", "final", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "first", ...
比较两个等长字符串的每一位,相或<br> 适用于仅含有1和0的字符串. @param first a {@link java.lang.String} object. @param second a {@link java.lang.String} object. @return a {@link java.lang.String} object.
[ "比较两个等长字符串的每一位,相或<br", ">", "适用于仅含有1和0的字符串", "." ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/BitStrings.java#L61-L71
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.setDateExpired
public void setDateExpired(CmsDbContext dbc, CmsResource resource, long dateExpired) throws CmsDataAccessException { resource.setDateExpired(dateExpired); if (resource.getState().isUnchanged()) { resource.setState(CmsResource.STATE_CHANGED); } getVfsDriver(dbc).writeResourceState(dbc, dbc.currentProject(), resource, UPDATE_STRUCTURE, false); // modify the last modified project reference getVfsDriver(dbc).writeResourceState(dbc, dbc.currentProject(), resource, UPDATE_RESOURCE_PROJECT, false); // log log( dbc, new CmsLogEntry( dbc, resource.getStructureId(), CmsLogEntryType.RESOURCE_DATE_EXPIRED, new String[] {resource.getRootPath()}), false); // clear the cache m_monitor.clearResourceCache(); // fire the event Map<String, Object> data = new HashMap<String, Object>(2); data.put(I_CmsEventListener.KEY_RESOURCE, resource); data.put(I_CmsEventListener.KEY_CHANGE, new Integer(CHANGED_TIMEFRAME)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, data)); }
java
public void setDateExpired(CmsDbContext dbc, CmsResource resource, long dateExpired) throws CmsDataAccessException { resource.setDateExpired(dateExpired); if (resource.getState().isUnchanged()) { resource.setState(CmsResource.STATE_CHANGED); } getVfsDriver(dbc).writeResourceState(dbc, dbc.currentProject(), resource, UPDATE_STRUCTURE, false); // modify the last modified project reference getVfsDriver(dbc).writeResourceState(dbc, dbc.currentProject(), resource, UPDATE_RESOURCE_PROJECT, false); // log log( dbc, new CmsLogEntry( dbc, resource.getStructureId(), CmsLogEntryType.RESOURCE_DATE_EXPIRED, new String[] {resource.getRootPath()}), false); // clear the cache m_monitor.clearResourceCache(); // fire the event Map<String, Object> data = new HashMap<String, Object>(2); data.put(I_CmsEventListener.KEY_RESOURCE, resource); data.put(I_CmsEventListener.KEY_CHANGE, new Integer(CHANGED_TIMEFRAME)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, data)); }
[ "public", "void", "setDateExpired", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ",", "long", "dateExpired", ")", "throws", "CmsDataAccessException", "{", "resource", ".", "setDateExpired", "(", "dateExpired", ")", ";", "if", "(", "resource", ".", ...
Changes the "expire" date of a resource.<p> @param dbc the current database context @param resource the resource to touch @param dateExpired the new expire date of the resource @throws CmsDataAccessException if something goes wrong @see CmsObject#setDateExpired(String, long, boolean) @see I_CmsResourceType#setDateExpired(CmsObject, CmsSecurityManager, CmsResource, long, boolean)
[ "Changes", "the", "expire", "date", "of", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L8830-L8858
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.indexOf
public static int indexOf(final CharSequence seq, final int searchChar) { if (isEmpty(seq)) { return INDEX_NOT_FOUND; } return CharSequenceUtils.indexOf(seq, searchChar, 0); }
java
public static int indexOf(final CharSequence seq, final int searchChar) { if (isEmpty(seq)) { return INDEX_NOT_FOUND; } return CharSequenceUtils.indexOf(seq, searchChar, 0); }
[ "public", "static", "int", "indexOf", "(", "final", "CharSequence", "seq", ",", "final", "int", "searchChar", ")", "{", "if", "(", "isEmpty", "(", "seq", ")", ")", "{", "return", "INDEX_NOT_FOUND", ";", "}", "return", "CharSequenceUtils", ".", "indexOf", "...
Returns the index within <code>seq</code> of the first occurrence of the specified character. If a character with value <code>searchChar</code> occurs in the character sequence represented by <code>seq</code> <code>CharSequence</code> object, then the index (in Unicode code units) of the first such occurrence is returned. For values of <code>searchChar</code> in the range from 0 to 0xFFFF (inclusive), this is the smallest value <i>k</i> such that: <blockquote><pre> this.charAt(<i>k</i>) == searchChar </pre></blockquote> is true. For other values of <code>searchChar</code>, it is the smallest value <i>k</i> such that: <blockquote><pre> this.codePointAt(<i>k</i>) == searchChar </pre></blockquote> is true. In either case, if no such character occurs in <code>seq</code>, then {@code INDEX_NOT_FOUND (-1)} is returned. <p>Furthermore, a {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.</p> <pre> StringUtils.indexOf(null, *) = -1 StringUtils.indexOf("", *) = -1 StringUtils.indexOf("aabaabaa", 'a') = 0 StringUtils.indexOf("aabaabaa", 'b') = 2 </pre> @param seq the CharSequence to check, may be null @param searchChar the character to find @return the first index of the search character, -1 if no match or {@code null} string input @since 2.0 @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int) @since 3.6 Updated {@link CharSequenceUtils} call to behave more like <code>String</code>
[ "Returns", "the", "index", "within", "<code", ">", "seq<", "/", "code", ">", "of", "the", "first", "occurrence", "of", "the", "specified", "character", ".", "If", "a", "character", "with", "value", "<code", ">", "searchChar<", "/", "code", ">", "occurs", ...
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L1324-L1329
VoltDB/voltdb
src/frontend/org/voltdb/client/ClientStatsContext.java
ClientStatsContext.getCompleteStats
public Map<Long, Map<String, ClientStats>> getCompleteStats() { Map<Long, Map<String, ClientStats>> retval = new TreeMap<Long, Map<String, ClientStats>>(); for (Entry<Long, Map<String, ClientStats>> e : m_current.entrySet()) { if (m_baseline.containsKey(e.getKey())) { retval.put(e.getKey(), diff(e.getValue(), m_baseline.get(e.getKey()))); } else { retval.put(e.getKey(), dup(e.getValue())); } } // reset the timestamp fields to reflect the difference for (Entry<Long, Map<String, ClientStats>> e : retval.entrySet()) { for (Entry<String, ClientStats> e2 : e.getValue().entrySet()) { ClientStats cs = e2.getValue(); cs.m_startTS = m_baselineTS; cs.m_endTS = m_currentTS; assert(cs.m_startTS != Long.MAX_VALUE); assert(cs.m_endTS != Long.MIN_VALUE); } } return retval; }
java
public Map<Long, Map<String, ClientStats>> getCompleteStats() { Map<Long, Map<String, ClientStats>> retval = new TreeMap<Long, Map<String, ClientStats>>(); for (Entry<Long, Map<String, ClientStats>> e : m_current.entrySet()) { if (m_baseline.containsKey(e.getKey())) { retval.put(e.getKey(), diff(e.getValue(), m_baseline.get(e.getKey()))); } else { retval.put(e.getKey(), dup(e.getValue())); } } // reset the timestamp fields to reflect the difference for (Entry<Long, Map<String, ClientStats>> e : retval.entrySet()) { for (Entry<String, ClientStats> e2 : e.getValue().entrySet()) { ClientStats cs = e2.getValue(); cs.m_startTS = m_baselineTS; cs.m_endTS = m_currentTS; assert(cs.m_startTS != Long.MAX_VALUE); assert(cs.m_endTS != Long.MIN_VALUE); } } return retval; }
[ "public", "Map", "<", "Long", ",", "Map", "<", "String", ",", "ClientStats", ">", ">", "getCompleteStats", "(", ")", "{", "Map", "<", "Long", ",", "Map", "<", "String", ",", "ClientStats", ">", ">", "retval", "=", "new", "TreeMap", "<", "Long", ",", ...
Return a map of maps by connection id. Each sub-map maps procedure names to {@link ClientStats} instances. Note that connection id is unique, while hostname and port may not be. Hostname and port will be included in the {@link ClientStats} instance data. Each {@link ClientStats} instance will apply to the time period currently covered by the context. This is full set of data available from this context instance. @return A map from connection id to {@link ClientStats} instances.
[ "Return", "a", "map", "of", "maps", "by", "connection", "id", ".", "Each", "sub", "-", "map", "maps", "procedure", "names", "to", "{", "@link", "ClientStats", "}", "instances", ".", "Note", "that", "connection", "id", "is", "unique", "while", "hostname", ...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientStatsContext.java#L180-L205
landawn/AbacusUtil
src/com/landawn/abacus/util/BiIterator.java
BiIterator.forEachRemaining
@Override @Deprecated public void forEachRemaining(java.util.function.Consumer<? super Pair<A, B>> action) { super.forEachRemaining(action); }
java
@Override @Deprecated public void forEachRemaining(java.util.function.Consumer<? super Pair<A, B>> action) { super.forEachRemaining(action); }
[ "@", "Override", "@", "Deprecated", "public", "void", "forEachRemaining", "(", "java", ".", "util", ".", "function", ".", "Consumer", "<", "?", "super", "Pair", "<", "A", ",", "B", ">", ">", "action", ")", "{", "super", ".", "forEachRemaining", "(", "a...
It's preferred to call <code>forEachRemaining(Try.BiConsumer)</code> to avoid the create the unnecessary <code>Pair</code> Objects. @deprecated
[ "It", "s", "preferred", "to", "call", "<code", ">", "forEachRemaining", "(", "Try", ".", "BiConsumer", ")", "<", "/", "code", ">", "to", "avoid", "the", "create", "the", "unnecessary", "<code", ">", "Pair<", "/", "code", ">", "Objects", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/BiIterator.java#L423-L427
Qkyrie/Markdown2Pdf
src/main/java/com/qkyrie/markdown2pdf/internal/converting/HtmlCleaner.java
HtmlCleaner.cleanWithInputEncoding
public String cleanWithInputEncoding(String htmlFile, String inputEncoding) throws ConversionException { return clean(htmlFile, inputEncoding, null); }
java
public String cleanWithInputEncoding(String htmlFile, String inputEncoding) throws ConversionException { return clean(htmlFile, inputEncoding, null); }
[ "public", "String", "cleanWithInputEncoding", "(", "String", "htmlFile", ",", "String", "inputEncoding", ")", "throws", "ConversionException", "{", "return", "clean", "(", "htmlFile", ",", "inputEncoding", ",", "null", ")", ";", "}" ]
Clean-up HTML code with specified input encoding, asumes UTF-8 as output encoding. @param htmlFile @param inputEncoding @return @throws ConversionException
[ "Clean", "-", "up", "HTML", "code", "with", "specified", "input", "encoding", "asumes", "UTF", "-", "8", "as", "output", "encoding", "." ]
train
https://github.com/Qkyrie/Markdown2Pdf/blob/f89167ddcfad96c64b3371a6dfb1cd11c5bb1b5a/src/main/java/com/qkyrie/markdown2pdf/internal/converting/HtmlCleaner.java#L49-L51
facebookarchive/hadoop-20
src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/SimpleSeekableFormatOutputStream.java
SimpleSeekableFormatOutputStream.write
@Override public void write(byte[] b, int start, int length) throws IOException { currentDataSegmentBuffer.write(b, start, length); flushIfNeeded(); }
java
@Override public void write(byte[] b, int start, int length) throws IOException { currentDataSegmentBuffer.write(b, start, length); flushIfNeeded(); }
[ "@", "Override", "public", "void", "write", "(", "byte", "[", "]", "b", ",", "int", "start", ",", "int", "length", ")", "throws", "IOException", "{", "currentDataSegmentBuffer", ".", "write", "(", "b", ",", "start", ",", "length", ")", ";", "flushIfNeede...
This function makes sure the whole buffer is written into the same data segment.
[ "This", "function", "makes", "sure", "the", "whole", "buffer", "is", "written", "into", "the", "same", "data", "segment", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/SimpleSeekableFormatOutputStream.java#L111-L115
apache/groovy
src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.leftShift
public static Writer leftShift(OutputStream self, Object value) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter(self); leftShift(writer, value); return writer; }
java
public static Writer leftShift(OutputStream self, Object value) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter(self); leftShift(writer, value); return writer; }
[ "public", "static", "Writer", "leftShift", "(", "OutputStream", "self", ",", "Object", "value", ")", "throws", "IOException", "{", "OutputStreamWriter", "writer", "=", "new", "FlushingStreamWriter", "(", "self", ")", ";", "leftShift", "(", "writer", ",", "value"...
Overloads the leftShift operator to provide an append mechanism to add values to a stream. @param self an OutputStream @param value a value to append @return a Writer @throws java.io.IOException if an I/O error occurs. @since 1.0
[ "Overloads", "the", "leftShift", "operator", "to", "provide", "an", "append", "mechanism", "to", "add", "values", "to", "a", "stream", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L180-L184
CenturyLinkCloud/mdw
mdw-services/src/com/centurylink/mdw/services/process/ProcessEngineDriver.java
ProcessEngineDriver.invokeServiceAsSubprocess
public Map<String,String> invokeServiceAsSubprocess(Long processId, Long parentProcInstId, String masterRequestId, Map<String,String> parameters, int performance_level) throws Exception { long startMilli = System.currentTimeMillis(); if (performance_level<=0) performance_level = getProcessDefinition(processId).getPerformanceLevel(); if (performance_level<=0) performance_level = default_performance_level_service; EngineDataAccess edao = EngineDataAccessCache.getInstance(true, performance_level); InternalMessenger msgBroker = MessengerFactory.newInternalMessenger(); msgBroker.setCacheOption(InternalMessenger.CACHE_ONLY); ProcessExecutor engine = new ProcessExecutor(edao, msgBroker, true); ProcessInstance mainProcessInst = executeServiceProcess(engine, processId, OwnerType.PROCESS_INSTANCE, parentProcInstId, masterRequestId, parameters, null, null, null); boolean completed = mainProcessInst.getStatusCode().equals(WorkStatus.STATUS_COMPLETED); Map<String,String> resp = completed?engine.getOutPutParameters(mainProcessInst.getId(), processId):null; long stopMilli = System.currentTimeMillis(); logger.info("Synchronous process executed in " + ((stopMilli-startMilli)/1000.0) + " seconds at performance level " + performance_level); if (completed) return resp; if (lastException==null) throw new Exception("Process instance not completed"); throw lastException; }
java
public Map<String,String> invokeServiceAsSubprocess(Long processId, Long parentProcInstId, String masterRequestId, Map<String,String> parameters, int performance_level) throws Exception { long startMilli = System.currentTimeMillis(); if (performance_level<=0) performance_level = getProcessDefinition(processId).getPerformanceLevel(); if (performance_level<=0) performance_level = default_performance_level_service; EngineDataAccess edao = EngineDataAccessCache.getInstance(true, performance_level); InternalMessenger msgBroker = MessengerFactory.newInternalMessenger(); msgBroker.setCacheOption(InternalMessenger.CACHE_ONLY); ProcessExecutor engine = new ProcessExecutor(edao, msgBroker, true); ProcessInstance mainProcessInst = executeServiceProcess(engine, processId, OwnerType.PROCESS_INSTANCE, parentProcInstId, masterRequestId, parameters, null, null, null); boolean completed = mainProcessInst.getStatusCode().equals(WorkStatus.STATUS_COMPLETED); Map<String,String> resp = completed?engine.getOutPutParameters(mainProcessInst.getId(), processId):null; long stopMilli = System.currentTimeMillis(); logger.info("Synchronous process executed in " + ((stopMilli-startMilli)/1000.0) + " seconds at performance level " + performance_level); if (completed) return resp; if (lastException==null) throw new Exception("Process instance not completed"); throw lastException; }
[ "public", "Map", "<", "String", ",", "String", ">", "invokeServiceAsSubprocess", "(", "Long", "processId", ",", "Long", "parentProcInstId", ",", "String", "masterRequestId", ",", "Map", "<", "String", ",", "String", ">", "parameters", ",", "int", "performance_le...
Called internally by invoke subprocess activities to call service processes as subprocesses of regular processes. @return map of output parameters (can be empty hash, but not null);
[ "Called", "internally", "by", "invoke", "subprocess", "activities", "to", "call", "service", "processes", "as", "subprocesses", "of", "regular", "processes", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/process/ProcessEngineDriver.java#L780-L801
TakahikoKawasaki/nv-cipher
src/main/java/com/neovisionaries/security/AESCipher.java
AESCipher.setKey
public AESCipher setKey(byte[] key, byte[] iv) { SecretKey secretKey = Utils.createSecretKeySpec(key, getAlgorithm(), 16); IvParameterSpec spec = null; if (iv != null) { spec = Utils.createIvParameterSpec(iv, 16); } return setKey(secretKey, spec); }
java
public AESCipher setKey(byte[] key, byte[] iv) { SecretKey secretKey = Utils.createSecretKeySpec(key, getAlgorithm(), 16); IvParameterSpec spec = null; if (iv != null) { spec = Utils.createIvParameterSpec(iv, 16); } return setKey(secretKey, spec); }
[ "public", "AESCipher", "setKey", "(", "byte", "[", "]", "key", ",", "byte", "[", "]", "iv", ")", "{", "SecretKey", "secretKey", "=", "Utils", ".", "createSecretKeySpec", "(", "key", ",", "getAlgorithm", "(", ")", ",", "16", ")", ";", "IvParameterSpec", ...
Set cipher initialization parameters. Other {@code setKey} method variants call this method. <p> This method constructs a {@link SecretKey} instance and an {@link IvParameterSpec} instance from the arguments, and then calls {@link #setKey(SecretKey, IvParameterSpec)}. </p> @param key Secret key. If {@code null} is given, {@code new byte[16]} is used. If not {@code null} and the length is less than 16, a byte array of size 16 is allocated and the content of {@code key} is copied to the newly allocated byte array, and the resultant byte array is used. Even if the length is greater than 16, only the first 16 bytes are used to construct a {@code SecretKey} instance. @param iv Initial vector. If {@code null} is given, {@code null} is used, meaning that {@code IvParameterSepc} argument passed to {@link #setKey(SecretKey, IvParameterSpec)} is {@code null}. In that case, you will want to obtain the auto-generated initial vector by calling {@link #getCipher() getCipher()}{@code .}{@link javax.crypto.Cipher#getIV() getIV()} in order to decrypt the encrypted data. <p> If {@code iv} is not {@code null} and the length is less than 16, a byte array of size 16 is allocated and the content of {@code iv} is copied to the newly allocated byte array, and the resultant byte array is used. Even if the length is greater than 16, only the first 16 bytes are used to construct an {@code IvParameterSpec} instance. </p> @return {@code this} object.
[ "Set", "cipher", "initialization", "parameters", ".", "Other", "{", "@code", "setKey", "}", "method", "variants", "call", "this", "method", "." ]
train
https://github.com/TakahikoKawasaki/nv-cipher/blob/d01aa4f53611e2724ae03633060f55bacf549175/src/main/java/com/neovisionaries/security/AESCipher.java#L274-L285
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java
MappingTrackArchiver.getAssemblyFiles
public AssemblyFiles getAssemblyFiles(MavenSession session) { AssemblyFiles ret = new AssemblyFiles(new File(getDestFile().getParentFile(), assemblyName)); // Where the 'real' files are copied to for (Addition addition : added) { Object resource = addition.resource; File target = new File(ret.getAssemblyDirectory(), addition.destination); if (resource instanceof File && addition.destination != null) { addFileEntry(ret, session, (File) resource, target); } else if (resource instanceof PlexusIoFileResource) { addFileEntry(ret, session, ((PlexusIoFileResource) resource).getFile(), target); } else if (resource instanceof FileSet) { FileSet fs = (FileSet) resource; DirectoryScanner ds = new DirectoryScanner(); File base = addition.directory; ds.setBasedir(base); ds.setIncludes(fs.getIncludes()); ds.setExcludes(fs.getExcludes()); ds.setCaseSensitive(fs.isCaseSensitive()); ds.scan(); for (String f : ds.getIncludedFiles()) { File source = new File(base, f); File subTarget = new File(target, f); addFileEntry(ret, session, source, subTarget); } } else { throw new IllegalStateException("Unknown resource type " + resource.getClass() + ": " + resource); } } return ret; }
java
public AssemblyFiles getAssemblyFiles(MavenSession session) { AssemblyFiles ret = new AssemblyFiles(new File(getDestFile().getParentFile(), assemblyName)); // Where the 'real' files are copied to for (Addition addition : added) { Object resource = addition.resource; File target = new File(ret.getAssemblyDirectory(), addition.destination); if (resource instanceof File && addition.destination != null) { addFileEntry(ret, session, (File) resource, target); } else if (resource instanceof PlexusIoFileResource) { addFileEntry(ret, session, ((PlexusIoFileResource) resource).getFile(), target); } else if (resource instanceof FileSet) { FileSet fs = (FileSet) resource; DirectoryScanner ds = new DirectoryScanner(); File base = addition.directory; ds.setBasedir(base); ds.setIncludes(fs.getIncludes()); ds.setExcludes(fs.getExcludes()); ds.setCaseSensitive(fs.isCaseSensitive()); ds.scan(); for (String f : ds.getIncludedFiles()) { File source = new File(base, f); File subTarget = new File(target, f); addFileEntry(ret, session, source, subTarget); } } else { throw new IllegalStateException("Unknown resource type " + resource.getClass() + ": " + resource); } } return ret; }
[ "public", "AssemblyFiles", "getAssemblyFiles", "(", "MavenSession", "session", ")", "{", "AssemblyFiles", "ret", "=", "new", "AssemblyFiles", "(", "new", "File", "(", "getDestFile", "(", ")", ".", "getParentFile", "(", ")", ",", "assemblyName", ")", ")", ";", ...
Get all files depicted by this assembly. @return assembled files
[ "Get", "all", "files", "depicted", "by", "this", "assembly", "." ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java#L59-L88