repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
j256/ormlite-core
src/main/java/com/j256/ormlite/stmt/QueryBuilder.java
QueryBuilder.matchJoinedFields
private void matchJoinedFields(JoinInfo joinInfo, QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException { for (FieldType fieldType : tableInfo.getFieldTypes()) { // if this is a foreign field and its foreign field is the same as the other's id FieldType foreignRefField = fieldType.getForeignRefField(); if (fieldType.isForeign() && foreignRefField.equals(joinedQueryBuilder.tableInfo.getIdField())) { joinInfo.localField = fieldType; joinInfo.remoteField = foreignRefField; return; } } // if this other field is a foreign field and its foreign-id field is our id for (FieldType fieldType : joinedQueryBuilder.tableInfo.getFieldTypes()) { if (fieldType.isForeign() && fieldType.getForeignIdField().equals(idField)) { joinInfo.localField = idField; joinInfo.remoteField = fieldType; return; } } throw new SQLException("Could not find a foreign " + tableInfo.getDataClass() + " field in " + joinedQueryBuilder.tableInfo.getDataClass() + " or vice versa"); }
java
private void matchJoinedFields(JoinInfo joinInfo, QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException { for (FieldType fieldType : tableInfo.getFieldTypes()) { // if this is a foreign field and its foreign field is the same as the other's id FieldType foreignRefField = fieldType.getForeignRefField(); if (fieldType.isForeign() && foreignRefField.equals(joinedQueryBuilder.tableInfo.getIdField())) { joinInfo.localField = fieldType; joinInfo.remoteField = foreignRefField; return; } } // if this other field is a foreign field and its foreign-id field is our id for (FieldType fieldType : joinedQueryBuilder.tableInfo.getFieldTypes()) { if (fieldType.isForeign() && fieldType.getForeignIdField().equals(idField)) { joinInfo.localField = idField; joinInfo.remoteField = fieldType; return; } } throw new SQLException("Could not find a foreign " + tableInfo.getDataClass() + " field in " + joinedQueryBuilder.tableInfo.getDataClass() + " or vice versa"); }
[ "private", "void", "matchJoinedFields", "(", "JoinInfo", "joinInfo", ",", "QueryBuilder", "<", "?", ",", "?", ">", "joinedQueryBuilder", ")", "throws", "SQLException", "{", "for", "(", "FieldType", "fieldType", ":", "tableInfo", ".", "getFieldTypes", "(", ")", ...
Match up our joined fields so we can throw a nice exception immediately if you can't join with this type.
[ "Match", "up", "our", "joined", "fields", "so", "we", "can", "throw", "a", "nice", "exception", "immediately", "if", "you", "can", "t", "join", "with", "this", "type", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/QueryBuilder.java#L612-L633
aws/aws-sdk-java
aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/AddOperations.java
AddOperations.getHttpStatusCode
private Integer getHttpStatusCode(ErrorMap error, Shape shape) { final Integer httpStatusCode = getHttpStatusCode(error.getErrorTrait()); return httpStatusCode == null ? getHttpStatusCode(shape.getErrorTrait()) : httpStatusCode; }
java
private Integer getHttpStatusCode(ErrorMap error, Shape shape) { final Integer httpStatusCode = getHttpStatusCode(error.getErrorTrait()); return httpStatusCode == null ? getHttpStatusCode(shape.getErrorTrait()) : httpStatusCode; }
[ "private", "Integer", "getHttpStatusCode", "(", "ErrorMap", "error", ",", "Shape", "shape", ")", "{", "final", "Integer", "httpStatusCode", "=", "getHttpStatusCode", "(", "error", ".", "getErrorTrait", "(", ")", ")", ";", "return", "httpStatusCode", "==", "null"...
Get HTTP status code either from error trait on the operation reference or the error trait on the shape. @param error ErrorMap on operation reference. @param shape Error shape. @return HTTP status code or null if not present.
[ "Get", "HTTP", "status", "code", "either", "from", "error", "trait", "on", "the", "operation", "reference", "or", "the", "error", "trait", "on", "the", "shape", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/AddOperations.java#L130-L133
elki-project/elki
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/similarityfunction/kernel/KernelMatrix.java
KernelMatrix.getSquaredDistance
public double getSquaredDistance(final DBIDRef id1, final DBIDRef id2) { final int o1 = idmap.getOffset(id1), o2 = idmap.getOffset(id2); return kernel[o1][o1] + kernel[o2][o2] - 2 * kernel[o1][o2]; }
java
public double getSquaredDistance(final DBIDRef id1, final DBIDRef id2) { final int o1 = idmap.getOffset(id1), o2 = idmap.getOffset(id2); return kernel[o1][o1] + kernel[o2][o2] - 2 * kernel[o1][o2]; }
[ "public", "double", "getSquaredDistance", "(", "final", "DBIDRef", "id1", ",", "final", "DBIDRef", "id2", ")", "{", "final", "int", "o1", "=", "idmap", ".", "getOffset", "(", "id1", ")", ",", "o2", "=", "idmap", ".", "getOffset", "(", "id2", ")", ";", ...
Returns the squared kernel distance between the two specified objects. @param id1 first ObjectID @param id2 second ObjectID @return the distance between the two objects
[ "Returns", "the", "squared", "kernel", "distance", "between", "the", "two", "specified", "objects", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/similarityfunction/kernel/KernelMatrix.java#L229-L232
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/optional/Html.java
Html.neckoParse
public static Object neckoParse(final ChainedHttpConfig config, final FromServer fromServer) { try { final XMLReader p = new org.cyberneko.html.parsers.SAXParser(); p.setEntityResolver(NativeHandlers.Parsers.catalogResolver); return new XmlSlurper(p).parse(new InputStreamReader(fromServer.getInputStream(), fromServer.getCharset())); } catch (IOException | SAXException ex) { throw new TransportingException(ex); } }
java
public static Object neckoParse(final ChainedHttpConfig config, final FromServer fromServer) { try { final XMLReader p = new org.cyberneko.html.parsers.SAXParser(); p.setEntityResolver(NativeHandlers.Parsers.catalogResolver); return new XmlSlurper(p).parse(new InputStreamReader(fromServer.getInputStream(), fromServer.getCharset())); } catch (IOException | SAXException ex) { throw new TransportingException(ex); } }
[ "public", "static", "Object", "neckoParse", "(", "final", "ChainedHttpConfig", "config", ",", "final", "FromServer", "fromServer", ")", "{", "try", "{", "final", "XMLReader", "p", "=", "new", "org", ".", "cyberneko", ".", "html", ".", "parsers", ".", "SAXPar...
Method that provides an HTML parser for response configuration (uses necko parser). @param config the chained configuration @param fromServer the server response adapter @return the parsed HTML content (a {@link groovy.util.slurpersupport.GPathResult} object)
[ "Method", "that", "provides", "an", "HTML", "parser", "for", "response", "configuration", "(", "uses", "necko", "parser", ")", "." ]
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/optional/Html.java#L56-L64
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/constraint/OR.java
OR.satisfies
@Override public boolean satisfies(Match match, int... ind) { for (MappedConst mc : con) { if (mc.satisfies(match, ind)) return true; } return false; }
java
@Override public boolean satisfies(Match match, int... ind) { for (MappedConst mc : con) { if (mc.satisfies(match, ind)) return true; } return false; }
[ "@", "Override", "public", "boolean", "satisfies", "(", "Match", "match", ",", "int", "...", "ind", ")", "{", "for", "(", "MappedConst", "mc", ":", "con", ")", "{", "if", "(", "mc", ".", "satisfies", "(", "match", ",", "ind", ")", ")", "return", "t...
Checks if any of the wrapped constraints satisfy. @param match current pattern match @param ind mapped indices @return true if any of the wrapped constraints satisfy
[ "Checks", "if", "any", "of", "the", "wrapped", "constraints", "satisfy", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/OR.java#L39-L47
pwall567/jsonutil
src/main/java/net/pwall/json/JSONObject.java
JSONObject.putValue
public JSONObject putValue(String key, double value) { put(key, JSONDouble.valueOf(value)); return this; }
java
public JSONObject putValue(String key, double value) { put(key, JSONDouble.valueOf(value)); return this; }
[ "public", "JSONObject", "putValue", "(", "String", "key", ",", "double", "value", ")", "{", "put", "(", "key", ",", "JSONDouble", ".", "valueOf", "(", "value", ")", ")", ";", "return", "this", ";", "}" ]
Add a {@link JSONDouble} representing the supplied {@code double} to the {@code JSONObject}. @param key the key to use when storing the value @param value the value @return {@code this} (for chaining) @throws NullPointerException if key is {@code null}
[ "Add", "a", "{", "@link", "JSONDouble", "}", "representing", "the", "supplied", "{", "@code", "double", "}", "to", "the", "{", "@code", "JSONObject", "}", "." ]
train
https://github.com/pwall567/jsonutil/blob/dd5960b9b0bcc9acfe6c52b884fffd9ee5f422fe/src/main/java/net/pwall/json/JSONObject.java#L158-L161
JetBrains/xodus
openAPI/src/main/java/jetbrains/exodus/env/EnvironmentConfig.java
EnvironmentConfig.setGcFilesInterval
public EnvironmentConfig setGcFilesInterval(final int files) throws InvalidSettingException { if (files < 1) { throw new InvalidSettingException("Invalid number of files: " + files); } return setSetting(GC_FILES_INTERVAL, files); }
java
public EnvironmentConfig setGcFilesInterval(final int files) throws InvalidSettingException { if (files < 1) { throw new InvalidSettingException("Invalid number of files: " + files); } return setSetting(GC_FILES_INTERVAL, files); }
[ "public", "EnvironmentConfig", "setGcFilesInterval", "(", "final", "int", "files", ")", "throws", "InvalidSettingException", "{", "if", "(", "files", "<", "1", ")", "{", "throw", "new", "InvalidSettingException", "(", "\"Invalid number of files: \"", "+", "files", "...
Sets the number of new {@code Log} files (.xd files) that must be created to trigger if necessary (if database utilization is not sufficient) the next background cleaning cycle (single run of the database garbage collector) after the previous cycle finished. Default value is {@code 3}, i.e. GC can start after each 3 newly created {@code Log} files. Cannot be less than {@code 1}. <p>Mutable at runtime: yes @param files number of new .xd files that must be created to trigger the next background cleaning cycle @return this {@code EnvironmentConfig} instance @throws InvalidSettingException {@code files} is less than {@code 1}
[ "Sets", "the", "number", "of", "new", "{", "@code", "Log", "}", "files", "(", ".", "xd", "files", ")", "that", "must", "be", "created", "to", "trigger", "if", "necessary", "(", "if", "database", "utilization", "is", "not", "sufficient", ")", "the", "ne...
train
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/openAPI/src/main/java/jetbrains/exodus/env/EnvironmentConfig.java#L1956-L1961
Microsoft/malmo
Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java
JSONWorldDataHelper.buildLifeStats
public static void buildLifeStats(JsonObject json, EntityPlayerMP player) { json.addProperty("Life", player.getHealth()); json.addProperty("Score", player.getScore()); // Might always be the same as XP? json.addProperty("Food", player.getFoodStats().getFoodLevel()); json.addProperty("XP", player.experienceTotal); json.addProperty("IsAlive", !player.isDead); json.addProperty("Air", player.getAir()); json.addProperty("Name", player.getName()); }
java
public static void buildLifeStats(JsonObject json, EntityPlayerMP player) { json.addProperty("Life", player.getHealth()); json.addProperty("Score", player.getScore()); // Might always be the same as XP? json.addProperty("Food", player.getFoodStats().getFoodLevel()); json.addProperty("XP", player.experienceTotal); json.addProperty("IsAlive", !player.isDead); json.addProperty("Air", player.getAir()); json.addProperty("Name", player.getName()); }
[ "public", "static", "void", "buildLifeStats", "(", "JsonObject", "json", ",", "EntityPlayerMP", "player", ")", "{", "json", ".", "addProperty", "(", "\"Life\"", ",", "player", ".", "getHealth", "(", ")", ")", ";", "json", ".", "addProperty", "(", "\"Score\""...
Builds the basic life world data to be used as observation signals by the listener. @param json a JSON object into which the life stats will be added.
[ "Builds", "the", "basic", "life", "world", "data", "to", "be", "used", "as", "observation", "signals", "by", "the", "listener", "." ]
train
https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java#L124-L133
calimero-project/calimero-core
src/tuwien/auto/calimero/link/medium/RawFrameFactory.java
RawFrameFactory.createTP1
public static RawFrame createTP1(final byte[] data, final int offset) throws KNXFormatException { final int ctrl = data[offset] & 0xff; // parse control field and check if valid if ((ctrl & 0x10) == 0x10) { if ((ctrl & 0x40) == 0x00) return new TP1LData(data, offset); else if (ctrl == 0xF0) return new TP1LPollData(data, offset); throw new KNXFormatException("invalid raw frame control field", ctrl); } return new TP1Ack(data, offset); }
java
public static RawFrame createTP1(final byte[] data, final int offset) throws KNXFormatException { final int ctrl = data[offset] & 0xff; // parse control field and check if valid if ((ctrl & 0x10) == 0x10) { if ((ctrl & 0x40) == 0x00) return new TP1LData(data, offset); else if (ctrl == 0xF0) return new TP1LPollData(data, offset); throw new KNXFormatException("invalid raw frame control field", ctrl); } return new TP1Ack(data, offset); }
[ "public", "static", "RawFrame", "createTP1", "(", "final", "byte", "[", "]", "data", ",", "final", "int", "offset", ")", "throws", "KNXFormatException", "{", "final", "int", "ctrl", "=", "data", "[", "offset", "]", "&", "0xff", ";", "// parse control field a...
Creates a raw frame out of a byte array for the TP1 communication medium. @param data byte array containing the TP1 raw frame structure @param offset start offset of frame structure in <code>data</code>, 0 &lt;= offset &lt; <code>data.length</code> @return the created TP1 raw frame @throws KNXFormatException on no valid frame structure
[ "Creates", "a", "raw", "frame", "out", "of", "a", "byte", "array", "for", "the", "TP1", "communication", "medium", "." ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/link/medium/RawFrameFactory.java#L91-L103
infinispan/infinispan
lucene/directory-provider/src/main/java/org/infinispan/hibernate/search/util/configuration/impl/ConfigurationParseHelper.java
ConfigurationParseHelper.parseInt
public static int parseInt(String value, String errorMsgOnParseFailure) { if (value == null) { throw new SearchException(errorMsgOnParseFailure); } else { try { return Integer.parseInt(value.trim()); } catch (NumberFormatException nfe) { throw log.getInvalidIntegerValueException(errorMsgOnParseFailure, nfe); } } }
java
public static int parseInt(String value, String errorMsgOnParseFailure) { if (value == null) { throw new SearchException(errorMsgOnParseFailure); } else { try { return Integer.parseInt(value.trim()); } catch (NumberFormatException nfe) { throw log.getInvalidIntegerValueException(errorMsgOnParseFailure, nfe); } } }
[ "public", "static", "int", "parseInt", "(", "String", "value", ",", "String", "errorMsgOnParseFailure", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "SearchException", "(", "errorMsgOnParseFailure", ")", ";", "}", "else", "{", "try",...
Parses a string into an integer value. @param value a string containing an int value to parse @param errorMsgOnParseFailure message being wrapped in a SearchException if value is {@code null} or not an integer @return the parsed integer value @throws SearchException both for null values and for Strings not containing a valid int.
[ "Parses", "a", "string", "into", "an", "integer", "value", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lucene/directory-provider/src/main/java/org/infinispan/hibernate/search/util/configuration/impl/ConfigurationParseHelper.java#L73-L83
SG-O/miIO
src/main/java/de/sg_o/app/miio/vacuum/Vacuum.java
Vacuum.resetConsumable
public boolean resetConsumable(VacuumConsumableStatus.Names consumable) throws CommandExecutionException { if (consumable == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS); JSONArray params = new JSONArray(); params.put(consumable.toString()); return sendOk("reset_consumable", params); }
java
public boolean resetConsumable(VacuumConsumableStatus.Names consumable) throws CommandExecutionException { if (consumable == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS); JSONArray params = new JSONArray(); params.put(consumable.toString()); return sendOk("reset_consumable", params); }
[ "public", "boolean", "resetConsumable", "(", "VacuumConsumableStatus", ".", "Names", "consumable", ")", "throws", "CommandExecutionException", "{", "if", "(", "consumable", "==", "null", ")", "throw", "new", "CommandExecutionException", "(", "CommandExecutionException", ...
Reset a vacuums consumable. @param consumable The consumable to reset @return True if the consumable has been reset. @throws CommandExecutionException When there has been a error during the communication or the response was invalid.
[ "Reset", "a", "vacuums", "consumable", "." ]
train
https://github.com/SG-O/miIO/blob/f352dbd2a699d2cdb1b412ca5e6cbb0c38ca779b/src/main/java/de/sg_o/app/miio/vacuum/Vacuum.java#L99-L104
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addNotEqualToColumn
public void addNotEqualToColumn(String attribute, String colName) { // PAW // FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias()); FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getUserAlias(attribute)); c.setTranslateField(false); addSelectionCriteria(c); }
java
public void addNotEqualToColumn(String attribute, String colName) { // PAW // FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias()); FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getUserAlias(attribute)); c.setTranslateField(false); addSelectionCriteria(c); }
[ "public", "void", "addNotEqualToColumn", "(", "String", "attribute", ",", "String", "colName", ")", "{", "// PAW\r", "// FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias());\r", "FieldCriteria", "c", "=", "FieldCriteria", ".", "buildNotEqualToC...
Adds and equals (<>) criteria for column comparison. The column Name will NOT be translated. <br> name <> T_BOSS.LASTNMAE @param attribute The field name to be used @param colName The name of the column to compare with
[ "Adds", "and", "equals", "(", "<", ">", ")", "criteria", "for", "column", "comparison", ".", "The", "column", "Name", "will", "NOT", "be", "translated", ".", "<br", ">", "name", "<", ">", "T_BOSS", ".", "LASTNMAE" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L374-L381
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.writePropertyObject
public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } }
java
public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } }
[ "public", "void", "writePropertyObject", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "CmsProperty", "property", ")", "throws", "CmsException", ",", "CmsSecurityException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbCo...
Writes a property for a specified resource.<p> @param context the current request context @param resource the resource to write the property for @param property the property to write @throws CmsException if something goes wrong @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) @see CmsObject#writePropertyObject(String, CmsProperty) @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty)
[ "Writes", "a", "property", "for", "a", "specified", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6802-L6818
tomgibara/bits
src/main/java/com/tomgibara/bits/FileBitReaderFactory.java
FileBitReaderFactory.openReader
public BitReader openReader() throws BitStreamException { try { switch(mode) { case MEMORY : return new ByteArrayBitReader(getBytes()); case STREAM : return new InputStreamBitReader(new BufferedInputStream(new FileInputStream(file), bufferSize)); case CHANNEL: return new FileChannelBitReader(new RandomAccessFile(file, "r").getChannel(), ByteBuffer.allocateDirect(bufferSize)); default: throw new IllegalStateException("Unexpected mode: " + mode); } } catch (IOException e) { throw new BitStreamException(e); } }
java
public BitReader openReader() throws BitStreamException { try { switch(mode) { case MEMORY : return new ByteArrayBitReader(getBytes()); case STREAM : return new InputStreamBitReader(new BufferedInputStream(new FileInputStream(file), bufferSize)); case CHANNEL: return new FileChannelBitReader(new RandomAccessFile(file, "r").getChannel(), ByteBuffer.allocateDirect(bufferSize)); default: throw new IllegalStateException("Unexpected mode: " + mode); } } catch (IOException e) { throw new BitStreamException(e); } }
[ "public", "BitReader", "openReader", "(", ")", "throws", "BitStreamException", "{", "try", "{", "switch", "(", "mode", ")", "{", "case", "MEMORY", ":", "return", "new", "ByteArrayBitReader", "(", "getBytes", "(", ")", ")", ";", "case", "STREAM", ":", "retu...
Opens a reader over the bits of the file. The characteristics of the returned reader are determined by the {@link Mode} in which the factory was created. Any reader returned by this method SHOULD eventually be closed by passing it to the {@link #closeReader(BitReader)} method. Not doing so may risk leaking system resources. @return a new reader over the file @throws BitStreamException if the reader could not be opened, typically because the file could not be read
[ "Opens", "a", "reader", "over", "the", "bits", "of", "the", "file", ".", "The", "characteristics", "of", "the", "returned", "reader", "are", "determined", "by", "the", "{", "@link", "Mode", "}", "in", "which", "the", "factory", "was", "created", "." ]
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/FileBitReaderFactory.java#L165-L176
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java
IndexChangeAdapters.forMixinTypes
public static IndexChangeAdapter forMixinTypes( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { return new MixinTypesChangeAdapter(context, matcher, workspaceName, index); }
java
public static IndexChangeAdapter forMixinTypes( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { return new MixinTypesChangeAdapter(context, matcher, workspaceName, index); }
[ "public", "static", "IndexChangeAdapter", "forMixinTypes", "(", "ExecutionContext", "context", ",", "NodeTypePredicate", "matcher", ",", "String", "workspaceName", ",", "ProvidedIndex", "<", "?", ">", "index", ")", "{", "return", "new", "MixinTypesChangeAdapter", "(",...
Create an {@link IndexChangeAdapter} implementation that handles the "jcr:mixinTypes" property. @param context the execution context; may not be null @param matcher the node type matcher used to determine which nodes should be included in the index; may not be null @param workspaceName the name of the workspace; may not be null @param index the local index that should be used; may not be null @return the new {@link IndexChangeAdapter}; never null
[ "Create", "an", "{", "@link", "IndexChangeAdapter", "}", "implementation", "that", "handles", "the", "jcr", ":", "mixinTypes", "property", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java#L160-L165
actorapp/actor-platform
actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java
MarkdownParser.findSpanStart
private int findSpanStart(TextCursor cursor, int limit) { for (int i = cursor.currentOffset; i < limit; i++) { char c = cursor.text.charAt(i); if (c == '*' || c == '_') { // Check prev and next symbols if (isGoodAnchor(cursor.text, i - 1) && isNotSymbol(cursor.text, i + 1, c)) { return i; } } } return -1; }
java
private int findSpanStart(TextCursor cursor, int limit) { for (int i = cursor.currentOffset; i < limit; i++) { char c = cursor.text.charAt(i); if (c == '*' || c == '_') { // Check prev and next symbols if (isGoodAnchor(cursor.text, i - 1) && isNotSymbol(cursor.text, i + 1, c)) { return i; } } } return -1; }
[ "private", "int", "findSpanStart", "(", "TextCursor", "cursor", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "cursor", ".", "currentOffset", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "char", "c", "=", "cursor", ".", "text", "...
Searching for valid formatting span start @param cursor text cursor @param limit maximum index in cursor @return span start, -1 if not found
[ "Searching", "for", "valid", "formatting", "span", "start" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java#L271-L282
spring-projects/spring-retry
src/main/java/org/springframework/retry/policy/NeverRetryPolicy.java
NeverRetryPolicy.registerThrowable
public void registerThrowable(RetryContext context, Throwable throwable) { ((NeverRetryContext) context).setFinished(); ((RetryContextSupport) context).registerThrowable(throwable); }
java
public void registerThrowable(RetryContext context, Throwable throwable) { ((NeverRetryContext) context).setFinished(); ((RetryContextSupport) context).registerThrowable(throwable); }
[ "public", "void", "registerThrowable", "(", "RetryContext", "context", ",", "Throwable", "throwable", ")", "{", "(", "(", "NeverRetryContext", ")", "context", ")", ".", "setFinished", "(", ")", ";", "(", "(", "RetryContextSupport", ")", "context", ")", ".", ...
Make the throwable available for downstream use through the context. @see org.springframework.retry.RetryPolicy#registerThrowable(org.springframework.retry.RetryContext, Throwable)
[ "Make", "the", "throwable", "available", "for", "downstream", "use", "through", "the", "context", "." ]
train
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/policy/NeverRetryPolicy.java#L67-L70
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.mapFv
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { return mapFv(fv(key, false), fv(val, false), nullAllowed); }
java
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { return mapFv(fv(key, false), fv(val, false), nullAllowed); }
[ "public", "static", "NestableFieldValidator", "mapFv", "(", "Class", "key", ",", "Class", "val", ",", "boolean", "nullAllowed", ")", "{", "return", "mapFv", "(", "fv", "(", "key", ",", "false", ")", ",", "fv", "(", "val", ",", "false", ")", ",", "nullA...
Returns a new NestableFieldValidator for a Map of key to val. @param key the Class of keys in the map @param val the Class of values in the map @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a Map of key to val
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "Map", "of", "key", "to", "val", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L126-L128
OpenLiberty/open-liberty
dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java
LibertyFeaturesToMavenRepo.addDependency
private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); } if (type != null) { dependency.setType(type.getType()); } dependencies.add(dependency); }
java
private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); } if (type != null) { dependency.setType(type.getType()); } dependencies.add(dependency); }
[ "private", "static", "void", "addDependency", "(", "List", "<", "Dependency", ">", "dependencies", ",", "MavenCoordinates", "requiredArtifact", ",", "Constants", ".", "ArtifactType", "type", ",", "String", "scope", ")", "{", "Dependency", "dependency", "=", "new",...
Add dependency to the list of Maven Dependencies. @param dependencies The list of dependencies to append to. @param requiredArtifact The required artifact to add as a dependency. @param type The type of artifact, or null if jar.
[ "Add", "dependency", "to", "the", "list", "of", "Maven", "Dependencies", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java#L416-L429
elki-project/elki
elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/AbstractNode.java
AbstractNode.splitTo
public final void splitTo(AbstractNode<E> newNode, List<E> assignmentsToFirst, List<E> assignmentsToSecond) { assert (isLeaf() == newNode.isLeaf()); deleteAllEntries(); StringBuilder msg = LoggingConfiguration.DEBUG ? new StringBuilder(1000) : null; // assignments to this node for(E entry : assignmentsToFirst) { if(msg != null) { msg.append("n_").append(getPageID()).append(' ').append(entry).append('\n'); } addEntry(entry); } // assignments to the new node for(E entry : assignmentsToSecond) { if(msg != null) { msg.append("n_").append(newNode.getPageID()).append(' ').append(entry).append('\n'); } newNode.addEntry(entry); } if(msg != null) { Logging.getLogger(this.getClass()).fine(msg.toString()); } }
java
public final void splitTo(AbstractNode<E> newNode, List<E> assignmentsToFirst, List<E> assignmentsToSecond) { assert (isLeaf() == newNode.isLeaf()); deleteAllEntries(); StringBuilder msg = LoggingConfiguration.DEBUG ? new StringBuilder(1000) : null; // assignments to this node for(E entry : assignmentsToFirst) { if(msg != null) { msg.append("n_").append(getPageID()).append(' ').append(entry).append('\n'); } addEntry(entry); } // assignments to the new node for(E entry : assignmentsToSecond) { if(msg != null) { msg.append("n_").append(newNode.getPageID()).append(' ').append(entry).append('\n'); } newNode.addEntry(entry); } if(msg != null) { Logging.getLogger(this.getClass()).fine(msg.toString()); } }
[ "public", "final", "void", "splitTo", "(", "AbstractNode", "<", "E", ">", "newNode", ",", "List", "<", "E", ">", "assignmentsToFirst", ",", "List", "<", "E", ">", "assignmentsToSecond", ")", "{", "assert", "(", "isLeaf", "(", ")", "==", "newNode", ".", ...
Splits the entries of this node into a new node using the given assignments @param newNode Node to split to @param assignmentsToFirst the assignment to this node @param assignmentsToSecond the assignment to the new node
[ "Splits", "the", "entries", "of", "this", "node", "into", "a", "new", "node", "using", "the", "given", "assignments" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/AbstractNode.java#L332-L355
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java
AbstractValidator.validateDomainObject
protected <S extends Serializable> void validateDomainObject(S domainObject, Set<ATError> errors) { Set<ConstraintViolation<S>> constraintViolations = validator.validate( domainObject ); if (CollectionUtils.isEmpty(constraintViolations)) { return; } for ( ConstraintViolation<S> violation : constraintViolations ) { String type = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(); String attrPath = violation.getPropertyPath().toString(); String msgKey = attrPath + "." + type; if (null != violation.getMessage() && violation.getMessage().startsWith(MSG_KEY_PREFIX)) { msgKey = violation.getMessage(); } errors.add(new ATError((attrPath + "." + type), getMessage(msgKey, new Object[]{attrPath}, violation.getMessage()), attrPath)); } }
java
protected <S extends Serializable> void validateDomainObject(S domainObject, Set<ATError> errors) { Set<ConstraintViolation<S>> constraintViolations = validator.validate( domainObject ); if (CollectionUtils.isEmpty(constraintViolations)) { return; } for ( ConstraintViolation<S> violation : constraintViolations ) { String type = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(); String attrPath = violation.getPropertyPath().toString(); String msgKey = attrPath + "." + type; if (null != violation.getMessage() && violation.getMessage().startsWith(MSG_KEY_PREFIX)) { msgKey = violation.getMessage(); } errors.add(new ATError((attrPath + "." + type), getMessage(msgKey, new Object[]{attrPath}, violation.getMessage()), attrPath)); } }
[ "protected", "<", "S", "extends", "Serializable", ">", "void", "validateDomainObject", "(", "S", "domainObject", ",", "Set", "<", "ATError", ">", "errors", ")", "{", "Set", "<", "ConstraintViolation", "<", "S", ">>", "constraintViolations", "=", "validator", "...
validates a domain object with javax.validation annotations @param domainObject @param errors
[ "validates", "a", "domain", "object", "with", "javax", ".", "validation", "annotations" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java#L105-L119
derari/cthul
objects/src/main/java/org/cthul/objects/reflection/Signatures.java
Signatures.candidateMatches
public static int[] candidateMatches(Class<?>[][] signatures, boolean[] varArgs, Class<?>[] argTypes) { return candidateMatches(signatures, varArgs, new JavaSignatureComparator(argTypes)); }
java
public static int[] candidateMatches(Class<?>[][] signatures, boolean[] varArgs, Class<?>[] argTypes) { return candidateMatches(signatures, varArgs, new JavaSignatureComparator(argTypes)); }
[ "public", "static", "int", "[", "]", "candidateMatches", "(", "Class", "<", "?", ">", "[", "]", "[", "]", "signatures", ",", "boolean", "[", "]", "varArgs", ",", "Class", "<", "?", ">", "[", "]", "argTypes", ")", "{", "return", "candidateMatches", "(...
Returns indices of all signatures that are a best match for the given argument types. @param signatures @param varArgs @param argTypes @return signature indices
[ "Returns", "indices", "of", "all", "signatures", "that", "are", "a", "best", "match", "for", "the", "given", "argument", "types", "." ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/reflection/Signatures.java#L494-L496
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
AbstractQueuedSynchronizer.shouldParkAfterFailedAcquire
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park. */ return true; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. */ do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ pred.compareAndSetWaitStatus(ws, Node.SIGNAL); } return false; }
java
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park. */ return true; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. */ do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ pred.compareAndSetWaitStatus(ws, Node.SIGNAL); } return false; }
[ "private", "static", "boolean", "shouldParkAfterFailedAcquire", "(", "Node", "pred", ",", "Node", "node", ")", "{", "int", "ws", "=", "pred", ".", "waitStatus", ";", "if", "(", "ws", "==", "Node", ".", "SIGNAL", ")", "/*\n * This node has already set...
Checks and updates status for a node that failed to acquire. Returns true if thread should block. This is the main signal control in all acquire loops. Requires that pred == node.prev. @param pred node's predecessor holding status @param node the node @return {@code true} if thread should block
[ "Checks", "and", "updates", "status", "for", "a", "node", "that", "failed", "to", "acquire", ".", "Returns", "true", "if", "thread", "should", "block", ".", "This", "is", "the", "main", "signal", "control", "in", "all", "acquire", "loops", ".", "Requires",...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java#L831-L857
tvesalainen/util
util/src/main/java/org/vesalainen/util/AbstractConfigFile.java
AbstractConfigFile.storeAs
public void storeAs(File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, UTF_8); BufferedWriter bw = new BufferedWriter(osw)) { store(bw); } }
java
public void storeAs(File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, UTF_8); BufferedWriter bw = new BufferedWriter(osw)) { store(bw); } }
[ "public", "void", "storeAs", "(", "File", "file", ")", "throws", "IOException", "{", "try", "(", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "file", ")", ";", "OutputStreamWriter", "osw", "=", "new", "OutputStreamWriter", "(", "fos", ",", ...
Stores xml-content to file. This doesn't change stored url/file. @param file @throws IOException
[ "Stores", "xml", "-", "content", "to", "file", ".", "This", "doesn", "t", "change", "stored", "url", "/", "file", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/AbstractConfigFile.java#L150-L158
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_domain_domainName_GET
public OvhDomain organizationName_service_exchangeService_domain_domainName_GET(String organizationName, String exchangeService, String domainName) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/domain/{domainName}"; StringBuilder sb = path(qPath, organizationName, exchangeService, domainName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDomain.class); }
java
public OvhDomain organizationName_service_exchangeService_domain_domainName_GET(String organizationName, String exchangeService, String domainName) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/domain/{domainName}"; StringBuilder sb = path(qPath, organizationName, exchangeService, domainName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDomain.class); }
[ "public", "OvhDomain", "organizationName_service_exchangeService_domain_domainName_GET", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "domainName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organization...
Get this object properties REST: GET /email/exchange/{organizationName}/service/{exchangeService}/domain/{domainName} @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param domainName [required] Domain name
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L484-L489
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDSRegistryAuditor.java
XDSRegistryAuditor.auditRegisterEvent
protected void auditRegisterEvent( IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, String repositoryUserId, String repositoryIpAddress, String userName, String registryEndpointUri, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles) { ImportEvent importEvent = new ImportEvent(false, eventOutcome, transaction, purposesOfUse); importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); importEvent.addSourceActiveParticipant(repositoryUserId, null, null, repositoryIpAddress, true); if (! EventUtils.isEmptyOrNull(userName)) { importEvent.addHumanRequestorActiveParticipant(userName, null, userName, userRoles); } importEvent.addDestinationActiveParticipant(registryEndpointUri, getSystemAltUserId(), null, EventUtils.getAddressForUrl(registryEndpointUri, false), false); if (!EventUtils.isEmptyOrNull(patientId)) { importEvent.addPatientParticipantObject(patientId); } importEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(importEvent); }
java
protected void auditRegisterEvent( IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, String repositoryUserId, String repositoryIpAddress, String userName, String registryEndpointUri, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles) { ImportEvent importEvent = new ImportEvent(false, eventOutcome, transaction, purposesOfUse); importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); importEvent.addSourceActiveParticipant(repositoryUserId, null, null, repositoryIpAddress, true); if (! EventUtils.isEmptyOrNull(userName)) { importEvent.addHumanRequestorActiveParticipant(userName, null, userName, userRoles); } importEvent.addDestinationActiveParticipant(registryEndpointUri, getSystemAltUserId(), null, EventUtils.getAddressForUrl(registryEndpointUri, false), false); if (!EventUtils.isEmptyOrNull(patientId)) { importEvent.addPatientParticipantObject(patientId); } importEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(importEvent); }
[ "protected", "void", "auditRegisterEvent", "(", "IHETransactionEventTypeCodes", "transaction", ",", "RFC3881EventOutcomeCodes", "eventOutcome", ",", "String", "repositoryUserId", ",", "String", "repositoryIpAddress", ",", "String", "userName", ",", "String", "registryEndpoint...
Generically sends audit messages for XDS Document Registry Register Document Set events @param transaction The specific IHE Transaction (ITI-15 or ITI-41) @param eventOutcome The event outcome indicator @param repositoryUserId The Active Participant UserID for the repository (if using WS-Addressing) @param repositoryIpAddress The IP Address of the repository that initiated the transaction @param userName user name from XUA @param registryEndpointUri The URI of this registry's endpoint that received the transaction @param submissionSetUniqueId The UniqueID of the Submission Set provided @param patientId The Patient Id that this submission pertains to @param purposesOfUse purpose of use codes (may be taken from XUA token) @param userRoles roles of the human user (may be taken from XUA token)
[ "Generically", "sends", "audit", "messages", "for", "XDS", "Document", "Registry", "Register", "Document", "Set", "events" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDSRegistryAuditor.java#L215-L238
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/elements/path/PathBuilder.java
PathBuilder.quadTo
public PathBuilder quadTo(Point2d cp, Point2d ep) { add(new QuadTo(cp, ep)); return this; }
java
public PathBuilder quadTo(Point2d cp, Point2d ep) { add(new QuadTo(cp, ep)); return this; }
[ "public", "PathBuilder", "quadTo", "(", "Point2d", "cp", ",", "Point2d", "ep", ")", "{", "add", "(", "new", "QuadTo", "(", "cp", ",", "ep", ")", ")", ";", "return", "this", ";", "}" ]
Make a quadratic curve in the path, with one control point. @param cp the control point of the curve @param ep the end point of the curve @return a reference to this builder
[ "Make", "a", "quadratic", "curve", "in", "the", "path", "with", "one", "control", "point", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/elements/path/PathBuilder.java#L111-L114
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/media/MediaClient.java
MediaClient.createPreset
public CreatePresetResponse createPreset(String presetName, String container, Audio audio) { return createPreset(presetName, null, container, false, null, audio, null, null, null); }
java
public CreatePresetResponse createPreset(String presetName, String container, Audio audio) { return createPreset(presetName, null, container, false, null, audio, null, null, null); }
[ "public", "CreatePresetResponse", "createPreset", "(", "String", "presetName", ",", "String", "container", ",", "Audio", "audio", ")", "{", "return", "createPreset", "(", "presetName", ",", "null", ",", "container", ",", "false", ",", "null", ",", "audio", ","...
Create a preset which help to convert audio files on be played in a wide range of devices. @param presetName The name of the new preset. @param container The container type for the output file. Valid values include mp4, flv, hls, mp3, m4a. @param audio Specify the audio format of target file.
[ "Create", "a", "preset", "which", "help", "to", "convert", "audio", "files", "on", "be", "played", "in", "a", "wide", "range", "of", "devices", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L678-L680
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java
Firmata.addMessageListener
public void addMessageListener(Class<? extends Message> messageClass, MessageListener<Message> messageListener) { addMessageListener(messageListener.getChannelIdentifier(), messageClass, messageListener); }
java
public void addMessageListener(Class<? extends Message> messageClass, MessageListener<Message> messageListener) { addMessageListener(messageListener.getChannelIdentifier(), messageClass, messageListener); }
[ "public", "void", "addMessageListener", "(", "Class", "<", "?", "extends", "Message", ">", "messageClass", ",", "MessageListener", "<", "Message", ">", "messageListener", ")", "{", "addMessageListener", "(", "messageListener", ".", "getChannelIdentifier", "(", ")", ...
Add a generic message listener to listen for a specific type of message. Useful if you want to combine several or more message handlers into one bucket. @param messageClass Message class to listen to from the project board. @param messageListener (Generic)Listener that will fire whenever the message type is received.
[ "Add", "a", "generic", "message", "listener", "to", "listen", "for", "a", "specific", "type", "of", "message", ".", "Useful", "if", "you", "want", "to", "combine", "several", "or", "more", "message", "handlers", "into", "one", "bucket", "." ]
train
https://github.com/reapzor/FiloFirmata/blob/39c26c1a577b8fff8690245e105cb62e02284f16/src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java#L195-L197
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java
QueryDataUtils.getReplierExportStrategyLabel
private static String getReplierExportStrategyLabel(Locale locale, ReplierExportStrategy replierExportStrategy) { switch (replierExportStrategy) { case NONE: break; case HASH: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierIdColumn"); case NAME: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierNameColumn"); case EMAIL: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierEmailColumn"); } return null; }
java
private static String getReplierExportStrategyLabel(Locale locale, ReplierExportStrategy replierExportStrategy) { switch (replierExportStrategy) { case NONE: break; case HASH: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierIdColumn"); case NAME: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierNameColumn"); case EMAIL: return Messages.getInstance().getText(locale, "panelAdmin.query.export.csvReplierEmailColumn"); } return null; }
[ "private", "static", "String", "getReplierExportStrategyLabel", "(", "Locale", "locale", ",", "ReplierExportStrategy", "replierExportStrategy", ")", "{", "switch", "(", "replierExportStrategy", ")", "{", "case", "NONE", ":", "break", ";", "case", "HASH", ":", "retur...
Returns label for given replier export strategy @param locale locale @param replierExportStrategy replier export strategy @return label
[ "Returns", "label", "for", "given", "replier", "export", "strategy" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java#L279-L292
moparisthebest/beehive
beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java
DefaultObjectResultSetMapper.arrayFromResultSet
protected Object arrayFromResultSet(ResultSet rs, int maxRows, Class arrayClass, Calendar cal) throws SQLException { ArrayList<Object> list = new ArrayList<Object>(); Class componentType = arrayClass.getComponentType(); RowMapper rowMapper = RowMapperFactory.getRowMapper(rs, componentType, cal); // a value of zero indicates that all rows from the resultset should be included. if (maxRows == 0) { maxRows = -1; } int numRows; boolean hasMoreRows = rs.next(); for (numRows = 0; numRows != maxRows && hasMoreRows; numRows++) { list.add(rowMapper.mapRowToReturnType()); hasMoreRows = rs.next(); } Object array = Array.newInstance(componentType, numRows); try { for (int i = 0; i < numRows; i++) { Array.set(array, i, list.get(i)); } } catch (IllegalArgumentException iae) { ResultSetMetaData md = rs.getMetaData(); // assuming no errors in resultSetObject() this can only happen // for single column result sets. throw new ControlException("The declared Java type for array " + componentType.getName() + "is incompatible with the SQL format of column " + md.getColumnName(1) + md.getColumnTypeName(1) + "which returns objects of type + " + list.get(0).getClass().getName()); } return array; }
java
protected Object arrayFromResultSet(ResultSet rs, int maxRows, Class arrayClass, Calendar cal) throws SQLException { ArrayList<Object> list = new ArrayList<Object>(); Class componentType = arrayClass.getComponentType(); RowMapper rowMapper = RowMapperFactory.getRowMapper(rs, componentType, cal); // a value of zero indicates that all rows from the resultset should be included. if (maxRows == 0) { maxRows = -1; } int numRows; boolean hasMoreRows = rs.next(); for (numRows = 0; numRows != maxRows && hasMoreRows; numRows++) { list.add(rowMapper.mapRowToReturnType()); hasMoreRows = rs.next(); } Object array = Array.newInstance(componentType, numRows); try { for (int i = 0; i < numRows; i++) { Array.set(array, i, list.get(i)); } } catch (IllegalArgumentException iae) { ResultSetMetaData md = rs.getMetaData(); // assuming no errors in resultSetObject() this can only happen // for single column result sets. throw new ControlException("The declared Java type for array " + componentType.getName() + "is incompatible with the SQL format of column " + md.getColumnName(1) + md.getColumnTypeName(1) + "which returns objects of type + " + list.get(0).getClass().getName()); } return array; }
[ "protected", "Object", "arrayFromResultSet", "(", "ResultSet", "rs", ",", "int", "maxRows", ",", "Class", "arrayClass", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "ArrayList", "<", "Object", ">", "list", "=", "new", "ArrayList", "<", "Object",...
Invoked when the return type of the method is an array type. @param rs ResultSet to process. @param maxRows The maximum size of array to create, a value of 0 indicates that the array size will be the same as the result set size (no limit). @param arrayClass The class of object contained within the array @param cal A calendar instance to use for date/time values @return An array of the specified class type @throws SQLException On error.
[ "Invoked", "when", "the", "return", "type", "of", "the", "method", "is", "an", "array", "type", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultObjectResultSetMapper.java#L88-L122
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/base/CPOptionLocalServiceBaseImpl.java
CPOptionLocalServiceBaseImpl.fetchCPOptionByUuidAndGroupId
@Override public CPOption fetchCPOptionByUuidAndGroupId(String uuid, long groupId) { return cpOptionPersistence.fetchByUUID_G(uuid, groupId); }
java
@Override public CPOption fetchCPOptionByUuidAndGroupId(String uuid, long groupId) { return cpOptionPersistence.fetchByUUID_G(uuid, groupId); }
[ "@", "Override", "public", "CPOption", "fetchCPOptionByUuidAndGroupId", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "cpOptionPersistence", ".", "fetchByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "}" ]
Returns the cp option matching the UUID and group. @param uuid the cp option's UUID @param groupId the primary key of the group @return the matching cp option, or <code>null</code> if a matching cp option could not be found
[ "Returns", "the", "cp", "option", "matching", "the", "UUID", "and", "group", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/base/CPOptionLocalServiceBaseImpl.java#L253-L256
trellis-ldp/trellis
components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResource.java
TriplestoreResource.fetchIndirectMemberQuads
private Stream<Quad> fetchIndirectMemberQuads() { final Var s = Var.alloc("s"); final Var o = Var.alloc("o"); final Var res = Var.alloc("res"); final Query q = new Query(); q.setQuerySelectType(); q.addResultVar(SUBJECT); q.addResultVar(PREDICATE); q.addResultVar(OBJECT); final ElementPathBlock epb1 = new ElementPathBlock(); epb1.addTriple(create(s, rdf.asJenaNode(LDP.member), rdf.asJenaNode(identifier))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.membershipResource), SUBJECT)); epb1.addTriple(create(s, rdf.asJenaNode(RDF.type), rdf.asJenaNode(LDP.IndirectContainer))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.hasMemberRelation), PREDICATE)); epb1.addTriple(create(s, rdf.asJenaNode(LDP.insertedContentRelation), o)); epb1.addTriple(create(res, rdf.asJenaNode(DC.isPartOf), s)); final ElementPathBlock epb2 = new ElementPathBlock(); epb2.addTriple(create(res, o, OBJECT)); final ElementGroup elg = new ElementGroup(); elg.addElement(new ElementNamedGraph(rdf.asJenaNode(Trellis.PreferServerManaged), epb1)); elg.addElement(new ElementNamedGraph(res, epb2)); q.setQueryPattern(elg); final Stream.Builder<Quad> builder = builder(); rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(LDP.PreferMembership, getSubject(qs), getPredicate(qs), getObject(qs)))); return builder.build(); }
java
private Stream<Quad> fetchIndirectMemberQuads() { final Var s = Var.alloc("s"); final Var o = Var.alloc("o"); final Var res = Var.alloc("res"); final Query q = new Query(); q.setQuerySelectType(); q.addResultVar(SUBJECT); q.addResultVar(PREDICATE); q.addResultVar(OBJECT); final ElementPathBlock epb1 = new ElementPathBlock(); epb1.addTriple(create(s, rdf.asJenaNode(LDP.member), rdf.asJenaNode(identifier))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.membershipResource), SUBJECT)); epb1.addTriple(create(s, rdf.asJenaNode(RDF.type), rdf.asJenaNode(LDP.IndirectContainer))); epb1.addTriple(create(s, rdf.asJenaNode(LDP.hasMemberRelation), PREDICATE)); epb1.addTriple(create(s, rdf.asJenaNode(LDP.insertedContentRelation), o)); epb1.addTriple(create(res, rdf.asJenaNode(DC.isPartOf), s)); final ElementPathBlock epb2 = new ElementPathBlock(); epb2.addTriple(create(res, o, OBJECT)); final ElementGroup elg = new ElementGroup(); elg.addElement(new ElementNamedGraph(rdf.asJenaNode(Trellis.PreferServerManaged), epb1)); elg.addElement(new ElementNamedGraph(res, epb2)); q.setQueryPattern(elg); final Stream.Builder<Quad> builder = builder(); rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(LDP.PreferMembership, getSubject(qs), getPredicate(qs), getObject(qs)))); return builder.build(); }
[ "private", "Stream", "<", "Quad", ">", "fetchIndirectMemberQuads", "(", ")", "{", "final", "Var", "s", "=", "Var", ".", "alloc", "(", "\"s\"", ")", ";", "final", "Var", "o", "=", "Var", ".", "alloc", "(", "\"o\"", ")", ";", "final", "Var", "res", "...
This code is equivalent to the SPARQL query below. <p><pre><code> SELECT ?subject ?predicate ?object WHERE { GRAPH trellis:PreferServerManaged { ?s ldp:member IDENTIFIER ?s ldp:membershipResource ?subject AND ?s rdf:type ldp:IndirectContainer AND ?s ldp:membershipRelation ?predicate AND ?s ldp:insertedContentRelation ?o AND ?res dc:isPartOf ?s . } GRAPH ?res { ?res ?o ?object } } </code></pre>
[ "This", "code", "is", "equivalent", "to", "the", "SPARQL", "query", "below", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResource.java#L319-L351
janus-project/guava.janusproject.io
guava/src/com/google/common/base/Joiner.java
Joiner.appendTo
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); }
java
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); }
[ "public", "<", "A", "extends", "Appendable", ">", "A", "appendTo", "(", "A", "appendable", ",", "Iterable", "<", "?", ">", "parts", ")", "throws", "IOException", "{", "return", "appendTo", "(", "appendable", ",", "parts", ".", "iterator", "(", ")", ")", ...
Appends the string representation of each of {@code parts}, using the previously configured separator between each, to {@code appendable}.
[ "Appends", "the", "string", "representation", "of", "each", "of", "{" ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/base/Joiner.java#L95-L97
apache/incubator-druid
extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchBuildBufferAggregator.java
DoublesSketchBuildBufferAggregator.relocate
@Override public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer) { UpdateDoublesSketch sketch = sketches.get(oldBuffer).get(oldPosition); final WritableMemory oldRegion = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize); if (sketch.isSameResource(oldRegion)) { // sketch was not relocated on heap final WritableMemory newRegion = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize); sketch = UpdateDoublesSketch.wrap(newRegion); } putSketch(newBuffer, newPosition, sketch); final Int2ObjectMap<UpdateDoublesSketch> map = sketches.get(oldBuffer); map.remove(oldPosition); if (map.isEmpty()) { sketches.remove(oldBuffer); memCache.remove(oldBuffer); } }
java
@Override public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer) { UpdateDoublesSketch sketch = sketches.get(oldBuffer).get(oldPosition); final WritableMemory oldRegion = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize); if (sketch.isSameResource(oldRegion)) { // sketch was not relocated on heap final WritableMemory newRegion = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize); sketch = UpdateDoublesSketch.wrap(newRegion); } putSketch(newBuffer, newPosition, sketch); final Int2ObjectMap<UpdateDoublesSketch> map = sketches.get(oldBuffer); map.remove(oldPosition); if (map.isEmpty()) { sketches.remove(oldBuffer); memCache.remove(oldBuffer); } }
[ "@", "Override", "public", "synchronized", "void", "relocate", "(", "int", "oldPosition", ",", "int", "newPosition", ",", "ByteBuffer", "oldBuffer", ",", "ByteBuffer", "newBuffer", ")", "{", "UpdateDoublesSketch", "sketch", "=", "sketches", ".", "get", "(", "old...
In that case we need to reuse the object from the cache as opposed to wrapping the new buffer.
[ "In", "that", "case", "we", "need", "to", "reuse", "the", "object", "from", "the", "cache", "as", "opposed", "to", "wrapping", "the", "new", "buffer", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchBuildBufferAggregator.java#L96-L113
before/uadetector
modules/uadetector-core/src/main/java/net/sf/uadetector/datareader/XmlDataReader.java
XmlDataReader.readXml
protected static Data readXml(@Nonnull final InputStream inputStream, @Nonnull final Charset charset) { Check.notNull(inputStream, "inputStream"); Check.notNull(charset, "charset"); final DataBuilder builder = new DataBuilder(); boolean hasErrors = false; try { XmlParser.parse(inputStream, builder); } catch (final ParserConfigurationException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final SAXException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IOException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IllegalStateException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final Exception e) { hasErrors = true; LOG.warn(e.getLocalizedMessage(), e); } finally { Closeables.closeAndConvert(inputStream, true); } return hasErrors ? Data.EMPTY : builder.build(); }
java
protected static Data readXml(@Nonnull final InputStream inputStream, @Nonnull final Charset charset) { Check.notNull(inputStream, "inputStream"); Check.notNull(charset, "charset"); final DataBuilder builder = new DataBuilder(); boolean hasErrors = false; try { XmlParser.parse(inputStream, builder); } catch (final ParserConfigurationException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final SAXException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IOException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final IllegalStateException e) { hasErrors = true; LOG.warn(e.getLocalizedMessage()); } catch (final Exception e) { hasErrors = true; LOG.warn(e.getLocalizedMessage(), e); } finally { Closeables.closeAndConvert(inputStream, true); } return hasErrors ? Data.EMPTY : builder.build(); }
[ "protected", "static", "Data", "readXml", "(", "@", "Nonnull", "final", "InputStream", "inputStream", ",", "@", "Nonnull", "final", "Charset", "charset", ")", "{", "Check", ".", "notNull", "(", "inputStream", ",", "\"inputStream\"", ")", ";", "Check", ".", "...
Reads the <em>UAS data</em> in XML format based on the given URL.<br> <br> When during the reading errors occur which lead to a termination of the read operation, the information will be written to a log. The termination of the read operation will not lead to a program termination and in this case this method returns {@link Data#EMPTY}. @param inputStream an input stream for reading <em>UAS data</em> @param charset the character set in which the data should be read @return read in <em>UAS data</em> as {@code Data} instance @throws net.sf.qualitycheck.exception.IllegalNullArgumentException if any of the given arguments is {@code null} @throws net.sf.uadetector.exception.CanNotOpenStreamException if no stream to the given {@code URL} can be established
[ "Reads", "the", "<em", ">", "UAS", "data<", "/", "em", ">", "in", "XML", "format", "based", "on", "the", "given", "URL", ".", "<br", ">", "<br", ">", "When", "during", "the", "reading", "errors", "occur", "which", "lead", "to", "a", "termination", "o...
train
https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/datareader/XmlDataReader.java#L104-L132
icode/ameba
src/main/java/ameba/db/ebean/support/ModelResourceStructure.java
ModelResourceStructure.processCheckRowCountError
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception { if (e == null) { throw root; } if (e instanceof OptimisticLockException) { if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) { if (process != null) return process.call(t); } } return processCheckRowCountError(t, root, e.getCause(), process); }
java
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception { if (e == null) { throw root; } if (e instanceof OptimisticLockException) { if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) { if (process != null) return process.call(t); } } return processCheckRowCountError(t, root, e.getCause(), process); }
[ "protected", "<", "T", ">", "T", "processCheckRowCountError", "(", "Transaction", "t", ",", "Exception", "root", ",", "Throwable", "e", ",", "TxCallable", "<", "T", ">", "process", ")", "throws", "Exception", "{", "if", "(", "e", "==", "null", ")", "{", ...
<p>processCheckRowCountError.</p> @param t Transaction @param root root exception @param e exception @param process process method @param <T> model @return model @throws java.lang.Exception if any.
[ "<p", ">", "processCheckRowCountError", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L1076-L1087
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/GeoParser.java
GeoParser.parse
public List<ResolvedLocation> parse(String inputText) throws Exception { return parse(inputText, ClavinLocationResolver.DEFAULT_ANCESTRY_MODE); }
java
public List<ResolvedLocation> parse(String inputText) throws Exception { return parse(inputText, ClavinLocationResolver.DEFAULT_ANCESTRY_MODE); }
[ "public", "List", "<", "ResolvedLocation", ">", "parse", "(", "String", "inputText", ")", "throws", "Exception", "{", "return", "parse", "(", "inputText", ",", "ClavinLocationResolver", ".", "DEFAULT_ANCESTRY_MODE", ")", ";", "}" ]
Takes an unstructured text document (as a String), extracts the location names contained therein, and resolves them into geographic entities representing the best match for those location names. @param inputText unstructured text to be processed @return list of geo entities resolved from text @throws Exception
[ "Takes", "an", "unstructured", "text", "document", "(", "as", "a", "String", ")", "extracts", "the", "location", "names", "contained", "therein", "and", "resolves", "them", "into", "geographic", "entities", "representing", "the", "best", "match", "for", "those",...
train
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParser.java#L96-L98
stevespringett/Alpine
alpine/src/main/java/alpine/filters/RequestRateThrottleFilter.java
RequestRateThrottleFilter.doFilter
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final HttpSession session = httpRequest.getSession(true); synchronized (session.getId().intern()) { Stack<Date> times = HttpUtil.getSessionAttribute(session, "times"); if (times == null) { times = new Stack<>(); times.push(new Date(0)); session.setAttribute("times", times); } times.push(new Date()); if (times.size() >= maximumRequestsPerPeriod) { times.removeElementAt(0); } final Date newest = times.get(times.size() - 1); final Date oldest = times.get(0); final long elapsed = newest.getTime() - oldest.getTime(); if (elapsed < timePeriodSeconds * 1000) { httpResponse.sendError(429); return; } } chain.doFilter(request, response); }
java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final HttpSession session = httpRequest.getSession(true); synchronized (session.getId().intern()) { Stack<Date> times = HttpUtil.getSessionAttribute(session, "times"); if (times == null) { times = new Stack<>(); times.push(new Date(0)); session.setAttribute("times", times); } times.push(new Date()); if (times.size() >= maximumRequestsPerPeriod) { times.removeElementAt(0); } final Date newest = times.get(times.size() - 1); final Date oldest = times.get(0); final long elapsed = newest.getTime() - oldest.getTime(); if (elapsed < timePeriodSeconds * 1000) { httpResponse.sendError(429); return; } } chain.doFilter(request, response); }
[ "public", "void", "doFilter", "(", "final", "ServletRequest", "request", ",", "final", "ServletResponse", "response", ",", "final", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "final", "HttpServletRequest", "httpRequest", "=", ...
Determines if the request rate is below or has exceeded the the maximum requests per second for the given time period. If exceeded, a HTTP status code of 429 (too many requests) will be send and no further processing of the request will be done. If the request has not exceeded the limit, the request will continue on as normal. @param request a ServletRequest @param response a ServletResponse @param chain a FilterChain @throws IOException a IOException @throws ServletException a ServletException
[ "Determines", "if", "the", "request", "rate", "is", "below", "or", "has", "exceeded", "the", "the", "maximum", "requests", "per", "second", "for", "the", "given", "time", "period", ".", "If", "exceeded", "a", "HTTP", "status", "code", "of", "429", "(", "...
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/RequestRateThrottleFilter.java#L92-L118
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java
ExamplesImpl.listWithServiceResponseAsync
public Observable<ServiceResponse<List<LabeledUtterance>>> listWithServiceResponseAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null; final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null; return listWithServiceResponseAsync(appId, versionId, skip, take); }
java
public Observable<ServiceResponse<List<LabeledUtterance>>> listWithServiceResponseAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null; final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null; return listWithServiceResponseAsync(appId, versionId, skip, take); }
[ "public", "Observable", "<", "ServiceResponse", "<", "List", "<", "LabeledUtterance", ">", ">", ">", "listWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "ListExamplesOptionalParameter", "listOptionalParameter", ")", "{", "if", "(", ...
Returns examples to be reviewed. @param appId The application ID. @param versionId The version ID. @param listOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LabeledUtterance&gt; object
[ "Returns", "examples", "to", "be", "reviewed", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java#L328-L342
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java
Error.globalClassesAbsent
public static void globalClassesAbsent(Class<?> aClass){ throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorRelationalException3, aClass.getSimpleName())); }
java
public static void globalClassesAbsent(Class<?> aClass){ throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorRelationalException3, aClass.getSimpleName())); }
[ "public", "static", "void", "globalClassesAbsent", "(", "Class", "<", "?", ">", "aClass", ")", "{", "throw", "new", "MappingErrorException", "(", "MSG", ".", "INSTANCE", ".", "message", "(", "mappingErrorRelationalException3", ",", "aClass", ".", "getSimpleName", ...
Thrown if the configured class hasn't classes parameter. @param aClass class's field
[ "Thrown", "if", "the", "configured", "class", "hasn", "t", "classes", "parameter", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L550-L552
Impetus/Kundera
src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java
MongoDBClient.populateGFSEntity
private void populateGFSEntity(EntityMetadata entityMetadata, List entities, GridFSDBFile gfsDBFile) { Object entity = instantiateEntity(entityMetadata.getEntityClazz(), null); handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(), entity, entityMetadata, gfsDBFile, kunderaMetadata); entities.add(entity); }
java
private void populateGFSEntity(EntityMetadata entityMetadata, List entities, GridFSDBFile gfsDBFile) { Object entity = instantiateEntity(entityMetadata.getEntityClazz(), null); handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(), entity, entityMetadata, gfsDBFile, kunderaMetadata); entities.add(entity); }
[ "private", "void", "populateGFSEntity", "(", "EntityMetadata", "entityMetadata", ",", "List", "entities", ",", "GridFSDBFile", "gfsDBFile", ")", "{", "Object", "entity", "=", "instantiateEntity", "(", "entityMetadata", ".", "getEntityClazz", "(", ")", ",", "null", ...
Populate gfs entity. @param entityMetadata the entity metadata @param entities the entities @param gfsDBFile the gfs db file
[ "Populate", "gfs", "entity", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java#L838-L844
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/SortedBugCollection.java
SortedBugCollection.readXML
public void readXML(@WillClose InputStream in, File base) throws IOException, DocumentException { try { doReadXML(in, base); } finally { in.close(); } }
java
public void readXML(@WillClose InputStream in, File base) throws IOException, DocumentException { try { doReadXML(in, base); } finally { in.close(); } }
[ "public", "void", "readXML", "(", "@", "WillClose", "InputStream", "in", ",", "File", "base", ")", "throws", "IOException", ",", "DocumentException", "{", "try", "{", "doReadXML", "(", "in", ",", "base", ")", ";", "}", "finally", "{", "in", ".", "close",...
Read XML data from given input stream into this object, populating the Project as a side effect. An attempt will be made to close the input stream (even if an exception is thrown). @param in the InputStream
[ "Read", "XML", "data", "from", "given", "input", "stream", "into", "this", "object", "populating", "the", "Project", "as", "a", "side", "effect", ".", "An", "attempt", "will", "be", "made", "to", "close", "the", "input", "stream", "(", "even", "if", "an"...
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SortedBugCollection.java#L306-L312
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.setVariable
public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null) { throw new IllegalArgumentException("Variable \"" + name + "\" has already been assigned and cannot be reassigned"); } frame.put(name, frames); }
java
public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null) { throw new IllegalArgumentException("Variable \"" + name + "\" has already been assigned and cannot be reassigned"); } frame.put(name, frames); }
[ "public", "void", "setVariable", "(", "String", "name", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", "frames", ")", "{", "Map", "<", "String", ",", "Iterable", "<", "?", "extends", "WindupVertexFrame", ">", ">", "frame", "=", "peek", "("...
Set a variable in the top variables layer to given "collection" of the vertex frames. Can't be reassigned - throws on attempt to reassign.
[ "Set", "a", "variable", "in", "the", "top", "variables", "layer", "to", "given", "collection", "of", "the", "vertex", "frames", ".", "Can", "t", "be", "reassigned", "-", "throws", "on", "attempt", "to", "reassign", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L99-L109
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/ExceptionTableSensitiveMethodVisitor.java
ExceptionTableSensitiveMethodVisitor.onVisitMethodInsn
@Deprecated @SuppressWarnings("deprecation") protected void onVisitMethodInsn(int opcode, String owner, String name, String descriptor) { super.visitMethodInsn(opcode, owner, name, descriptor); }
java
@Deprecated @SuppressWarnings("deprecation") protected void onVisitMethodInsn(int opcode, String owner, String name, String descriptor) { super.visitMethodInsn(opcode, owner, name, descriptor); }
[ "@", "Deprecated", "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "protected", "void", "onVisitMethodInsn", "(", "int", "opcode", ",", "String", "owner", ",", "String", "name", ",", "String", "descriptor", ")", "{", "super", ".", "visitMethodInsn", "(", ...
Visits a method instruction. @param opcode The visited opcode. @param owner The method's owner. @param name The method's internal name. @param descriptor The method's descriptor. @deprecated Use {@link ExceptionTableSensitiveMethodVisitor#onVisitMethodInsn(int, String, String, String, boolean)} instead.
[ "Visits", "a", "method", "instruction", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/ExceptionTableSensitiveMethodVisitor.java#L158-L162
mikepenz/FastAdapter
library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java
FastAdapter.notifyAdapterItemRangeRemoved
public void notifyAdapterItemRangeRemoved(int position, int itemCount) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeRemoved(position, itemCount); } cacheSizes(); notifyItemRangeRemoved(position, itemCount); }
java
public void notifyAdapterItemRangeRemoved(int position, int itemCount) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeRemoved(position, itemCount); } cacheSizes(); notifyItemRangeRemoved(position, itemCount); }
[ "public", "void", "notifyAdapterItemRangeRemoved", "(", "int", "position", ",", "int", "itemCount", ")", "{", "// handle our extensions", "for", "(", "IAdapterExtension", "<", "Item", ">", "ext", ":", "mExtensions", ".", "values", "(", ")", ")", "{", "ext", "....
wraps notifyItemRangeRemoved @param position the global position @param itemCount the count of items removed
[ "wraps", "notifyItemRangeRemoved" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1303-L1311
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.container/src/com/ibm/ws/jpa/container/osgi/internal/url/JPAWSJarURLConnection.java
JPAWSJarURLConnection.getInputStream
@Override public synchronized InputStream getInputStream() throws IOException { if (connected == false) { // Implicitly open the connection if it has not yet been done so. connect(); } Object token = ThreadIdentityManager.runAsServer(); try { if (inputStream == null) { if ("".equals(archivePath)) { inputStream = new FileInputStream(urlTargetFile); } else { inputStream = new FilterZipFileInputStream(urlTargetFile, archivePath); } } } finally { ThreadIdentityManager.reset(token); } return inputStream; }
java
@Override public synchronized InputStream getInputStream() throws IOException { if (connected == false) { // Implicitly open the connection if it has not yet been done so. connect(); } Object token = ThreadIdentityManager.runAsServer(); try { if (inputStream == null) { if ("".equals(archivePath)) { inputStream = new FileInputStream(urlTargetFile); } else { inputStream = new FilterZipFileInputStream(urlTargetFile, archivePath); } } } finally { ThreadIdentityManager.reset(token); } return inputStream; }
[ "@", "Override", "public", "synchronized", "InputStream", "getInputStream", "(", ")", "throws", "IOException", "{", "if", "(", "connected", "==", "false", ")", "{", "// Implicitly open the connection if it has not yet been done so.", "connect", "(", ")", ";", "}", "Ob...
/* Passthrough operations for archive referencing wsjar URL support. Synchronized because calling getInputStream() while an InputStream is still active should return the active InputStream.
[ "/", "*", "Passthrough", "operations", "for", "archive", "referencing", "wsjar", "URL", "support", ".", "Synchronized", "because", "calling", "getInputStream", "()", "while", "an", "InputStream", "is", "still", "active", "should", "return", "the", "active", "Input...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jpa.container/src/com/ibm/ws/jpa/container/osgi/internal/url/JPAWSJarURLConnection.java#L63-L84
carewebframework/carewebframework-core
org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.helpconverter/src/main/java/org/carewebframework/maven/plugin/help/chm/BinaryTransform.java
BinaryTransform.readWord
protected int readWord(byte[] data, int offset) { int low = data[offset] & 0xff; int high = data[offset + 1] & 0xff; return high << 8 | low; }
java
protected int readWord(byte[] data, int offset) { int low = data[offset] & 0xff; int high = data[offset + 1] & 0xff; return high << 8 | low; }
[ "protected", "int", "readWord", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "int", "low", "=", "data", "[", "offset", "]", "&", "0xff", ";", "int", "high", "=", "data", "[", "offset", "+", "1", "]", "&", "0xff", ";", "return", ...
Reads a two-byte integer from a byte array at the specified offset. @param data The source data. @param offset The byte offset. @return A two-byte integer value.
[ "Reads", "a", "two", "-", "byte", "integer", "from", "a", "byte", "array", "at", "the", "specified", "offset", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.helpconverter/src/main/java/org/carewebframework/maven/plugin/help/chm/BinaryTransform.java#L96-L100
Azure/azure-sdk-for-java
notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java
NotificationHubsInner.debugSend
public DebugSendResponseInner debugSend(String resourceGroupName, String namespaceName, String notificationHubName) { return debugSendWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName).toBlocking().single().body(); }
java
public DebugSendResponseInner debugSend(String resourceGroupName, String namespaceName, String notificationHubName) { return debugSendWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName).toBlocking().single().body(); }
[ "public", "DebugSendResponseInner", "debugSend", "(", "String", "resourceGroupName", ",", "String", "namespaceName", ",", "String", "notificationHubName", ")", "{", "return", "debugSendWithServiceResponseAsync", "(", "resourceGroupName", ",", "namespaceName", ",", "notifica...
test send a push notification. @param resourceGroupName The name of the resource group. @param namespaceName The namespace name. @param notificationHubName The notification hub name. @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 DebugSendResponseInner object if successful.
[ "test", "send", "a", "push", "notification", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java#L715-L717
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Exception.java
Http2Exception.headerListSizeError
public static Http2Exception headerListSizeError(int id, Http2Error error, boolean onDecode, String fmt, Object... args) { return CONNECTION_STREAM_ID == id ? Http2Exception.connectionError(error, fmt, args) : new HeaderListSizeException(id, error, String.format(fmt, args), onDecode); }
java
public static Http2Exception headerListSizeError(int id, Http2Error error, boolean onDecode, String fmt, Object... args) { return CONNECTION_STREAM_ID == id ? Http2Exception.connectionError(error, fmt, args) : new HeaderListSizeException(id, error, String.format(fmt, args), onDecode); }
[ "public", "static", "Http2Exception", "headerListSizeError", "(", "int", "id", ",", "Http2Error", "error", ",", "boolean", "onDecode", ",", "String", "fmt", ",", "Object", "...", "args", ")", "{", "return", "CONNECTION_STREAM_ID", "==", "id", "?", "Http2Exceptio...
A specific stream error resulting from failing to decode headers that exceeds the max header size list. If the {@code id} is not {@link Http2CodecUtil#CONNECTION_STREAM_ID} then a {@link Http2Exception.StreamException} will be returned. Otherwise the error is considered a connection error and a {@link Http2Exception} is returned. @param id The stream id for which the error is isolated to. @param error The type of error as defined by the HTTP/2 specification. @param onDecode Whether this error was caught while decoding headers @param fmt String with the content and format for the additional debug data. @param args Objects which fit into the format defined by {@code fmt}. @return If the {@code id} is not {@link Http2CodecUtil#CONNECTION_STREAM_ID} then a {@link HeaderListSizeException} will be returned. Otherwise the error is considered a connection error and a {@link Http2Exception} is returned.
[ "A", "specific", "stream", "error", "resulting", "from", "failing", "to", "decode", "headers", "that", "exceeds", "the", "max", "header", "size", "list", ".", "If", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Exception.java#L167-L172
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvseById
private Evse getEvseById(ChargingStationType chargingStationType, Long id) { for (Evse evse:chargingStationType.getEvses()) { if(id.equals(evse.getId())) { return evse; } } throw new EntityNotFoundException(String.format("Unable to find evse with id '%s'", id)); }
java
private Evse getEvseById(ChargingStationType chargingStationType, Long id) { for (Evse evse:chargingStationType.getEvses()) { if(id.equals(evse.getId())) { return evse; } } throw new EntityNotFoundException(String.format("Unable to find evse with id '%s'", id)); }
[ "private", "Evse", "getEvseById", "(", "ChargingStationType", "chargingStationType", ",", "Long", "id", ")", "{", "for", "(", "Evse", "evse", ":", "chargingStationType", ".", "getEvses", "(", ")", ")", "{", "if", "(", "id", ".", "equals", "(", "evse", ".",...
Gets a Evse by id. @param chargingStationType charging station type. @param id evse id. @return evse @throws EntityNotFoundException if the Evse cannot be found.
[ "Gets", "a", "Evse", "by", "id", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L395-L402
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java
DefaultImageFormatChecker.isBmpHeader
private static boolean isBmpHeader(final byte[] imageHeaderBytes, final int headerSize) { if (headerSize < BMP_HEADER.length) { return false; } return ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, BMP_HEADER); }
java
private static boolean isBmpHeader(final byte[] imageHeaderBytes, final int headerSize) { if (headerSize < BMP_HEADER.length) { return false; } return ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, BMP_HEADER); }
[ "private", "static", "boolean", "isBmpHeader", "(", "final", "byte", "[", "]", "imageHeaderBytes", ",", "final", "int", "headerSize", ")", "{", "if", "(", "headerSize", "<", "BMP_HEADER", ".", "length", ")", "{", "return", "false", ";", "}", "return", "Ima...
Checks if first headerSize bytes of imageHeaderBytes constitute a valid header for a bmp image. Details on BMP header can be found <a href="http://www.onicos.com/staff/iz/formats/bmp.html"> </a> @param imageHeaderBytes @param headerSize @return true if imageHeaderBytes is a valid header for a bmp image
[ "Checks", "if", "first", "headerSize", "bytes", "of", "imageHeaderBytes", "constitute", "a", "valid", "header", "for", "a", "bmp", "image", ".", "Details", "on", "BMP", "header", "can", "be", "found", "<a", "href", "=", "http", ":", "//", "www", ".", "on...
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java#L212-L217
softindex/datakernel
boot/src/main/java/io/datakernel/service/ServiceGraphModule.java
ServiceGraphModule.register
public <T> ServiceGraphModule register(Class<? extends T> type, ServiceAdapter<T> factory) { registeredServiceAdapters.put(type, factory); return this; }
java
public <T> ServiceGraphModule register(Class<? extends T> type, ServiceAdapter<T> factory) { registeredServiceAdapters.put(type, factory); return this; }
[ "public", "<", "T", ">", "ServiceGraphModule", "register", "(", "Class", "<", "?", "extends", "T", ">", "type", ",", "ServiceAdapter", "<", "T", ">", "factory", ")", "{", "registeredServiceAdapters", ".", "put", "(", "type", ",", "factory", ")", ";", "re...
Puts an instance of class and its factory to the factoryMap @param <T> type of service @param type key with which the specified factory is to be associated @param factory value to be associated with the specified type @return ServiceGraphModule with change
[ "Puts", "an", "instance", "of", "class", "and", "its", "factory", "to", "the", "factoryMap" ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/boot/src/main/java/io/datakernel/service/ServiceGraphModule.java#L143-L146
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/FileUtils.java
FileUtils.getRootStorageDirectory
public static File getRootStorageDirectory(Context c, String directory_name){ File result; // First, try getting access to the sdcard partition if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Log.d(TAG,"Using sdcard"); result = new File(Environment.getExternalStorageDirectory(), directory_name); } else { // Else, use the internal storage directory for this application Log.d(TAG,"Using internal storage"); result = new File(c.getApplicationContext().getFilesDir(), directory_name); } if(!result.exists()) result.mkdir(); else if(result.isFile()){ return null; } Log.d("getRootStorageDirectory", result.getAbsolutePath()); return result; }
java
public static File getRootStorageDirectory(Context c, String directory_name){ File result; // First, try getting access to the sdcard partition if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Log.d(TAG,"Using sdcard"); result = new File(Environment.getExternalStorageDirectory(), directory_name); } else { // Else, use the internal storage directory for this application Log.d(TAG,"Using internal storage"); result = new File(c.getApplicationContext().getFilesDir(), directory_name); } if(!result.exists()) result.mkdir(); else if(result.isFile()){ return null; } Log.d("getRootStorageDirectory", result.getAbsolutePath()); return result; }
[ "public", "static", "File", "getRootStorageDirectory", "(", "Context", "c", ",", "String", "directory_name", ")", "{", "File", "result", ";", "// First, try getting access to the sdcard partition", "if", "(", "Environment", ".", "getExternalStorageState", "(", ")", ".",...
Returns a Java File initialized to a directory of given name at the root storage location, with preference to external storage. If the directory did not exist, it will be created at the conclusion of this call. If a file with conflicting name exists, this method returns null; @param c the context to determine the internal storage location, if external is unavailable @param directory_name the name of the directory desired at the storage location @return a File pointing to the storage directory, or null if a file with conflicting name exists
[ "Returns", "a", "Java", "File", "initialized", "to", "a", "directory", "of", "given", "name", "at", "the", "root", "storage", "location", "with", "preference", "to", "external", "storage", ".", "If", "the", "directory", "did", "not", "exist", "it", "will", ...
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/FileUtils.java#L54-L73
litsec/eidas-opensaml
opensaml3/src/main/java/se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.java
MetadataServiceListSignatureValidator.validateSignature
public void validateSignature(MetadataServiceList mdsl, X509Certificate signersCertificate) throws SignatureException { // The signature to validate. // final Signature signature = mdsl.getSignature(); if (signature == null) { log.warn("Metadata service list is not signed"); throw new SignatureException("Metadata service list has no signature"); } // Is the signature correct according to the SAML signature profile? // try { this.signatureProfileValidator.validate(signature); } catch (SignatureException e) { log.warn("Signature failed pre-validation: " + e.getMessage()); throw e; } // Validate the signature. // CriteriaSet criteria = new CriteriaSet(new X509CertificateCriterion(signersCertificate)); try { if (!this.signatureTrustEngine.validate(signature, criteria)) { String msg = "Signature validation failed"; log.warn(msg); throw new SignatureException(msg); } } catch (SecurityException e) { String msg = String.format("A problem was encountered evaluating the signature: %s", e.getMessage()); log.warn(msg); throw new SignatureException(msg, e); } log.debug("Signature on MetadataServiceList successfully verified"); }
java
public void validateSignature(MetadataServiceList mdsl, X509Certificate signersCertificate) throws SignatureException { // The signature to validate. // final Signature signature = mdsl.getSignature(); if (signature == null) { log.warn("Metadata service list is not signed"); throw new SignatureException("Metadata service list has no signature"); } // Is the signature correct according to the SAML signature profile? // try { this.signatureProfileValidator.validate(signature); } catch (SignatureException e) { log.warn("Signature failed pre-validation: " + e.getMessage()); throw e; } // Validate the signature. // CriteriaSet criteria = new CriteriaSet(new X509CertificateCriterion(signersCertificate)); try { if (!this.signatureTrustEngine.validate(signature, criteria)) { String msg = "Signature validation failed"; log.warn(msg); throw new SignatureException(msg); } } catch (SecurityException e) { String msg = String.format("A problem was encountered evaluating the signature: %s", e.getMessage()); log.warn(msg); throw new SignatureException(msg, e); } log.debug("Signature on MetadataServiceList successfully verified"); }
[ "public", "void", "validateSignature", "(", "MetadataServiceList", "mdsl", ",", "X509Certificate", "signersCertificate", ")", "throws", "SignatureException", "{", "// The signature to validate.", "//", "final", "Signature", "signature", "=", "mdsl", ".", "getSignature", "...
Validates the signature of the supplied {@code MetadataServiceList} element using the supplied certificate. @param mdsl the {@code MetadataServiceList} @param signersCertificate the certificate of the signer @throws SignatureException for validation errors
[ "Validates", "the", "signature", "of", "the", "supplied", "{", "@code", "MetadataServiceList", "}", "element", "using", "the", "supplied", "certificate", "." ]
train
https://github.com/litsec/eidas-opensaml/blob/522ba6dba433a9524cb8a02464cc3b087b47a2b7/opensaml3/src/main/java/se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.java#L78-L115
alkacon/opencms-core
src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java
CmsDefaultXmlContentHandler.addNestedFormatter
protected void addNestedFormatter(String elementName, CmsXmlContentDefinition contentDefinition) throws CmsXmlException { if (contentDefinition.getSchemaType(elementName) == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1, elementName)); } m_nestedFormatterElements.add(elementName); }
java
protected void addNestedFormatter(String elementName, CmsXmlContentDefinition contentDefinition) throws CmsXmlException { if (contentDefinition.getSchemaType(elementName) == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1, elementName)); } m_nestedFormatterElements.add(elementName); }
[ "protected", "void", "addNestedFormatter", "(", "String", "elementName", ",", "CmsXmlContentDefinition", "contentDefinition", ")", "throws", "CmsXmlException", "{", "if", "(", "contentDefinition", ".", "getSchemaType", "(", "elementName", ")", "==", "null", ")", "{", ...
Adds a nested formatter element.<p> @param elementName the element name @param contentDefinition the content definition @throws CmsXmlException in case something goes wrong
[ "Adds", "a", "nested", "formatter", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2042-L2050
spring-projects/spring-android
spring-android-core/src/main/java/org/springframework/core/CollectionFactory.java
CollectionFactory.createApproximateMap
@SuppressWarnings("unchecked") public static Map createApproximateMap(Object map, int initialCapacity) { if (map instanceof SortedMap) { return new TreeMap(((SortedMap) map).comparator()); } else { return new LinkedHashMap(initialCapacity); } }
java
@SuppressWarnings("unchecked") public static Map createApproximateMap(Object map, int initialCapacity) { if (map instanceof SortedMap) { return new TreeMap(((SortedMap) map).comparator()); } else { return new LinkedHashMap(initialCapacity); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "createApproximateMap", "(", "Object", "map", ",", "int", "initialCapacity", ")", "{", "if", "(", "map", "instanceof", "SortedMap", ")", "{", "return", "new", "TreeMap", "(", "(", ...
Create the most approximate map for the given map. <p>Creates a TreeMap or linked Map for a SortedMap or Map, respectively. @param map the original Map object @param initialCapacity the initial capacity @return the new Map instance @see java.util.TreeMap @see java.util.LinkedHashMap
[ "Create", "the", "most", "approximate", "map", "for", "the", "given", "map", ".", "<p", ">", "Creates", "a", "TreeMap", "or", "linked", "Map", "for", "a", "SortedMap", "or", "Map", "respectively", "." ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/CollectionFactory.java#L279-L287
lordcodes/SnackbarBuilder
snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarWrapper.java
SnackbarWrapper.setIcon
@NonNull @SuppressWarnings("WeakerAccess") public SnackbarWrapper setIcon(@DrawableRes int icon) { return setIcon(ContextCompat.getDrawable(context, icon)); }
java
@NonNull @SuppressWarnings("WeakerAccess") public SnackbarWrapper setIcon(@DrawableRes int icon) { return setIcon(ContextCompat.getDrawable(context, icon)); }
[ "@", "NonNull", "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "SnackbarWrapper", "setIcon", "(", "@", "DrawableRes", "int", "icon", ")", "{", "return", "setIcon", "(", "ContextCompat", ".", "getDrawable", "(", "context", ",", "icon", ")", ")...
Set the icon at the start of the Snackbar. If there is no icon it will be added, or if there is then it will be replaced. @param icon The icon drawable resource to display. @return This instance.
[ "Set", "the", "icon", "at", "the", "start", "of", "the", "Snackbar", ".", "If", "there", "is", "no", "icon", "it", "will", "be", "added", "or", "if", "there", "is", "then", "it", "will", "be", "replaced", "." ]
train
https://github.com/lordcodes/SnackbarBuilder/blob/a104a753c78ed66940c19d295e141a521cf81d73/snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarWrapper.java#L538-L542
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/utility/ResourceCache.java
ResourceCache.wrapCallback
public static TextureCallback wrapCallback( ResourceCache<GVRImage> cache, TextureCallback callback) { return new TextureCallbackWrapper(cache, callback); }
java
public static TextureCallback wrapCallback( ResourceCache<GVRImage> cache, TextureCallback callback) { return new TextureCallbackWrapper(cache, callback); }
[ "public", "static", "TextureCallback", "wrapCallback", "(", "ResourceCache", "<", "GVRImage", ">", "cache", ",", "TextureCallback", "callback", ")", "{", "return", "new", "TextureCallbackWrapper", "(", "cache", ",", "callback", ")", ";", "}" ]
Wrap the callback, to cache the {@link TextureCallback#loaded(GVRHybridObject, GVRAndroidResource) loaded()} resource
[ "Wrap", "the", "callback", "to", "cache", "the", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/utility/ResourceCache.java#L97-L100
square/okhttp
okhttp/src/main/java/okhttp3/internal/Util.java
Util.skipTrailingAsciiWhitespace
public static int skipTrailingAsciiWhitespace(String input, int pos, int limit) { for (int i = limit - 1; i >= pos; i--) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i + 1; } } return pos; }
java
public static int skipTrailingAsciiWhitespace(String input, int pos, int limit) { for (int i = limit - 1; i >= pos; i--) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i + 1; } } return pos; }
[ "public", "static", "int", "skipTrailingAsciiWhitespace", "(", "String", "input", ",", "int", "pos", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "limit", "-", "1", ";", "i", ">=", "pos", ";", "i", "--", ")", "{", "switch", "(", "inp...
Decrements {@code limit} until {@code input[limit - 1]} is not ASCII whitespace. Stops at {@code pos}.
[ "Decrements", "{" ]
train
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/Util.java#L316-L330
box/box-java-sdk
src/main/java/com/box/sdk/RetentionPolicyParams.java
RetentionPolicyParams.addCustomNotificationRecipient
public void addCustomNotificationRecipient(String userID) { BoxUser user = new BoxUser(null, userID); this.customNotificationRecipients.add(user.new Info()); }
java
public void addCustomNotificationRecipient(String userID) { BoxUser user = new BoxUser(null, userID); this.customNotificationRecipients.add(user.new Info()); }
[ "public", "void", "addCustomNotificationRecipient", "(", "String", "userID", ")", "{", "BoxUser", "user", "=", "new", "BoxUser", "(", "null", ",", "userID", ")", ";", "this", ".", "customNotificationRecipients", ".", "add", "(", "user", ".", "new", "Info", "...
Add a user by ID to the list of people to notify when the retention period is ending. @param userID The ID of the user to add to the list.
[ "Add", "a", "user", "by", "ID", "to", "the", "list", "of", "people", "to", "notify", "when", "the", "retention", "period", "is", "ending", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/RetentionPolicyParams.java#L85-L89
zaproxy/zaproxy
src/org/zaproxy/zap/extension/script/ScriptVars.java
ScriptVars.getScriptVar
public static String getScriptVar(ScriptContext context, String key) { return getScriptVarImpl(getScriptName(context), key); }
java
public static String getScriptVar(ScriptContext context, String key) { return getScriptVarImpl(getScriptName(context), key); }
[ "public", "static", "String", "getScriptVar", "(", "ScriptContext", "context", ",", "String", "key", ")", "{", "return", "getScriptVarImpl", "(", "getScriptName", "(", "context", ")", ",", "key", ")", ";", "}" ]
Gets a script variable. @param context the context of the script. @param key the key of the variable. @return the value of the variable, might be {@code null} if no value was previously set. @throws IllegalArgumentException if the {@code context} is {@code null} or it does not contain the name of the script.
[ "Gets", "a", "script", "variable", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/script/ScriptVars.java#L249-L251
RestComm/Restcomm-Connect
restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AccountsEndpoint.java
AccountsEndpoint.updateAccountAsXmlPost
@Path("/{accountSid}") @Consumes(APPLICATION_FORM_URLENCODED) @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateAccountAsXmlPost(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateAccount(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); }
java
@Path("/{accountSid}") @Consumes(APPLICATION_FORM_URLENCODED) @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateAccountAsXmlPost(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateAccount(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); }
[ "@", "Path", "(", "\"/{accountSid}\"", ")", "@", "Consumes", "(", "APPLICATION_FORM_URLENCODED", ")", "@", "POST", "@", "Produces", "(", "{", "MediaType", ".", "APPLICATION_XML", ",", "MediaType", ".", "APPLICATION_JSON", "}", ")", "public", "Response", "updateA...
The {accountSid} could be the email address of the account we need to update. Later we check if this is SID or EMAIL
[ "The", "{", "accountSid", "}", "could", "be", "the", "email", "address", "of", "the", "account", "we", "need", "to", "update", ".", "Later", "we", "check", "if", "this", "is", "SID", "or", "EMAIL" ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AccountsEndpoint.java#L894-L903
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/NamespaceDto.java
NamespaceDto.transformToDto
public static NamespaceDto transformToDto(Namespace namespace) { if (namespace == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } NamespaceDto result = createDtoObject(NamespaceDto.class, namespace); for (PrincipalUser user : namespace.getUsers()) { result.addUsername(user.getUserName()); } return result; }
java
public static NamespaceDto transformToDto(Namespace namespace) { if (namespace == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } NamespaceDto result = createDtoObject(NamespaceDto.class, namespace); for (PrincipalUser user : namespace.getUsers()) { result.addUsername(user.getUserName()); } return result; }
[ "public", "static", "NamespaceDto", "transformToDto", "(", "Namespace", "namespace", ")", "{", "if", "(", "namespace", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Null entity object cannot be converted to Dto object.\"", ",", "Status", "."...
Converts a namespace entity to a DTO. @param namespace The entity to convert. @return The namespace DTO. @throws WebApplicationException If an error occurs.
[ "Converts", "a", "namespace", "entity", "to", "a", "DTO", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/NamespaceDto.java#L74-L85
Crab2died/Excel4J
src/main/java/com/github/crab2died/ExcelUtils.java
ExcelUtils.noTemplateSheet2Excel
public void noTemplateSheet2Excel(List<NoTemplateSheetWrapper> sheets, OutputStream os) throws Excel4JException, IOException { try (Workbook workbook = exportExcelNoTemplateHandler(sheets, true)) { workbook.write(os); } }
java
public void noTemplateSheet2Excel(List<NoTemplateSheetWrapper> sheets, OutputStream os) throws Excel4JException, IOException { try (Workbook workbook = exportExcelNoTemplateHandler(sheets, true)) { workbook.write(os); } }
[ "public", "void", "noTemplateSheet2Excel", "(", "List", "<", "NoTemplateSheetWrapper", ">", "sheets", ",", "OutputStream", "os", ")", "throws", "Excel4JException", ",", "IOException", "{", "try", "(", "Workbook", "workbook", "=", "exportExcelNoTemplateHandler", "(", ...
无模板、基于注解、多sheet数据 @param sheets 待导出sheet数据 @param os 生成的Excel输出文件流 @throws Excel4JException 异常 @throws IOException 异常
[ "无模板、基于注解、多sheet数据" ]
train
https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/ExcelUtils.java#L1163-L1169
ACRA/acra
acra-core/src/main/java/org/acra/file/CrashReportFileNameParser.java
CrashReportFileNameParser.getTimestamp
@NonNull public Calendar getTimestamp(@NonNull String reportFileName) { final String timestamp = reportFileName.replace(ACRAConstants.REPORTFILE_EXTENSION, "").replace(ACRAConstants.SILENT_SUFFIX, ""); final Calendar calendar = Calendar.getInstance(); try { calendar.setTime(new SimpleDateFormat(ACRAConstants.DATE_TIME_FORMAT_STRING, Locale.ENGLISH).parse(timestamp)); } catch (ParseException ignored) { } return calendar; }
java
@NonNull public Calendar getTimestamp(@NonNull String reportFileName) { final String timestamp = reportFileName.replace(ACRAConstants.REPORTFILE_EXTENSION, "").replace(ACRAConstants.SILENT_SUFFIX, ""); final Calendar calendar = Calendar.getInstance(); try { calendar.setTime(new SimpleDateFormat(ACRAConstants.DATE_TIME_FORMAT_STRING, Locale.ENGLISH).parse(timestamp)); } catch (ParseException ignored) { } return calendar; }
[ "@", "NonNull", "public", "Calendar", "getTimestamp", "(", "@", "NonNull", "String", "reportFileName", ")", "{", "final", "String", "timestamp", "=", "reportFileName", ".", "replace", "(", "ACRAConstants", ".", "REPORTFILE_EXTENSION", ",", "\"\"", ")", ".", "rep...
Gets the timestamp of a report from its name @param reportFileName Name of the report to get the timestamp from. @return timestamp of the report
[ "Gets", "the", "timestamp", "of", "a", "report", "from", "its", "name" ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/file/CrashReportFileNameParser.java#L71-L80
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/Scope.java
Scope.getScopeId
public static int getScopeId(String scope) throws JspTagException { if(scope==null || PAGE.equals(scope)) return PageContext.PAGE_SCOPE; else if(REQUEST.equals(scope)) return PageContext.REQUEST_SCOPE; else if(SESSION.equals(scope)) return PageContext.SESSION_SCOPE; else if(APPLICATION.equals(scope)) return PageContext.APPLICATION_SCOPE; else throw new LocalizedJspTagException(ApplicationResources.accessor, "Scope.scope.invalid", scope); }
java
public static int getScopeId(String scope) throws JspTagException { if(scope==null || PAGE.equals(scope)) return PageContext.PAGE_SCOPE; else if(REQUEST.equals(scope)) return PageContext.REQUEST_SCOPE; else if(SESSION.equals(scope)) return PageContext.SESSION_SCOPE; else if(APPLICATION.equals(scope)) return PageContext.APPLICATION_SCOPE; else throw new LocalizedJspTagException(ApplicationResources.accessor, "Scope.scope.invalid", scope); }
[ "public", "static", "int", "getScopeId", "(", "String", "scope", ")", "throws", "JspTagException", "{", "if", "(", "scope", "==", "null", "||", "PAGE", ".", "equals", "(", "scope", ")", ")", "return", "PageContext", ".", "PAGE_SCOPE", ";", "else", "if", ...
Gets the PageContext scope value for the textual scope name. @exception JspTagException if invalid scope
[ "Gets", "the", "PageContext", "scope", "value", "for", "the", "textual", "scope", "name", "." ]
train
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/Scope.java#L51-L57
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setFontFamily
public void setFontFamily(String header_font_family, String details_font_family) { this.headerLabel .setStyle("-fx-font-family: \"" + header_font_family + "\";"); this.detailsLabel .setStyle("-fx-font-family: \"" + details_font_family + "\";"); }
java
public void setFontFamily(String header_font_family, String details_font_family) { this.headerLabel .setStyle("-fx-font-family: \"" + header_font_family + "\";"); this.detailsLabel .setStyle("-fx-font-family: \"" + details_font_family + "\";"); }
[ "public", "void", "setFontFamily", "(", "String", "header_font_family", ",", "String", "details_font_family", ")", "{", "this", ".", "headerLabel", ".", "setStyle", "(", "\"-fx-font-family: \\\"\"", "+", "header_font_family", "+", "\"\\\";\"", ")", ";", "this", ".",...
Sets both font families for the header and the details label with two font families <code>String</code> parameters given. @param header_font_family The header font family in <code>Strings</code> @param details_font_family The details font family in <code>Strings</code>
[ "Sets", "both", "font", "families", "for", "the", "header", "and", "the", "details", "label", "with", "two", "font", "families", "<code", ">", "String<", "/", "code", ">", "parameters", "given", "." ]
train
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L792-L797
landawn/AbacusUtil
src/com/landawn/abacus/util/stream/IteratorStream.java
IteratorStream.queued
@Override public Stream<T> queued(int queueSize) { final Iterator<T> iter = iterator(); if (iter instanceof QueuedIterator && ((QueuedIterator<? extends T>) iter).max() >= queueSize) { return newStream(elements, sorted, cmp); } else { return newStream(Stream.parallelConcatt(Arrays.asList(iter), 1, queueSize), sorted, cmp); } }
java
@Override public Stream<T> queued(int queueSize) { final Iterator<T> iter = iterator(); if (iter instanceof QueuedIterator && ((QueuedIterator<? extends T>) iter).max() >= queueSize) { return newStream(elements, sorted, cmp); } else { return newStream(Stream.parallelConcatt(Arrays.asList(iter), 1, queueSize), sorted, cmp); } }
[ "@", "Override", "public", "Stream", "<", "T", ">", "queued", "(", "int", "queueSize", ")", "{", "final", "Iterator", "<", "T", ">", "iter", "=", "iterator", "(", ")", ";", "if", "(", "iter", "instanceof", "QueuedIterator", "&&", "(", "(", "QueuedItera...
Returns a Stream with elements from a temporary queue which is filled by reading the elements from the specified iterator asynchronously. @param stream @param queueSize Default value is 8 @return
[ "Returns", "a", "Stream", "with", "elements", "from", "a", "temporary", "queue", "which", "is", "filled", "by", "reading", "the", "elements", "from", "the", "specified", "iterator", "asynchronously", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/IteratorStream.java#L3336-L3345
alkacon/opencms-core
src/org/opencms/ui/components/CmsFileTable.java
CmsFileTable.filterTable
public void filterTable(String search) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_TITLE, search, true, false))); } if ((m_fileTable.getValue() != null) & !((Set<?>)m_fileTable.getValue()).isEmpty()) { m_fileTable.setCurrentPageFirstItemId(((Set<?>)m_fileTable.getValue()).iterator().next()); } }
java
public void filterTable(String search) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT, search, true, false), new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_TITLE, search, true, false))); } if ((m_fileTable.getValue() != null) & !((Set<?>)m_fileTable.getValue()).isEmpty()) { m_fileTable.setCurrentPageFirstItemId(((Set<?>)m_fileTable.getValue()).iterator().next()); } }
[ "public", "void", "filterTable", "(", "String", "search", ")", "{", "m_container", ".", "removeAllContainerFilters", "(", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "search", ")", ")", "{", "m_container", ".", "addContainerFilter...
Filters the displayed resources.<p> Only resources where either the resource name, the title or the nav-text contains the given substring are shown.<p> @param search the search term
[ "Filters", "the", "displayed", "resources", ".", "<p", ">", "Only", "resources", "where", "either", "the", "resource", "name", "the", "title", "or", "the", "nav", "-", "text", "contains", "the", "given", "substring", "are", "shown", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsFileTable.java#L555-L568
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java
DefaultAsyncSearchQueryResult.fromHttp400
@Deprecated public static AsyncSearchQueryResult fromHttp400(String payload) { //dummy default values SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsMalformedRequestException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
java
@Deprecated public static AsyncSearchQueryResult fromHttp400(String payload) { //dummy default values SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsMalformedRequestException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
[ "@", "Deprecated", "public", "static", "AsyncSearchQueryResult", "fromHttp400", "(", "String", "payload", ")", "{", "//dummy default values", "SearchStatus", "status", "=", "new", "DefaultSearchStatus", "(", "1L", ",", "1L", ",", "0L", ")", ";", "SearchMetrics", "...
A utility method to convert an HTTP 400 response from the search service into a proper {@link AsyncSearchQueryResult}. HTTP 400 indicates the request was malformed and couldn't be parsed on the server. As of Couchbase Server 4.5 such a response is a text/plain body that describes the parsing error. The whole body is emitted/thrown, wrapped in a {@link FtsMalformedRequestException}. @param payload the HTTP 400 response body describing the parsing failure. @return an {@link AsyncSearchQueryResult} that will emit a {@link FtsMalformedRequestException} when calling its {@link AsyncSearchQueryResult#hits() hits()} method. @deprecated FTS is still in BETA so the response format is likely to change in a future version, and be unified with the HTTP 200 response format.
[ "A", "utility", "method", "to", "convert", "an", "HTTP", "400", "response", "from", "the", "search", "service", "into", "a", "proper", "{", "@link", "AsyncSearchQueryResult", "}", ".", "HTTP", "400", "indicates", "the", "request", "was", "malformed", "and", ...
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java#L262-L275
headius/invokebinder
src/main/java/com/headius/invokebinder/Binder.java
Binder.invokeSpecial
public MethodHandle invokeSpecial(MethodHandles.Lookup lookup, String name, Class<?> caller) throws NoSuchMethodException, IllegalAccessException { return invoke(lookup.findSpecial(type().parameterType(0), name, type().dropParameterTypes(0, 1), caller)); }
java
public MethodHandle invokeSpecial(MethodHandles.Lookup lookup, String name, Class<?> caller) throws NoSuchMethodException, IllegalAccessException { return invoke(lookup.findSpecial(type().parameterType(0), name, type().dropParameterTypes(0, 1), caller)); }
[ "public", "MethodHandle", "invokeSpecial", "(", "MethodHandles", ".", "Lookup", "lookup", ",", "String", "name", ",", "Class", "<", "?", ">", "caller", ")", "throws", "NoSuchMethodException", ",", "IllegalAccessException", "{", "return", "invoke", "(", "lookup", ...
Apply the chain of transforms and bind them to a special method specified using the end signature plus the given class and name. The method will be retrieved using the given Lookup and must match the end signature exactly. If the final handle's type does not exactly match the initial type for this Binder, an additional cast will be attempted. @param lookup the MethodHandles.Lookup to use to look up the method @param name the name of the method to invoke @param caller the calling class @return the full handle chain, bound to the given method @throws java.lang.NoSuchMethodException if the method does not exist @throws java.lang.IllegalAccessException if the method is not accessible
[ "Apply", "the", "chain", "of", "transforms", "and", "bind", "them", "to", "a", "special", "method", "specified", "using", "the", "end", "signature", "plus", "the", "given", "class", "and", "name", ".", "The", "method", "will", "be", "retrieved", "using", "...
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Binder.java#L1298-L1300
apereo/cas
support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java
LdapUtils.newLdaptiveSearchRequest
public static SearchRequest newLdaptiveSearchRequest(final String baseDn, final SearchFilter filter) { return newLdaptiveSearchRequest(baseDn, filter, ReturnAttributes.ALL_USER.value(), ReturnAttributes.ALL_USER.value()); }
java
public static SearchRequest newLdaptiveSearchRequest(final String baseDn, final SearchFilter filter) { return newLdaptiveSearchRequest(baseDn, filter, ReturnAttributes.ALL_USER.value(), ReturnAttributes.ALL_USER.value()); }
[ "public", "static", "SearchRequest", "newLdaptiveSearchRequest", "(", "final", "String", "baseDn", ",", "final", "SearchFilter", "filter", ")", "{", "return", "newLdaptiveSearchRequest", "(", "baseDn", ",", "filter", ",", "ReturnAttributes", ".", "ALL_USER", ".", "v...
New ldaptive search request. Returns all attributes. @param baseDn the base dn @param filter the filter @return the search request
[ "New", "ldaptive", "search", "request", ".", "Returns", "all", "attributes", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L488-L491
netty/netty
example/src/main/java/io/netty/example/http/upload/HttpUploadClient.java
HttpUploadClient.formpost
private static List<InterfaceHttpData> formpost( Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the next request // for the example (limit action on client side). Take this as a broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
java
private static List<InterfaceHttpData> formpost( Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the next request // for the example (limit action on client side). Take this as a broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
[ "private", "static", "List", "<", "InterfaceHttpData", ">", "formpost", "(", "Bootstrap", "bootstrap", ",", "String", "host", ",", "int", "port", ",", "URI", "uriSimple", ",", "File", "file", ",", "HttpDataFactory", "factory", ",", "List", "<", "Entry", "<",...
Standard post without multipart but already support on Factory (memory management) @return the list of HttpData object (attribute and file) to be reused on next post
[ "Standard", "post", "without", "multipart", "but", "already", "support", "on", "Factory", "(", "memory", "management", ")" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http/upload/HttpUploadClient.java#L204-L260
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayRemove
public static Expression arrayRemove(JsonArray array, Expression value) { return arrayRemove(x(array), value); }
java
public static Expression arrayRemove(JsonArray array, Expression value) { return arrayRemove(x(array), value); }
[ "public", "static", "Expression", "arrayRemove", "(", "JsonArray", "array", ",", "Expression", "value", ")", "{", "return", "arrayRemove", "(", "x", "(", "array", ")", ",", "value", ")", ";", "}" ]
Returned expression results in new array with all occurrences of value removed.
[ "Returned", "expression", "results", "in", "new", "array", "with", "all", "occurrences", "of", "value", "removed", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L358-L360
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java
HiveDataset.sortPartitions
public static List<Partition> sortPartitions(List<Partition> partitions) { Collections.sort(partitions, new Comparator<Partition>() { @Override public int compare(Partition o1, Partition o2) { return o1.getCompleteName().compareTo(o2.getCompleteName()); } }); return partitions; }
java
public static List<Partition> sortPartitions(List<Partition> partitions) { Collections.sort(partitions, new Comparator<Partition>() { @Override public int compare(Partition o1, Partition o2) { return o1.getCompleteName().compareTo(o2.getCompleteName()); } }); return partitions; }
[ "public", "static", "List", "<", "Partition", ">", "sortPartitions", "(", "List", "<", "Partition", ">", "partitions", ")", "{", "Collections", ".", "sort", "(", "partitions", ",", "new", "Comparator", "<", "Partition", ">", "(", ")", "{", "@", "Override",...
Sort all partitions inplace on the basis of complete name ie dbName.tableName.partitionName
[ "Sort", "all", "partitions", "inplace", "on", "the", "basis", "of", "complete", "name", "ie", "dbName", ".", "tableName", ".", "partitionName" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveDataset.java#L303-L311
Stratio/bdt
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
DatabaseSpec.connectToElasticSearch
@Given("^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$") public void connectToElasticSearch(String host, String foo, String nativePort, String bar, String clusterName) throws DBException, UnknownHostException, NumberFormatException { LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); if (clusterName != null) { settings_map.put("cluster.name", clusterName); } else { settings_map.put("cluster.name", ES_DEFAULT_CLUSTER_NAME); } commonspec.getElasticSearchClient().setSettings(settings_map); if (nativePort != null) { commonspec.getElasticSearchClient().setNativePort(Integer.valueOf(nativePort)); } else { commonspec.getElasticSearchClient().setNativePort(ES_DEFAULT_NATIVE_PORT); } commonspec.getElasticSearchClient().setHost(host); commonspec.getElasticSearchClient().connect(); }
java
@Given("^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$") public void connectToElasticSearch(String host, String foo, String nativePort, String bar, String clusterName) throws DBException, UnknownHostException, NumberFormatException { LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); if (clusterName != null) { settings_map.put("cluster.name", clusterName); } else { settings_map.put("cluster.name", ES_DEFAULT_CLUSTER_NAME); } commonspec.getElasticSearchClient().setSettings(settings_map); if (nativePort != null) { commonspec.getElasticSearchClient().setNativePort(Integer.valueOf(nativePort)); } else { commonspec.getElasticSearchClient().setNativePort(ES_DEFAULT_NATIVE_PORT); } commonspec.getElasticSearchClient().setHost(host); commonspec.getElasticSearchClient().connect(); }
[ "@", "Given", "(", "\"^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$\"", ")", "public", "void", "connectToElasticSearch", "(", "String", "host", ",", "String", "foo", ",", "String", "nativePort", ",", "String", "b...
Connect to ElasticSearch using custom parameters @param host ES host @param foo regex needed to match method @param nativePort ES port @param bar regex needed to match method @param clusterName ES clustername @throws DBException exception @throws UnknownHostException exception @throws NumberFormatException exception
[ "Connect", "to", "ElasticSearch", "using", "custom", "parameters" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L135-L151
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java
LevelRipConverter.start
public static int start(Media levelrip, MapTile map, ProgressListener listener) { return start(levelrip, map, listener, null); }
java
public static int start(Media levelrip, MapTile map, ProgressListener listener) { return start(levelrip, map, listener, null); }
[ "public", "static", "int", "start", "(", "Media", "levelrip", ",", "MapTile", "map", ",", "ProgressListener", "listener", ")", "{", "return", "start", "(", "levelrip", ",", "map", ",", "listener", ",", "null", ")", ";", "}" ]
Run the converter. @param levelrip The file containing the levelrip as an image. @param map The destination map reference. @param listener The progress listener. @return The total number of not found tiles. @throws LionEngineException If media is <code>null</code> or image cannot be read.
[ "Run", "the", "converter", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/LevelRipConverter.java#L58-L61
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java
EventSerializer.isEvent
private static boolean isEvent(ByteBuffer buffer, Class<?> eventClass) throws IOException { if (buffer.remaining() < 4) { throw new IOException("Incomplete event"); } final int bufferPos = buffer.position(); final ByteOrder bufferOrder = buffer.order(); buffer.order(ByteOrder.BIG_ENDIAN); try { int type = buffer.getInt(); if (eventClass.equals(EndOfPartitionEvent.class)) { return type == END_OF_PARTITION_EVENT; } else if (eventClass.equals(CheckpointBarrier.class)) { return type == CHECKPOINT_BARRIER_EVENT; } else if (eventClass.equals(EndOfSuperstepEvent.class)) { return type == END_OF_SUPERSTEP_EVENT; } else if (eventClass.equals(CancelCheckpointMarker.class)) { return type == CANCEL_CHECKPOINT_MARKER_EVENT; } else { throw new UnsupportedOperationException("Unsupported eventClass = " + eventClass); } } finally { buffer.order(bufferOrder); // restore the original position in the buffer (recall: we only peak into it!) buffer.position(bufferPos); } }
java
private static boolean isEvent(ByteBuffer buffer, Class<?> eventClass) throws IOException { if (buffer.remaining() < 4) { throw new IOException("Incomplete event"); } final int bufferPos = buffer.position(); final ByteOrder bufferOrder = buffer.order(); buffer.order(ByteOrder.BIG_ENDIAN); try { int type = buffer.getInt(); if (eventClass.equals(EndOfPartitionEvent.class)) { return type == END_OF_PARTITION_EVENT; } else if (eventClass.equals(CheckpointBarrier.class)) { return type == CHECKPOINT_BARRIER_EVENT; } else if (eventClass.equals(EndOfSuperstepEvent.class)) { return type == END_OF_SUPERSTEP_EVENT; } else if (eventClass.equals(CancelCheckpointMarker.class)) { return type == CANCEL_CHECKPOINT_MARKER_EVENT; } else { throw new UnsupportedOperationException("Unsupported eventClass = " + eventClass); } } finally { buffer.order(bufferOrder); // restore the original position in the buffer (recall: we only peak into it!) buffer.position(bufferPos); } }
[ "private", "static", "boolean", "isEvent", "(", "ByteBuffer", "buffer", ",", "Class", "<", "?", ">", "eventClass", ")", "throws", "IOException", "{", "if", "(", "buffer", ".", "remaining", "(", ")", "<", "4", ")", "{", "throw", "new", "IOException", "(",...
Identifies whether the given buffer encodes the given event. Custom events are not supported. <p><strong>Pre-condition</strong>: This buffer must encode some event!</p> @param buffer the buffer to peak into @param eventClass the expected class of the event type @return whether the event class of the <tt>buffer</tt> matches the given <tt>eventClass</tt>
[ "Identifies", "whether", "the", "given", "buffer", "encodes", "the", "given", "event", ".", "Custom", "events", "are", "not", "supported", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java#L114-L143
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.createFieldAccessor
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess) { return createFieldAccessor(maker, field, fieldAccess, null); }
java
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess) { return createFieldAccessor(maker, field, fieldAccess, null); }
[ "static", "JCExpression", "createFieldAccessor", "(", "JavacTreeMaker", "maker", ",", "JavacNode", "field", ",", "FieldAccess", "fieldAccess", ")", "{", "return", "createFieldAccessor", "(", "maker", ",", "field", ",", "fieldAccess", ",", "null", ")", ";", "}" ]
Creates an expression that reads the field. Will either be {@code this.field} or {@code this.getField()} depending on whether or not there's a getter.
[ "Creates", "an", "expression", "that", "reads", "the", "field", ".", "Will", "either", "be", "{" ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L941-L943
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Conversion.java
Conversion.byteArrayToUuid
@GwtIncompatible("incompatible method") public static UUID byteArrayToUuid(final byte[] src, final int srcPos) { if (src.length - srcPos < 16) { throw new IllegalArgumentException("Need at least 16 bytes for UUID"); } return new UUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8)); }
java
@GwtIncompatible("incompatible method") public static UUID byteArrayToUuid(final byte[] src, final int srcPos) { if (src.length - srcPos < 16) { throw new IllegalArgumentException("Need at least 16 bytes for UUID"); } return new UUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8)); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "UUID", "byteArrayToUuid", "(", "final", "byte", "[", "]", "src", ",", "final", "int", "srcPos", ")", "{", "if", "(", "src", ".", "length", "-", "srcPos", "<", "16", ")", "{...
<p> Converts bytes from an array into a UUID using the default (little endian, Lsb0) byte and bit ordering. </p> @param src the byte array to convert @param srcPos the position in {@code src} where to copy the result from @return a UUID @throws NullPointerException if {@code src} is {@code null} @throws IllegalArgumentException if array does not contain at least 16 bytes beginning with {@code srcPos}
[ "<p", ">", "Converts", "bytes", "from", "an", "array", "into", "a", "UUID", "using", "the", "default", "(", "little", "endian", "Lsb0", ")", "byte", "and", "bit", "ordering", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Conversion.java#L1545-L1551
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.putAndEncrypt
public JsonObject putAndEncrypt(String name, Map<String, ?> value, String providerName) { addValueEncryptionInfo(name, providerName, true); return put(name, JsonObject.from(value)); }
java
public JsonObject putAndEncrypt(String name, Map<String, ?> value, String providerName) { addValueEncryptionInfo(name, providerName, true); return put(name, JsonObject.from(value)); }
[ "public", "JsonObject", "putAndEncrypt", "(", "String", "name", ",", "Map", "<", "String", ",", "?", ">", "value", ",", "String", "providerName", ")", "{", "addValueEncryptionInfo", "(", "name", ",", "providerName", ",", "true", ")", ";", "return", "put", ...
Attempt to convert a {@link Map} to a {@link JsonObject} value and store it, as encrypted identified by the field name. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the JSON field. @param value the value of the JSON field. @param providerName Crypto provider name for encryption. @return the {@link JsonObject}. @see #from(Map)
[ "Attempt", "to", "convert", "a", "{", "@link", "Map", "}", "to", "a", "{", "@link", "JsonObject", "}", "value", "and", "store", "it", "as", "encrypted", "identified", "by", "the", "field", "name", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L742-L745
threerings/nenya
core/src/main/java/com/threerings/openal/SoundManager.java
SoundManager.loadClip
public void loadClip (ClipProvider provider, String path, Observer observer) { getClip(provider, path, observer); }
java
public void loadClip (ClipProvider provider, String path, Observer observer) { getClip(provider, path, observer); }
[ "public", "void", "loadClip", "(", "ClipProvider", "provider", ",", "String", "path", ",", "Observer", "observer", ")", "{", "getClip", "(", "provider", ",", "path", ",", "observer", ")", ";", "}" ]
Loads a clip buffer for the sound clip loaded via the specified provider with the specified path. The loaded clip is placed in the cache.
[ "Loads", "a", "clip", "buffer", "for", "the", "sound", "clip", "loaded", "via", "the", "specified", "provider", "with", "the", "specified", "path", ".", "The", "loaded", "clip", "is", "placed", "in", "the", "cache", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/openal/SoundManager.java#L191-L194
primefaces-extensions/core
src/main/java/org/primefaces/extensions/component/sheet/Sheet.java
Sheet.getRenderValueForCell
public String getRenderValueForCell(final FacesContext context, final String rowKey, final int col) { // if we have a submitted value still, use it // note: can't check for null, as null may be the submitted value final SheetRowColIndex index = new SheetRowColIndex(rowKey, col); if (submittedValues.containsKey(index)) { return submittedValues.get(index); } final Object value = getValueForCell(context, rowKey, col); if (value == null) { return null; } final SheetColumn column = getColumns().get(col); final Converter converter = ComponentUtils.getConverter(context, column); if (converter == null) { return value.toString(); } else { return converter.getAsString(context, this, value); } }
java
public String getRenderValueForCell(final FacesContext context, final String rowKey, final int col) { // if we have a submitted value still, use it // note: can't check for null, as null may be the submitted value final SheetRowColIndex index = new SheetRowColIndex(rowKey, col); if (submittedValues.containsKey(index)) { return submittedValues.get(index); } final Object value = getValueForCell(context, rowKey, col); if (value == null) { return null; } final SheetColumn column = getColumns().get(col); final Converter converter = ComponentUtils.getConverter(context, column); if (converter == null) { return value.toString(); } else { return converter.getAsString(context, this, value); } }
[ "public", "String", "getRenderValueForCell", "(", "final", "FacesContext", "context", ",", "final", "String", "rowKey", ",", "final", "int", "col", ")", "{", "// if we have a submitted value still, use it", "// note: can't check for null, as null may be the submitted value", "f...
Gets the render string for the value the given cell. Applys the available converters to convert the value. @param context @param rowKey @param col @return
[ "Gets", "the", "render", "string", "for", "the", "value", "the", "given", "cell", ".", "Applys", "the", "available", "converters", "to", "convert", "the", "value", "." ]
train
https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/Sheet.java#L363-L385
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/FileIoUtil.java
FileIoUtil.readFileFrom
public static List<String> readFileFrom(String _fileName, Charset _charset, SearchOrder... _searchOrder) { InputStream stream = openInputStreamForFile(_fileName, _searchOrder); if (stream != null) { return readTextFileFromStream(stream, _charset, true); } return null; }
java
public static List<String> readFileFrom(String _fileName, Charset _charset, SearchOrder... _searchOrder) { InputStream stream = openInputStreamForFile(_fileName, _searchOrder); if (stream != null) { return readTextFileFromStream(stream, _charset, true); } return null; }
[ "public", "static", "List", "<", "String", ">", "readFileFrom", "(", "String", "_fileName", ",", "Charset", "_charset", ",", "SearchOrder", "...", "_searchOrder", ")", "{", "InputStream", "stream", "=", "openInputStreamForFile", "(", "_fileName", ",", "_searchOrde...
Read a file from different sources depending on _searchOrder. Will return the first successfully read file which can be loaded either from custom path, classpath or system path. @param _fileName file to read @param _charset charset used for reading @param _searchOrder search order @return List of String with file content or null if file could not be found
[ "Read", "a", "file", "from", "different", "sources", "depending", "on", "_searchOrder", ".", "Will", "return", "the", "first", "successfully", "read", "file", "which", "can", "be", "loaded", "either", "from", "custom", "path", "classpath", "or", "system", "pat...
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/FileIoUtil.java#L476-L482
Azure/azure-sdk-for-java
privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/RecordSetsInner.java
RecordSetsInner.listAsync
public Observable<Page<RecordSetInner>> listAsync(final String resourceGroupName, final String privateZoneName) { return listWithServiceResponseAsync(resourceGroupName, privateZoneName) .map(new Func1<ServiceResponse<Page<RecordSetInner>>, Page<RecordSetInner>>() { @Override public Page<RecordSetInner> call(ServiceResponse<Page<RecordSetInner>> response) { return response.body(); } }); }
java
public Observable<Page<RecordSetInner>> listAsync(final String resourceGroupName, final String privateZoneName) { return listWithServiceResponseAsync(resourceGroupName, privateZoneName) .map(new Func1<ServiceResponse<Page<RecordSetInner>>, Page<RecordSetInner>>() { @Override public Page<RecordSetInner> call(ServiceResponse<Page<RecordSetInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RecordSetInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "privateZoneName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "privateZoneNa...
Lists all record sets in a Private DNS zone. @param resourceGroupName The name of the resource group. @param privateZoneName The name of the Private DNS zone (without a terminating dot). @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RecordSetInner&gt; object
[ "Lists", "all", "record", "sets", "in", "a", "Private", "DNS", "zone", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/RecordSetsInner.java#L1147-L1155
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/Hdf5Archive.java
Hdf5Archive.readAttributeAsJson
public String readAttributeAsJson(String attributeName, String... groups) throws UnsupportedKerasConfigurationException { synchronized (Hdf5Archive.LOCK_OBJECT) { if (groups.length == 0) { Attribute a = this.file.openAttribute(attributeName); String s = readAttributeAsJson(a); a.deallocate(); return s; } Group[] groupArray = openGroups(groups); Attribute a = groupArray[groups.length - 1].openAttribute(attributeName); String s = readAttributeAsJson(a); a.deallocate(); closeGroups(groupArray); return s; } }
java
public String readAttributeAsJson(String attributeName, String... groups) throws UnsupportedKerasConfigurationException { synchronized (Hdf5Archive.LOCK_OBJECT) { if (groups.length == 0) { Attribute a = this.file.openAttribute(attributeName); String s = readAttributeAsJson(a); a.deallocate(); return s; } Group[] groupArray = openGroups(groups); Attribute a = groupArray[groups.length - 1].openAttribute(attributeName); String s = readAttributeAsJson(a); a.deallocate(); closeGroups(groupArray); return s; } }
[ "public", "String", "readAttributeAsJson", "(", "String", "attributeName", ",", "String", "...", "groups", ")", "throws", "UnsupportedKerasConfigurationException", "{", "synchronized", "(", "Hdf5Archive", ".", "LOCK_OBJECT", ")", "{", "if", "(", "groups", ".", "leng...
Read JSON-formatted string attribute from group path. @param attributeName Name of attribute @param groups Array of zero or more ancestor groups from root to parent. @return HDF5 attribute as JSON @throws UnsupportedKerasConfigurationException Unsupported Keras config
[ "Read", "JSON", "-", "formatted", "string", "attribute", "from", "group", "path", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/Hdf5Archive.java#L126-L142
ModeShape/modeshape
modeshape-schematic/src/main/java/org/modeshape/schematic/DocumentFactory.java
DocumentFactory.newDocument
public static EditableDocument newDocument( String name, Object value ) { return new DocumentEditor(new BasicDocument(name, value), DEFAULT_FACTORY); }
java
public static EditableDocument newDocument( String name, Object value ) { return new DocumentEditor(new BasicDocument(name, value), DEFAULT_FACTORY); }
[ "public", "static", "EditableDocument", "newDocument", "(", "String", "name", ",", "Object", "value", ")", "{", "return", "new", "DocumentEditor", "(", "new", "BasicDocument", "(", "name", ",", "value", ")", ",", "DEFAULT_FACTORY", ")", ";", "}" ]
Create a new editable document, initialized with a single field, that can be used as a new document entry in a SchematicDb or as nested documents for other documents. @param name the name of the initial field in the resulting document; if null, the field will not be added to the returned document @param value the value of the initial field in the resulting document @return the editable document; never null
[ "Create", "a", "new", "editable", "document", "initialized", "with", "a", "single", "field", "that", "can", "be", "used", "as", "a", "new", "document", "entry", "in", "a", "SchematicDb", "or", "as", "nested", "documents", "for", "other", "documents", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-schematic/src/main/java/org/modeshape/schematic/DocumentFactory.java#L69-L72
line/armeria
core/src/main/java/com/linecorp/armeria/server/cors/AbstractCorsPolicyBuilder.java
AbstractCorsPolicyBuilder.preflightResponseHeader
public B preflightResponseHeader(CharSequence name, Iterable<?> values) { requireNonNull(name, "name"); requireNonNull(values, "values"); checkArgument(!Iterables.isEmpty(values), "values should not be empty."); final ImmutableList.Builder builder = new Builder(); int i = 0; for (Object value : values) { if (value == null) { throw new NullPointerException("value[" + i + ']'); } builder.add(value); i++; } preflightResponseHeaders.put(HttpHeaderNames.of(name), new ConstantValueSupplier(builder.build())); return self(); }
java
public B preflightResponseHeader(CharSequence name, Iterable<?> values) { requireNonNull(name, "name"); requireNonNull(values, "values"); checkArgument(!Iterables.isEmpty(values), "values should not be empty."); final ImmutableList.Builder builder = new Builder(); int i = 0; for (Object value : values) { if (value == null) { throw new NullPointerException("value[" + i + ']'); } builder.add(value); i++; } preflightResponseHeaders.put(HttpHeaderNames.of(name), new ConstantValueSupplier(builder.build())); return self(); }
[ "public", "B", "preflightResponseHeader", "(", "CharSequence", "name", ",", "Iterable", "<", "?", ">", "values", ")", "{", "requireNonNull", "(", "name", ",", "\"name\"", ")", ";", "requireNonNull", "(", "values", ",", "\"values\"", ")", ";", "checkArgument", ...
Specifies HTTP response headers that should be added to a CORS preflight response. <p>An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. @param name the name of the HTTP header. @param values the values for the HTTP header. @return {@code this} to support method chaining.
[ "Specifies", "HTTP", "response", "headers", "that", "should", "be", "added", "to", "a", "CORS", "preflight", "response", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/cors/AbstractCorsPolicyBuilder.java#L315-L330
wildfly/wildfly-maven-plugin
plugin/src/main/java/org/wildfly/plugin/common/ServerOperations.java
ServerOperations.createRemoveOperation
public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) { final ModelNode op = createRemoveOperation(address); op.get(RECURSIVE).set(recursive); return op; }
java
public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) { final ModelNode op = createRemoveOperation(address); op.get(RECURSIVE).set(recursive); return op; }
[ "public", "static", "ModelNode", "createRemoveOperation", "(", "final", "ModelNode", "address", ",", "final", "boolean", "recursive", ")", "{", "final", "ModelNode", "op", "=", "createRemoveOperation", "(", "address", ")", ";", "op", ".", "get", "(", "RECURSIVE"...
Creates a remove operation. @param address the address for the operation @param recursive {@code true} if the remove should be recursive, otherwise {@code false} @return the operation
[ "Creates", "a", "remove", "operation", "." ]
train
https://github.com/wildfly/wildfly-maven-plugin/blob/c0e2d7ee28e511092561801959eae253b2b56def/plugin/src/main/java/org/wildfly/plugin/common/ServerOperations.java#L101-L105
belaban/JGroups
src/org/jgroups/protocols/pbcast/Merger.java
Merger.fetchDigestsFromAllMembersInSubPartition
protected Digest fetchDigestsFromAllMembersInSubPartition(final View view, MergeId merge_id) { final List<Address> current_mbrs=view.getMembers(); // Optimization: if we're the only member, we don't need to multicast the get-digest message if(current_mbrs == null || current_mbrs.size() == 1 && current_mbrs.get(0).equals(gms.local_addr)) return new MutableDigest(view.getMembersRaw()) .set((Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.local_addr))); Message get_digest_req=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL) .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.GET_DIGEST_REQ).mergeId(merge_id)); long max_wait_time=gms.merge_timeout / 2; // gms.merge_timeout is guaranteed to be > 0, verified in init() digest_collector.reset(current_mbrs); gms.getDownProtocol().down(get_digest_req); // add my own digest first - the get_digest_req needs to be sent first *before* getting our own digest, so // we have that message in our digest ! Digest digest=(Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.local_addr)); digest_collector.add(gms.local_addr, digest); digest_collector.waitForAllResponses(max_wait_time); if(log.isTraceEnabled()) { if(digest_collector.hasAllResponses()) log.trace("%s: fetched all digests for %s", gms.local_addr, current_mbrs); else log.trace("%s: fetched incomplete digests (after timeout of %d) ms for %s", gms.local_addr, max_wait_time, current_mbrs); } List<Address> valid_rsps=new ArrayList<>(current_mbrs); valid_rsps.removeAll(digest_collector.getMissing()); Address[] tmp=new Address[valid_rsps.size()]; valid_rsps.toArray(tmp); MutableDigest retval=new MutableDigest(tmp); Map<Address,Digest> responses=new HashMap<>(digest_collector.getResults()); responses.values().forEach(retval::set); return retval; }
java
protected Digest fetchDigestsFromAllMembersInSubPartition(final View view, MergeId merge_id) { final List<Address> current_mbrs=view.getMembers(); // Optimization: if we're the only member, we don't need to multicast the get-digest message if(current_mbrs == null || current_mbrs.size() == 1 && current_mbrs.get(0).equals(gms.local_addr)) return new MutableDigest(view.getMembersRaw()) .set((Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.local_addr))); Message get_digest_req=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL) .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.GET_DIGEST_REQ).mergeId(merge_id)); long max_wait_time=gms.merge_timeout / 2; // gms.merge_timeout is guaranteed to be > 0, verified in init() digest_collector.reset(current_mbrs); gms.getDownProtocol().down(get_digest_req); // add my own digest first - the get_digest_req needs to be sent first *before* getting our own digest, so // we have that message in our digest ! Digest digest=(Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.local_addr)); digest_collector.add(gms.local_addr, digest); digest_collector.waitForAllResponses(max_wait_time); if(log.isTraceEnabled()) { if(digest_collector.hasAllResponses()) log.trace("%s: fetched all digests for %s", gms.local_addr, current_mbrs); else log.trace("%s: fetched incomplete digests (after timeout of %d) ms for %s", gms.local_addr, max_wait_time, current_mbrs); } List<Address> valid_rsps=new ArrayList<>(current_mbrs); valid_rsps.removeAll(digest_collector.getMissing()); Address[] tmp=new Address[valid_rsps.size()]; valid_rsps.toArray(tmp); MutableDigest retval=new MutableDigest(tmp); Map<Address,Digest> responses=new HashMap<>(digest_collector.getResults()); responses.values().forEach(retval::set); return retval; }
[ "protected", "Digest", "fetchDigestsFromAllMembersInSubPartition", "(", "final", "View", "view", ",", "MergeId", "merge_id", ")", "{", "final", "List", "<", "Address", ">", "current_mbrs", "=", "view", ".", "getMembers", "(", ")", ";", "// Optimization: if we're the...
Multicasts a GET_DIGEST_REQ to all members of this sub partition and waits for all responses (GET_DIGEST_RSP) or N ms.
[ "Multicasts", "a", "GET_DIGEST_REQ", "to", "all", "members", "of", "this", "sub", "partition", "and", "waits", "for", "all", "responses", "(", "GET_DIGEST_RSP", ")", "or", "N", "ms", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/pbcast/Merger.java#L372-L410
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/CmsEditorBase.java
CmsEditorBase.loadContentDefinition
public void loadContentDefinition(final String entityId, final Command callback) { AsyncCallback<CmsContentDefinition> asyncCallback = new AsyncCallback<CmsContentDefinition>() { public void onFailure(Throwable caught) { onRpcError(caught); } public void onSuccess(CmsContentDefinition result) { registerContentDefinition(result); callback.execute(); } }; getService().loadContentDefinition(entityId, asyncCallback); }
java
public void loadContentDefinition(final String entityId, final Command callback) { AsyncCallback<CmsContentDefinition> asyncCallback = new AsyncCallback<CmsContentDefinition>() { public void onFailure(Throwable caught) { onRpcError(caught); } public void onSuccess(CmsContentDefinition result) { registerContentDefinition(result); callback.execute(); } }; getService().loadContentDefinition(entityId, asyncCallback); }
[ "public", "void", "loadContentDefinition", "(", "final", "String", "entityId", ",", "final", "Command", "callback", ")", "{", "AsyncCallback", "<", "CmsContentDefinition", ">", "asyncCallback", "=", "new", "AsyncCallback", "<", "CmsContentDefinition", ">", "(", ")",...
Loads the content definition for the given entity and executes the callback on success.<p> @param entityId the entity id @param callback the callback
[ "Loads", "the", "content", "definition", "for", "the", "given", "entity", "and", "executes", "the", "callback", "on", "success", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsEditorBase.java#L336-L352
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Streams.java
Streams.composedClose
static Runnable composedClose(BaseStream<?, ?> a, BaseStream<?, ?> b) { return new Runnable() { @Override public void run() { try { a.close(); } catch (Throwable e1) { try { b.close(); } catch (Throwable e2) { try { e1.addSuppressed(e2); } catch (Throwable ignore) {} } throw e1; } b.close(); } }; }
java
static Runnable composedClose(BaseStream<?, ?> a, BaseStream<?, ?> b) { return new Runnable() { @Override public void run() { try { a.close(); } catch (Throwable e1) { try { b.close(); } catch (Throwable e2) { try { e1.addSuppressed(e2); } catch (Throwable ignore) {} } throw e1; } b.close(); } }; }
[ "static", "Runnable", "composedClose", "(", "BaseStream", "<", "?", ",", "?", ">", "a", ",", "BaseStream", "<", "?", ",", "?", ">", "b", ")", "{", "return", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", ...
Given two streams, return a Runnable that executes both of their {@link BaseStream#close} methods in sequence, even if the first throws an exception, and if both throw exceptions, add any exceptions thrown by the second as suppressed exceptions of the first.
[ "Given", "two", "streams", "return", "a", "Runnable", "that", "executes", "both", "of", "their", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Streams.java#L874-L895
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.addAll
public static <T> boolean addAll(Collection<T> self, Iterable<T> items) { boolean changed = false; for (T next : items) { if (self.add(next)) changed = true; } return changed; }
java
public static <T> boolean addAll(Collection<T> self, Iterable<T> items) { boolean changed = false; for (T next : items) { if (self.add(next)) changed = true; } return changed; }
[ "public", "static", "<", "T", ">", "boolean", "addAll", "(", "Collection", "<", "T", ">", "self", ",", "Iterable", "<", "T", ">", "items", ")", "{", "boolean", "changed", "=", "false", ";", "for", "(", "T", "next", ":", "items", ")", "{", "if", "...
Adds all items from the iterable to the Collection. @param self the collection @param items the items to add @return true if the collection changed
[ "Adds", "all", "items", "from", "the", "iterable", "to", "the", "Collection", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L9387-L9393
Azure/azure-sdk-for-java
policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java
PolicyEventsInner.listQueryResultsForResource
public PolicyEventsQueryResultsInner listQueryResultsForResource(String resourceId, QueryOptions queryOptions) { return listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions).toBlocking().single().body(); }
java
public PolicyEventsQueryResultsInner listQueryResultsForResource(String resourceId, QueryOptions queryOptions) { return listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions).toBlocking().single().body(); }
[ "public", "PolicyEventsQueryResultsInner", "listQueryResultsForResource", "(", "String", "resourceId", ",", "QueryOptions", "queryOptions", ")", "{", "return", "listQueryResultsForResourceWithServiceResponseAsync", "(", "resourceId", ",", "queryOptions", ")", ".", "toBlocking",...
Queries policy events for the resource. @param resourceId Resource ID. @param queryOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws QueryFailureException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PolicyEventsQueryResultsInner object if successful.
[ "Queries", "policy", "events", "for", "the", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java#L764-L766
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearchManager.java
UserSearchManager.getSearchResults
public ReportedData getSearchResults(Form searchForm, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return userSearch.sendSearchForm(con, searchForm, searchService); }
java
public ReportedData getSearchResults(Form searchForm, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return userSearch.sendSearchForm(con, searchForm, searchService); }
[ "public", "ReportedData", "getSearchResults", "(", "Form", "searchForm", ",", "DomainBareJid", "searchService", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "userSearch", ".", "s...
Submits a search form to the server and returns the resulting information in the form of <code>ReportedData</code>. @param searchForm the <code>Form</code> to submit for searching. @param searchService the name of the search service to use. @return the ReportedData returned by the server. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Submits", "a", "search", "form", "to", "the", "server", "and", "returns", "the", "resulting", "information", "in", "the", "form", "of", "<code", ">", "ReportedData<", "/", "code", ">", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearchManager.java#L90-L92
rundeck/rundeck
core/src/main/java/com/dtolabs/shared/resources/ResourceXMLGenerator.java
ResourceXMLGenerator.serializeDocToStream
private static void serializeDocToStream(final OutputStream output, final Document doc) throws IOException { final OutputFormat format = OutputFormat.createPrettyPrint(); final XMLWriter writer = new XMLWriter(output, format); writer.write(doc); writer.flush(); }
java
private static void serializeDocToStream(final OutputStream output, final Document doc) throws IOException { final OutputFormat format = OutputFormat.createPrettyPrint(); final XMLWriter writer = new XMLWriter(output, format); writer.write(doc); writer.flush(); }
[ "private", "static", "void", "serializeDocToStream", "(", "final", "OutputStream", "output", ",", "final", "Document", "doc", ")", "throws", "IOException", "{", "final", "OutputFormat", "format", "=", "OutputFormat", ".", "createPrettyPrint", "(", ")", ";", "final...
Write Document to a file @param output stream @param doc document @throws IOException on error
[ "Write", "Document", "to", "a", "file" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/shared/resources/ResourceXMLGenerator.java#L300-L305
alkacon/opencms-core
src/org/opencms/db/CmsLoginManager.java
CmsLoginManager.removeInvalidLogins
protected void removeInvalidLogins(String userName, String remoteAddress) { if (m_maxBadAttempts < 0) { // invalid login storage is disabled return; } String key = createStorageKey(userName, remoteAddress); // just remove the user from the storage m_storage.remove(key); }
java
protected void removeInvalidLogins(String userName, String remoteAddress) { if (m_maxBadAttempts < 0) { // invalid login storage is disabled return; } String key = createStorageKey(userName, remoteAddress); // just remove the user from the storage m_storage.remove(key); }
[ "protected", "void", "removeInvalidLogins", "(", "String", "userName", ",", "String", "remoteAddress", ")", "{", "if", "(", "m_maxBadAttempts", "<", "0", ")", "{", "// invalid login storage is disabled", "return", ";", "}", "String", "key", "=", "createStorageKey", ...
Removes all invalid attempts to login for the given user / IP.<p> @param userName the name of the user @param remoteAddress the remore address (IP) from which the login attempt was made
[ "Removes", "all", "invalid", "attempts", "to", "login", "for", "the", "given", "user", "/", "IP", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsLoginManager.java#L743-L753
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputStream.java
DerInputStream.getPositiveBigInteger
public BigInteger getPositiveBigInteger() throws IOException { if (buffer.read() != DerValue.tag_Integer) { throw new IOException("DER input, Integer tag error"); } return buffer.getBigInteger(getLength(buffer), true); }
java
public BigInteger getPositiveBigInteger() throws IOException { if (buffer.read() != DerValue.tag_Integer) { throw new IOException("DER input, Integer tag error"); } return buffer.getBigInteger(getLength(buffer), true); }
[ "public", "BigInteger", "getPositiveBigInteger", "(", ")", "throws", "IOException", "{", "if", "(", "buffer", ".", "read", "(", ")", "!=", "DerValue", ".", "tag_Integer", ")", "{", "throw", "new", "IOException", "(", "\"DER input, Integer tag error\"", ")", ";",...
Returns an ASN.1 INTEGER value as a positive BigInteger. This is just to deal with implementations that incorrectly encode some values as negative. @return the integer held in this DER value as a BigInteger.
[ "Returns", "an", "ASN", ".", "1", "INTEGER", "value", "as", "a", "positive", "BigInteger", ".", "This", "is", "just", "to", "deal", "with", "implementations", "that", "incorrectly", "encode", "some", "values", "as", "negative", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputStream.java#L192-L197
ACRA/acra
acra-core/src/main/java/org/acra/collector/LogCatCollector.java
LogCatCollector.collectLogCat
private String collectLogCat(@NonNull CoreConfiguration config, @Nullable String bufferName) throws IOException { final int myPid = android.os.Process.myPid(); // no need to filter on jellybean onwards, android does that anyway final String myPidStr = Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN && config.logcatFilterByPid() && myPid > 0 ? Integer.toString(myPid) + "):" : null; final List<String> commandLine = new ArrayList<>(); commandLine.add("logcat"); if (bufferName != null) { commandLine.add("-b"); commandLine.add(bufferName); } final int tailCount; final List<String> logcatArgumentsList = config.logcatArguments(); final int tailIndex = logcatArgumentsList.indexOf("-t"); if (tailIndex > -1 && tailIndex < logcatArgumentsList.size()) { tailCount = Integer.parseInt(logcatArgumentsList.get(tailIndex + 1)); } else { tailCount = -1; } commandLine.addAll(logcatArgumentsList); final Process process = new ProcessBuilder().command(commandLine).redirectErrorStream(true).start(); if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Retrieving logcat output (buffer:" + (bufferName == null ? "default" : bufferName) + ")..."); try { return streamToString(config, process.getInputStream(), myPidStr == null ? null : s -> s.contains(myPidStr), tailCount); } finally { process.destroy(); } }
java
private String collectLogCat(@NonNull CoreConfiguration config, @Nullable String bufferName) throws IOException { final int myPid = android.os.Process.myPid(); // no need to filter on jellybean onwards, android does that anyway final String myPidStr = Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN && config.logcatFilterByPid() && myPid > 0 ? Integer.toString(myPid) + "):" : null; final List<String> commandLine = new ArrayList<>(); commandLine.add("logcat"); if (bufferName != null) { commandLine.add("-b"); commandLine.add(bufferName); } final int tailCount; final List<String> logcatArgumentsList = config.logcatArguments(); final int tailIndex = logcatArgumentsList.indexOf("-t"); if (tailIndex > -1 && tailIndex < logcatArgumentsList.size()) { tailCount = Integer.parseInt(logcatArgumentsList.get(tailIndex + 1)); } else { tailCount = -1; } commandLine.addAll(logcatArgumentsList); final Process process = new ProcessBuilder().command(commandLine).redirectErrorStream(true).start(); if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Retrieving logcat output (buffer:" + (bufferName == null ? "default" : bufferName) + ")..."); try { return streamToString(config, process.getInputStream(), myPidStr == null ? null : s -> s.contains(myPidStr), tailCount); } finally { process.destroy(); } }
[ "private", "String", "collectLogCat", "(", "@", "NonNull", "CoreConfiguration", "config", ",", "@", "Nullable", "String", "bufferName", ")", "throws", "IOException", "{", "final", "int", "myPid", "=", "android", ".", "os", ".", "Process", ".", "myPid", "(", ...
Executes the logcat command with arguments taken from {@link org.acra.annotation.AcraCore#logcatArguments()} @param bufferName The name of the buffer to be read: "main" (default), "radio" or "events". @return A string containing the latest lines of the output. Default is 100 lines, use "-t", "300" in {@link org.acra.annotation.AcraCore#logcatArguments()} if you want 300 lines. You should be aware that increasing this value causes a longer report generation time and a bigger footprint on the device data plan consumption.
[ "Executes", "the", "logcat", "command", "with", "arguments", "taken", "from", "{", "@link", "org", ".", "acra", ".", "annotation", ".", "AcraCore#logcatArguments", "()", "}" ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/LogCatCollector.java#L69-L100