repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Red5/red5-io | src/main/java/org/red5/io/utils/IOUtils.java | IOUtils.writeExtendedMediumInt | public final static void writeExtendedMediumInt(ByteBuffer out, int value) {
"""
Writes extended medium integer (equivalent to a regular integer whose most significant byte has been moved to its end, past its least significant byte)
@param out
Output buffer
@param value
Integer to write
"""
value = ((value & 0xff000000) >> 24) | (value << 8);
out.putInt(value);
} | java | public final static void writeExtendedMediumInt(ByteBuffer out, int value) {
value = ((value & 0xff000000) >> 24) | (value << 8);
out.putInt(value);
} | [
"public",
"final",
"static",
"void",
"writeExtendedMediumInt",
"(",
"ByteBuffer",
"out",
",",
"int",
"value",
")",
"{",
"value",
"=",
"(",
"(",
"value",
"&",
"0xff000000",
")",
">>",
"24",
")",
"|",
"(",
"value",
"<<",
"8",
")",
";",
"out",
".",
"putInt",
"(",
"value",
")",
";",
"}"
] | Writes extended medium integer (equivalent to a regular integer whose most significant byte has been moved to its end, past its least significant byte)
@param out
Output buffer
@param value
Integer to write | [
"Writes",
"extended",
"medium",
"integer",
"(",
"equivalent",
"to",
"a",
"regular",
"integer",
"whose",
"most",
"significant",
"byte",
"has",
"been",
"moved",
"to",
"its",
"end",
"past",
"its",
"least",
"significant",
"byte",
")"
] | train | https://github.com/Red5/red5-io/blob/9bbbc506423c5a8f18169d46d400df56c0072a33/src/main/java/org/red5/io/utils/IOUtils.java#L102-L105 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/data/clock/Day.java | Day.getLastOfMonth | public static Day getLastOfMonth(int dayOfWeek, int month, int year) {
"""
Find the last of a specific day in a given month. For instance
last Tuesday of May:
getLastOfMonth (Calendar.TUESDAY, Calendar.MAY, 2005);
@param dayOfWeek Weekday to get.
@param month Month of day to get.
@param year Year of day to get.
@return The requested day.
"""
Day day = Day.getNthOfMonth(5, dayOfWeek, month, year);
return day != null ? day : Day.getNthOfMonth(4, dayOfWeek, month, year);
} | java | public static Day getLastOfMonth(int dayOfWeek, int month, int year)
{
Day day = Day.getNthOfMonth(5, dayOfWeek, month, year);
return day != null ? day : Day.getNthOfMonth(4, dayOfWeek, month, year);
} | [
"public",
"static",
"Day",
"getLastOfMonth",
"(",
"int",
"dayOfWeek",
",",
"int",
"month",
",",
"int",
"year",
")",
"{",
"Day",
"day",
"=",
"Day",
".",
"getNthOfMonth",
"(",
"5",
",",
"dayOfWeek",
",",
"month",
",",
"year",
")",
";",
"return",
"day",
"!=",
"null",
"?",
"day",
":",
"Day",
".",
"getNthOfMonth",
"(",
"4",
",",
"dayOfWeek",
",",
"month",
",",
"year",
")",
";",
"}"
] | Find the last of a specific day in a given month. For instance
last Tuesday of May:
getLastOfMonth (Calendar.TUESDAY, Calendar.MAY, 2005);
@param dayOfWeek Weekday to get.
@param month Month of day to get.
@param year Year of day to get.
@return The requested day. | [
"Find",
"the",
"last",
"of",
"a",
"specific",
"day",
"in",
"a",
"given",
"month",
".",
"For",
"instance",
"last",
"Tuesday",
"of",
"May",
":",
"getLastOfMonth",
"(",
"Calendar",
".",
"TUESDAY",
"Calendar",
".",
"MAY",
"2005",
")",
";"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/data/clock/Day.java#L605-L609 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/orders/OrderItemUrl.java | OrderItemUrl.updateItemProductPriceUrl | public static MozuUrl updateItemProductPriceUrl(String orderId, String orderItemId, Double price, String responseFields, String updateMode, String version) {
"""
Get Resource Url for UpdateItemProductPrice
@param orderId Unique identifier of the order.
@param orderItemId Unique identifier of the item to remove from the order.
@param price The override price to specify for this item in the specified order.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/items/{orderItemId}/price/{price}?updatemode={updateMode}&version={version}&responseFields={responseFields}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("orderItemId", orderItemId);
formatter.formatUrl("price", price);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl updateItemProductPriceUrl(String orderId, String orderItemId, Double price, String responseFields, String updateMode, String version)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/items/{orderItemId}/price/{price}?updatemode={updateMode}&version={version}&responseFields={responseFields}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("orderItemId", orderItemId);
formatter.formatUrl("price", price);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"updateItemProductPriceUrl",
"(",
"String",
"orderId",
",",
"String",
"orderItemId",
",",
"Double",
"price",
",",
"String",
"responseFields",
",",
"String",
"updateMode",
",",
"String",
"version",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/orders/{orderId}/items/{orderItemId}/price/{price}?updatemode={updateMode}&version={version}&responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"orderId\"",
",",
"orderId",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"orderItemId\"",
",",
"orderItemId",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"price\"",
",",
"price",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"updateMode\"",
",",
"updateMode",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"version\"",
",",
"version",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
] | Get Resource Url for UpdateItemProductPrice
@param orderId Unique identifier of the order.
@param orderItemId Unique identifier of the item to remove from the order.
@param price The override price to specify for this item in the specified order.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"UpdateItemProductPrice"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/orders/OrderItemUrl.java#L163-L173 |
alkacon/opencms-core | src/org/opencms/importexport/A_CmsImport.java | A_CmsImport.getChildElementTextValue | public String getChildElementTextValue(Element parentElement, String elementName) {
"""
Returns the value of a child element with a specified name for a given parent element.<p>
@param parentElement the parent element
@param elementName the child element name
@return the value of the child node, or null if something went wrong
"""
try {
// get the first child element matching the specified name
Element childElement = (Element)parentElement.selectNodes("./" + elementName).get(0);
// return the value of the child element
return childElement.getTextTrim();
} catch (Exception e) {
return null;
}
} | java | public String getChildElementTextValue(Element parentElement, String elementName) {
try {
// get the first child element matching the specified name
Element childElement = (Element)parentElement.selectNodes("./" + elementName).get(0);
// return the value of the child element
return childElement.getTextTrim();
} catch (Exception e) {
return null;
}
} | [
"public",
"String",
"getChildElementTextValue",
"(",
"Element",
"parentElement",
",",
"String",
"elementName",
")",
"{",
"try",
"{",
"// get the first child element matching the specified name",
"Element",
"childElement",
"=",
"(",
"Element",
")",
"parentElement",
".",
"selectNodes",
"(",
"\"./\"",
"+",
"elementName",
")",
".",
"get",
"(",
"0",
")",
";",
"// return the value of the child element",
"return",
"childElement",
".",
"getTextTrim",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Returns the value of a child element with a specified name for a given parent element.<p>
@param parentElement the parent element
@param elementName the child element name
@return the value of the child node, or null if something went wrong | [
"Returns",
"the",
"value",
"of",
"a",
"child",
"element",
"with",
"a",
"specified",
"name",
"for",
"a",
"given",
"parent",
"element",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/A_CmsImport.java#L323-L333 |
xiancloud/xian | xian-dao/xian-mongodbdao/xian-mongodbdao-sync/src/main/java/info/xiancloud/plugin/dao/mongodb/Mongo.java | Mongo.getOrInitDefaultDatabase | public static MongoDatabase getOrInitDefaultDatabase(String connectionString, String database) {
"""
Get default mongodb database reference or initiate it if not initialized.
@param connectionString MongoDB standard connection string
@param database mongodb database name
@return MongoDB mongodb client database reference.
"""
if (DEFAULT_DATABASE == null) {
synchronized (LOCK) {
if (DEFAULT_DATABASE == null) {
if (!StringUtil.isEmpty(connectionString)) {
DEFAULT_CLIENT = MongoClients.create(connectionString);
CodecRegistry pojoCodecRegistry = fromRegistries(
/*fromCodecs(new StringCodecExt()),*/
MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
DEFAULT_DATABASE = DEFAULT_CLIENT.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
} else {
throw new RuntimeException("No datasource configuration found for mongodb.");
}
}
}
}
return DEFAULT_DATABASE;
} | java | public static MongoDatabase getOrInitDefaultDatabase(String connectionString, String database) {
if (DEFAULT_DATABASE == null) {
synchronized (LOCK) {
if (DEFAULT_DATABASE == null) {
if (!StringUtil.isEmpty(connectionString)) {
DEFAULT_CLIENT = MongoClients.create(connectionString);
CodecRegistry pojoCodecRegistry = fromRegistries(
/*fromCodecs(new StringCodecExt()),*/
MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
DEFAULT_DATABASE = DEFAULT_CLIENT.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
} else {
throw new RuntimeException("No datasource configuration found for mongodb.");
}
}
}
}
return DEFAULT_DATABASE;
} | [
"public",
"static",
"MongoDatabase",
"getOrInitDefaultDatabase",
"(",
"String",
"connectionString",
",",
"String",
"database",
")",
"{",
"if",
"(",
"DEFAULT_DATABASE",
"==",
"null",
")",
"{",
"synchronized",
"(",
"LOCK",
")",
"{",
"if",
"(",
"DEFAULT_DATABASE",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"StringUtil",
".",
"isEmpty",
"(",
"connectionString",
")",
")",
"{",
"DEFAULT_CLIENT",
"=",
"MongoClients",
".",
"create",
"(",
"connectionString",
")",
";",
"CodecRegistry",
"pojoCodecRegistry",
"=",
"fromRegistries",
"(",
"/*fromCodecs(new StringCodecExt()),*/",
"MongoClientSettings",
".",
"getDefaultCodecRegistry",
"(",
")",
",",
"fromProviders",
"(",
"PojoCodecProvider",
".",
"builder",
"(",
")",
".",
"automatic",
"(",
"true",
")",
".",
"build",
"(",
")",
")",
")",
";",
"DEFAULT_DATABASE",
"=",
"DEFAULT_CLIENT",
".",
"getDatabase",
"(",
"database",
")",
".",
"withCodecRegistry",
"(",
"pojoCodecRegistry",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"No datasource configuration found for mongodb.\"",
")",
";",
"}",
"}",
"}",
"}",
"return",
"DEFAULT_DATABASE",
";",
"}"
] | Get default mongodb database reference or initiate it if not initialized.
@param connectionString MongoDB standard connection string
@param database mongodb database name
@return MongoDB mongodb client database reference. | [
"Get",
"default",
"mongodb",
"database",
"reference",
"or",
"initiate",
"it",
"if",
"not",
"initialized",
"."
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-dao/xian-mongodbdao/xian-mongodbdao-sync/src/main/java/info/xiancloud/plugin/dao/mongodb/Mongo.java#L56-L74 |
revelytix/spark | spark-http-client/src/main/java/spark/protocol/parser/ResultFactory.java | ResultFactory.findParser | private static final ResultParser findParser(String mediaType, ResultType expectedType) {
"""
Find a parser to handle the protocol response body based on the content type found in the response
and the expected result type specified by the user; if one or both fields is missing then
attempts to choose a sensible default.
@param mediaType The content type in the response, or null if none was given.
@param expectedType The expected response type indicated by the user, or
@return
"""
ResponseFormat format = null;
// Prefer MIME type when choosing result format.
if (mediaType != null) {
mediaType = stripParams(mediaType);
format = mimeFormats.get(mediaType);
if (format == null) {
logger.warn("Unrecognized media type ({}) in SPARQL server response", mediaType);
} else {
logger.debug("Using result format {} for media type {}", format, mediaType);
}
}
// If MIME type was absent or unrecognized, choose default based on expected result type.
if (format == null) {
logger.debug("Unable to determine result format from media type");
if (expectedType != null) {
format = defaultTypeFormats.get(expectedType);
logger.debug("Using default format {} for expected result type {}", format, expectedType);
} else {
format = DEFAULT_FORMAT;
logger.debug("No expected type provided; using default format {}", format);
}
}
assert format != null:"Could not determine result format";
// Validate that the chosen format can produce the expected result type.
if (expectedType != null && !format.resultTypes.contains(expectedType)) {
throw new SparqlException("Result format " + format + " does not support expected result type " + expectedType);
}
return format.parser;
} | java | private static final ResultParser findParser(String mediaType, ResultType expectedType) {
ResponseFormat format = null;
// Prefer MIME type when choosing result format.
if (mediaType != null) {
mediaType = stripParams(mediaType);
format = mimeFormats.get(mediaType);
if (format == null) {
logger.warn("Unrecognized media type ({}) in SPARQL server response", mediaType);
} else {
logger.debug("Using result format {} for media type {}", format, mediaType);
}
}
// If MIME type was absent or unrecognized, choose default based on expected result type.
if (format == null) {
logger.debug("Unable to determine result format from media type");
if (expectedType != null) {
format = defaultTypeFormats.get(expectedType);
logger.debug("Using default format {} for expected result type {}", format, expectedType);
} else {
format = DEFAULT_FORMAT;
logger.debug("No expected type provided; using default format {}", format);
}
}
assert format != null:"Could not determine result format";
// Validate that the chosen format can produce the expected result type.
if (expectedType != null && !format.resultTypes.contains(expectedType)) {
throw new SparqlException("Result format " + format + " does not support expected result type " + expectedType);
}
return format.parser;
} | [
"private",
"static",
"final",
"ResultParser",
"findParser",
"(",
"String",
"mediaType",
",",
"ResultType",
"expectedType",
")",
"{",
"ResponseFormat",
"format",
"=",
"null",
";",
"// Prefer MIME type when choosing result format.",
"if",
"(",
"mediaType",
"!=",
"null",
")",
"{",
"mediaType",
"=",
"stripParams",
"(",
"mediaType",
")",
";",
"format",
"=",
"mimeFormats",
".",
"get",
"(",
"mediaType",
")",
";",
"if",
"(",
"format",
"==",
"null",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Unrecognized media type ({}) in SPARQL server response\"",
",",
"mediaType",
")",
";",
"}",
"else",
"{",
"logger",
".",
"debug",
"(",
"\"Using result format {} for media type {}\"",
",",
"format",
",",
"mediaType",
")",
";",
"}",
"}",
"// If MIME type was absent or unrecognized, choose default based on expected result type.",
"if",
"(",
"format",
"==",
"null",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Unable to determine result format from media type\"",
")",
";",
"if",
"(",
"expectedType",
"!=",
"null",
")",
"{",
"format",
"=",
"defaultTypeFormats",
".",
"get",
"(",
"expectedType",
")",
";",
"logger",
".",
"debug",
"(",
"\"Using default format {} for expected result type {}\"",
",",
"format",
",",
"expectedType",
")",
";",
"}",
"else",
"{",
"format",
"=",
"DEFAULT_FORMAT",
";",
"logger",
".",
"debug",
"(",
"\"No expected type provided; using default format {}\"",
",",
"format",
")",
";",
"}",
"}",
"assert",
"format",
"!=",
"null",
":",
"\"Could not determine result format\"",
";",
"// Validate that the chosen format can produce the expected result type.",
"if",
"(",
"expectedType",
"!=",
"null",
"&&",
"!",
"format",
".",
"resultTypes",
".",
"contains",
"(",
"expectedType",
")",
")",
"{",
"throw",
"new",
"SparqlException",
"(",
"\"Result format \"",
"+",
"format",
"+",
"\" does not support expected result type \"",
"+",
"expectedType",
")",
";",
"}",
"return",
"format",
".",
"parser",
";",
"}"
] | Find a parser to handle the protocol response body based on the content type found in the response
and the expected result type specified by the user; if one or both fields is missing then
attempts to choose a sensible default.
@param mediaType The content type in the response, or null if none was given.
@param expectedType The expected response type indicated by the user, or
@return | [
"Find",
"a",
"parser",
"to",
"handle",
"the",
"protocol",
"response",
"body",
"based",
"on",
"the",
"content",
"type",
"found",
"in",
"the",
"response",
"and",
"the",
"expected",
"result",
"type",
"specified",
"by",
"the",
"user",
";",
"if",
"one",
"or",
"both",
"fields",
"is",
"missing",
"then",
"attempts",
"to",
"choose",
"a",
"sensible",
"default",
"."
] | train | https://github.com/revelytix/spark/blob/d777d40c962bc66fdc04b7c3a66d20b777ff6fb4/spark-http-client/src/main/java/spark/protocol/parser/ResultFactory.java#L153-L187 |
alkacon/opencms-core | src-gwt/org/opencms/ade/contenteditor/client/CmsEntityObserver.java | CmsEntityObserver.addEntityChangeListener | public void addEntityChangeListener(I_CmsEntityChangeListener changeListener, String changeScope) {
"""
Adds an entity change listener for the given scope.<p>
@param changeListener the change listener
@param changeScope the change scope
"""
if (m_observerdEntity == null) {
throw new RuntimeException("The Observer has been cleared, no listener registration possible.");
}
if (!m_changeListeners.containsKey(changeScope)) {
m_changeListeners.put(changeScope, new ArrayList<I_CmsEntityChangeListener>());
// if changeScope==null, it is a global change listener, and we don't need a scope value
if (changeScope != null) {
// save the current change scope value
m_scopeValues.put(changeScope, CmsContentDefinition.getValueForPath(m_observerdEntity, changeScope));
}
}
m_changeListeners.get(changeScope).add(changeListener);
} | java | public void addEntityChangeListener(I_CmsEntityChangeListener changeListener, String changeScope) {
if (m_observerdEntity == null) {
throw new RuntimeException("The Observer has been cleared, no listener registration possible.");
}
if (!m_changeListeners.containsKey(changeScope)) {
m_changeListeners.put(changeScope, new ArrayList<I_CmsEntityChangeListener>());
// if changeScope==null, it is a global change listener, and we don't need a scope value
if (changeScope != null) {
// save the current change scope value
m_scopeValues.put(changeScope, CmsContentDefinition.getValueForPath(m_observerdEntity, changeScope));
}
}
m_changeListeners.get(changeScope).add(changeListener);
} | [
"public",
"void",
"addEntityChangeListener",
"(",
"I_CmsEntityChangeListener",
"changeListener",
",",
"String",
"changeScope",
")",
"{",
"if",
"(",
"m_observerdEntity",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The Observer has been cleared, no listener registration possible.\"",
")",
";",
"}",
"if",
"(",
"!",
"m_changeListeners",
".",
"containsKey",
"(",
"changeScope",
")",
")",
"{",
"m_changeListeners",
".",
"put",
"(",
"changeScope",
",",
"new",
"ArrayList",
"<",
"I_CmsEntityChangeListener",
">",
"(",
")",
")",
";",
"// if changeScope==null, it is a global change listener, and we don't need a scope value\r",
"if",
"(",
"changeScope",
"!=",
"null",
")",
"{",
"// save the current change scope value\r",
"m_scopeValues",
".",
"put",
"(",
"changeScope",
",",
"CmsContentDefinition",
".",
"getValueForPath",
"(",
"m_observerdEntity",
",",
"changeScope",
")",
")",
";",
"}",
"}",
"m_changeListeners",
".",
"get",
"(",
"changeScope",
")",
".",
"add",
"(",
"changeListener",
")",
";",
"}"
] | Adds an entity change listener for the given scope.<p>
@param changeListener the change listener
@param changeScope the change scope | [
"Adds",
"an",
"entity",
"change",
"listener",
"for",
"the",
"given",
"scope",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/contenteditor/client/CmsEntityObserver.java#L80-L94 |
keenon/loglinear | src/main/java/com/github/keenon/loglinear/inference/TableFactor.java | TableFactor.maxOut | public TableFactor maxOut(int variable) {
"""
Marginalize out a variable by taking the max value.
@param variable the variable to be maxed out.
@return a table factor that will contain the largest value of the variable being marginalized out.
"""
return marginalize(variable, Double.NEGATIVE_INFINITY, (marginalizedVariableValue, assignment) -> Math::max);
} | java | public TableFactor maxOut(int variable) {
return marginalize(variable, Double.NEGATIVE_INFINITY, (marginalizedVariableValue, assignment) -> Math::max);
} | [
"public",
"TableFactor",
"maxOut",
"(",
"int",
"variable",
")",
"{",
"return",
"marginalize",
"(",
"variable",
",",
"Double",
".",
"NEGATIVE_INFINITY",
",",
"(",
"marginalizedVariableValue",
",",
"assignment",
")",
"->",
"Math",
"::",
"max",
")",
";",
"}"
] | Marginalize out a variable by taking the max value.
@param variable the variable to be maxed out.
@return a table factor that will contain the largest value of the variable being marginalized out. | [
"Marginalize",
"out",
"a",
"variable",
"by",
"taking",
"the",
"max",
"value",
"."
] | train | https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L268-L270 |
bluelinelabs/Conductor | conductor/src/main/java/com/bluelinelabs/conductor/Controller.java | Controller.startActivityForResult | public final void startActivityForResult(@NonNull final Intent intent, final int requestCode) {
"""
Calls startActivityForResult(Intent, int) from this Controller's host Activity.
"""
executeWithRouter(new RouterRequiringFunc() {
@Override public void execute() { router.startActivityForResult(instanceId, intent, requestCode); }
});
} | java | public final void startActivityForResult(@NonNull final Intent intent, final int requestCode) {
executeWithRouter(new RouterRequiringFunc() {
@Override public void execute() { router.startActivityForResult(instanceId, intent, requestCode); }
});
} | [
"public",
"final",
"void",
"startActivityForResult",
"(",
"@",
"NonNull",
"final",
"Intent",
"intent",
",",
"final",
"int",
"requestCode",
")",
"{",
"executeWithRouter",
"(",
"new",
"RouterRequiringFunc",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"router",
".",
"startActivityForResult",
"(",
"instanceId",
",",
"intent",
",",
"requestCode",
")",
";",
"}",
"}",
")",
";",
"}"
] | Calls startActivityForResult(Intent, int) from this Controller's host Activity. | [
"Calls",
"startActivityForResult",
"(",
"Intent",
"int",
")",
"from",
"this",
"Controller",
"s",
"host",
"Activity",
"."
] | train | https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/Controller.java#L513-L517 |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java | StringUtil.replaceFirst | public String replaceFirst(String pString, String pRegex, String pReplacement) {
"""
Replaces the first substring of the given string that matches the given
regular expression with the given pReplacement.
<p/>
An invocation of this method of the form
<tt>replaceFirst(<i>str</i>, </tt><i>regex</i>, <i>repl</i>)</tt>
yields exactly the same result as the expression
<p/>
<blockquote><tt>
{@link Pattern}.{@link Pattern#compile compile}(<i>regex</i>).
{@link Pattern#matcher matcher}(<i>str</i>).
{@link java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)</tt></blockquote>
@param pString the string
@param pRegex the regular expression to which this string is to be matched
@param pReplacement the replacement text
@return The resulting {@code String}
@throws PatternSyntaxException if the regular expression's syntax is invalid
@see Pattern
@see java.util.regex.Matcher#replaceFirst(String)
"""
return Pattern.compile(pRegex).matcher(pString).replaceFirst(pReplacement);
} | java | public String replaceFirst(String pString, String pRegex, String pReplacement) {
return Pattern.compile(pRegex).matcher(pString).replaceFirst(pReplacement);
} | [
"public",
"String",
"replaceFirst",
"(",
"String",
"pString",
",",
"String",
"pRegex",
",",
"String",
"pReplacement",
")",
"{",
"return",
"Pattern",
".",
"compile",
"(",
"pRegex",
")",
".",
"matcher",
"(",
"pString",
")",
".",
"replaceFirst",
"(",
"pReplacement",
")",
";",
"}"
] | Replaces the first substring of the given string that matches the given
regular expression with the given pReplacement.
<p/>
An invocation of this method of the form
<tt>replaceFirst(<i>str</i>, </tt><i>regex</i>, <i>repl</i>)</tt>
yields exactly the same result as the expression
<p/>
<blockquote><tt>
{@link Pattern}.{@link Pattern#compile compile}(<i>regex</i>).
{@link Pattern#matcher matcher}(<i>str</i>).
{@link java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)</tt></blockquote>
@param pString the string
@param pRegex the regular expression to which this string is to be matched
@param pReplacement the replacement text
@return The resulting {@code String}
@throws PatternSyntaxException if the regular expression's syntax is invalid
@see Pattern
@see java.util.regex.Matcher#replaceFirst(String) | [
"Replaces",
"the",
"first",
"substring",
"of",
"the",
"given",
"string",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"with",
"the",
"given",
"pReplacement",
".",
"<p",
"/",
">",
"An",
"invocation",
"of",
"this",
"method",
"of",
"the",
"form",
"<tt",
">",
"replaceFirst",
"(",
"<i",
">",
"str<",
"/",
"i",
">",
"<",
"/",
"tt",
">",
"<i",
">",
"regex<",
"/",
"i",
">",
"<i",
">",
"repl<",
"/",
"i",
">",
")",
"<",
"/",
"tt",
">",
"yields",
"exactly",
"the",
"same",
"result",
"as",
"the",
"expression",
"<p",
"/",
">",
"<blockquote",
">",
"<tt",
">",
"{",
"@link",
"Pattern",
"}",
".",
"{",
"@link",
"Pattern#compile",
"compile",
"}",
"(",
"<i",
">",
"regex<",
"/",
"i",
">",
")",
".",
"{",
"@link",
"Pattern#matcher",
"matcher",
"}",
"(",
"<i",
">",
"str<",
"/",
"i",
">",
")",
".",
"{",
"@link",
"java",
".",
"util",
".",
"regex",
".",
"Matcher#replaceFirst",
"replaceFirst",
"}",
"(",
"<i",
">",
"repl<",
"/",
"i",
">",
")",
"<",
"/",
"tt",
">",
"<",
"/",
"blockquote",
">"
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java#L1806-L1808 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/SEPWorker.java | SEPWorker.maybeStop | private void maybeStop(long stopCheck, long now) {
"""
realtime we have spun too much and deschedule; if we get too far behind realtime, we reset to our initial offset
"""
long delta = now - stopCheck;
if (delta <= 0)
{
// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically
// set it to the past again, we should stop a worker
if (pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
// try and stop ourselves;
// if we've already been assigned work stop another worker
if (!assign(Work.STOP_SIGNALLED, true))
pool.schedule(Work.STOP_SIGNALLED);
}
}
else if (soleSpinnerSpinTime > stopCheckInterval && pool.spinningCount.get() == 1)
{
// permit self-stopping
assign(Work.STOP_SIGNALLED, true);
}
else
{
// if stop check has gotten too far behind present, update it so new spins can affect it
while (delta > stopCheckInterval * 2 && !pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
stopCheck = pool.stopCheck.get();
delta = now - stopCheck;
}
}
} | java | private void maybeStop(long stopCheck, long now)
{
long delta = now - stopCheck;
if (delta <= 0)
{
// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically
// set it to the past again, we should stop a worker
if (pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
// try and stop ourselves;
// if we've already been assigned work stop another worker
if (!assign(Work.STOP_SIGNALLED, true))
pool.schedule(Work.STOP_SIGNALLED);
}
}
else if (soleSpinnerSpinTime > stopCheckInterval && pool.spinningCount.get() == 1)
{
// permit self-stopping
assign(Work.STOP_SIGNALLED, true);
}
else
{
// if stop check has gotten too far behind present, update it so new spins can affect it
while (delta > stopCheckInterval * 2 && !pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
stopCheck = pool.stopCheck.get();
delta = now - stopCheck;
}
}
} | [
"private",
"void",
"maybeStop",
"(",
"long",
"stopCheck",
",",
"long",
"now",
")",
"{",
"long",
"delta",
"=",
"now",
"-",
"stopCheck",
";",
"if",
"(",
"delta",
"<=",
"0",
")",
"{",
"// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically",
"// set it to the past again, we should stop a worker",
"if",
"(",
"pool",
".",
"stopCheck",
".",
"compareAndSet",
"(",
"stopCheck",
",",
"now",
"-",
"stopCheckInterval",
")",
")",
"{",
"// try and stop ourselves;",
"// if we've already been assigned work stop another worker",
"if",
"(",
"!",
"assign",
"(",
"Work",
".",
"STOP_SIGNALLED",
",",
"true",
")",
")",
"pool",
".",
"schedule",
"(",
"Work",
".",
"STOP_SIGNALLED",
")",
";",
"}",
"}",
"else",
"if",
"(",
"soleSpinnerSpinTime",
">",
"stopCheckInterval",
"&&",
"pool",
".",
"spinningCount",
".",
"get",
"(",
")",
"==",
"1",
")",
"{",
"// permit self-stopping",
"assign",
"(",
"Work",
".",
"STOP_SIGNALLED",
",",
"true",
")",
";",
"}",
"else",
"{",
"// if stop check has gotten too far behind present, update it so new spins can affect it",
"while",
"(",
"delta",
">",
"stopCheckInterval",
"*",
"2",
"&&",
"!",
"pool",
".",
"stopCheck",
".",
"compareAndSet",
"(",
"stopCheck",
",",
"now",
"-",
"stopCheckInterval",
")",
")",
"{",
"stopCheck",
"=",
"pool",
".",
"stopCheck",
".",
"get",
"(",
")",
";",
"delta",
"=",
"now",
"-",
"stopCheck",
";",
"}",
"}",
"}"
] | realtime we have spun too much and deschedule; if we get too far behind realtime, we reset to our initial offset | [
"realtime",
"we",
"have",
"spun",
"too",
"much",
"and",
"deschedule",
";",
"if",
"we",
"get",
"too",
"far",
"behind",
"realtime",
"we",
"reset",
"to",
"our",
"initial",
"offset"
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPWorker.java#L261-L290 |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/Database.java | Database.findUnique | public <T> T findUnique(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) {
"""
Finds a unique result from database, converting the database row to given class using default mechanisms.
@throws NonUniqueResultException if there is more then one row
@throws EmptyResultException if there are no rows
"""
return findUnique(cl, SqlQuery.query(sql, args));
} | java | public <T> T findUnique(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) {
return findUnique(cl, SqlQuery.query(sql, args));
} | [
"public",
"<",
"T",
">",
"T",
"findUnique",
"(",
"@",
"NotNull",
"Class",
"<",
"T",
">",
"cl",
",",
"@",
"NotNull",
"@",
"SQL",
"String",
"sql",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"findUnique",
"(",
"cl",
",",
"SqlQuery",
".",
"query",
"(",
"sql",
",",
"args",
")",
")",
";",
"}"
] | Finds a unique result from database, converting the database row to given class using default mechanisms.
@throws NonUniqueResultException if there is more then one row
@throws EmptyResultException if there are no rows | [
"Finds",
"a",
"unique",
"result",
"from",
"database",
"converting",
"the",
"database",
"row",
"to",
"given",
"class",
"using",
"default",
"mechanisms",
"."
] | train | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L362-L364 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/util/LineInput.java | LineInput.readLine | public int readLine(byte[] b,int off,int len)
throws IOException {
"""
Read a line ended by CR, LF or CRLF.
@param b Byte array to place the line into.
@param off Offset into the buffer.
@param len Maximum length of line.
@return The length of the line or -1 for EOF.
@exception IOException
"""
len=fillLine(len);
if (len<0)
return -1;
if (len==0)
return 0;
System.arraycopy(_buf,_mark, b, off, len);
_mark=-1;
return len;
} | java | public int readLine(byte[] b,int off,int len)
throws IOException
{
len=fillLine(len);
if (len<0)
return -1;
if (len==0)
return 0;
System.arraycopy(_buf,_mark, b, off, len);
_mark=-1;
return len;
} | [
"public",
"int",
"readLine",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"len",
"=",
"fillLine",
"(",
"len",
")",
";",
"if",
"(",
"len",
"<",
"0",
")",
"return",
"-",
"1",
";",
"if",
"(",
"len",
"==",
"0",
")",
"return",
"0",
";",
"System",
".",
"arraycopy",
"(",
"_buf",
",",
"_mark",
",",
"b",
",",
"off",
",",
"len",
")",
";",
"_mark",
"=",
"-",
"1",
";",
"return",
"len",
";",
"}"
] | Read a line ended by CR, LF or CRLF.
@param b Byte array to place the line into.
@param off Offset into the buffer.
@param len Maximum length of line.
@return The length of the line or -1 for EOF.
@exception IOException | [
"Read",
"a",
"line",
"ended",
"by",
"CR",
"LF",
"or",
"CRLF",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/LineInput.java#L251-L265 |
apereo/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/profile/DefaultOAuth20UserProfileDataCreator.java | DefaultOAuth20UserProfileDataCreator.finalizeProfileResponse | protected void finalizeProfileResponse(final AccessToken accessTokenTicket, final Map<String, Object> map, final Principal principal) {
"""
Finalize profile response.
@param accessTokenTicket the access token ticket
@param map the map
@param principal the authentication principal
"""
val service = accessTokenTicket.getService();
val registeredService = servicesManager.findServiceBy(service);
if (registeredService instanceof OAuthRegisteredService) {
val oauth = (OAuthRegisteredService) registeredService;
map.put(OAuth20Constants.CLIENT_ID, oauth.getClientId());
map.put(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
}
} | java | protected void finalizeProfileResponse(final AccessToken accessTokenTicket, final Map<String, Object> map, final Principal principal) {
val service = accessTokenTicket.getService();
val registeredService = servicesManager.findServiceBy(service);
if (registeredService instanceof OAuthRegisteredService) {
val oauth = (OAuthRegisteredService) registeredService;
map.put(OAuth20Constants.CLIENT_ID, oauth.getClientId());
map.put(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
}
} | [
"protected",
"void",
"finalizeProfileResponse",
"(",
"final",
"AccessToken",
"accessTokenTicket",
",",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"final",
"Principal",
"principal",
")",
"{",
"val",
"service",
"=",
"accessTokenTicket",
".",
"getService",
"(",
")",
";",
"val",
"registeredService",
"=",
"servicesManager",
".",
"findServiceBy",
"(",
"service",
")",
";",
"if",
"(",
"registeredService",
"instanceof",
"OAuthRegisteredService",
")",
"{",
"val",
"oauth",
"=",
"(",
"OAuthRegisteredService",
")",
"registeredService",
";",
"map",
".",
"put",
"(",
"OAuth20Constants",
".",
"CLIENT_ID",
",",
"oauth",
".",
"getClientId",
"(",
")",
")",
";",
"map",
".",
"put",
"(",
"CasProtocolConstants",
".",
"PARAMETER_SERVICE",
",",
"service",
".",
"getId",
"(",
")",
")",
";",
"}",
"}"
] | Finalize profile response.
@param accessTokenTicket the access token ticket
@param map the map
@param principal the authentication principal | [
"Finalize",
"profile",
"response",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/profile/DefaultOAuth20UserProfileDataCreator.java#L85-L93 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/renderer/animation/transformation/Rotation.java | Rotation.doTransform | @Override
protected void doTransform(ITransformable.Rotate transformable, float comp) {
"""
Calculates the transformation.
@param transformable the transformable
@param comp the comp
"""
float from = reversed ? toAngle : fromAngle;
float to = reversed ? fromAngle : toAngle;
transformable.rotate(from + (to - from) * comp, axisX, axisY, axisZ, offsetX, offsetY, offsetZ);
} | java | @Override
protected void doTransform(ITransformable.Rotate transformable, float comp)
{
float from = reversed ? toAngle : fromAngle;
float to = reversed ? fromAngle : toAngle;
transformable.rotate(from + (to - from) * comp, axisX, axisY, axisZ, offsetX, offsetY, offsetZ);
} | [
"@",
"Override",
"protected",
"void",
"doTransform",
"(",
"ITransformable",
".",
"Rotate",
"transformable",
",",
"float",
"comp",
")",
"{",
"float",
"from",
"=",
"reversed",
"?",
"toAngle",
":",
"fromAngle",
";",
"float",
"to",
"=",
"reversed",
"?",
"fromAngle",
":",
"toAngle",
";",
"transformable",
".",
"rotate",
"(",
"from",
"+",
"(",
"to",
"-",
"from",
")",
"*",
"comp",
",",
"axisX",
",",
"axisY",
",",
"axisZ",
",",
"offsetX",
",",
"offsetY",
",",
"offsetZ",
")",
";",
"}"
] | Calculates the transformation.
@param transformable the transformable
@param comp the comp | [
"Calculates",
"the",
"transformation",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/animation/transformation/Rotation.java#L166-L172 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.createStrictPartialMockAndInvokeDefaultConstructor | public static <T> T createStrictPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames)
throws Exception {
"""
A utility method that may be used to strictly mock several methods in an
easy way (by just passing in the method names of the method you wish to
mock). The mock object created will support mocking of final methods and
invokes the default constructor (even if it's private).
@param <T> the type of the mock object
@param type the type of the mock object
@param methodNames The names of the methods that should be mocked. If
{@code null}, then this method will have the same effect
as just calling {@link #createMock(Class, Method...)} with the
second parameter as {@code new Method[0]} (i.e. all
methods in that class will be mocked).
@return the mock object.
"""
return createStrictMock(type, new ConstructorArgs(Whitebox.getConstructor(type)),
Whitebox.getMethods(type, methodNames));
} | java | public static <T> T createStrictPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames)
throws Exception {
return createStrictMock(type, new ConstructorArgs(Whitebox.getConstructor(type)),
Whitebox.getMethods(type, methodNames));
} | [
"public",
"static",
"<",
"T",
">",
"T",
"createStrictPartialMockAndInvokeDefaultConstructor",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"...",
"methodNames",
")",
"throws",
"Exception",
"{",
"return",
"createStrictMock",
"(",
"type",
",",
"new",
"ConstructorArgs",
"(",
"Whitebox",
".",
"getConstructor",
"(",
"type",
")",
")",
",",
"Whitebox",
".",
"getMethods",
"(",
"type",
",",
"methodNames",
")",
")",
";",
"}"
] | A utility method that may be used to strictly mock several methods in an
easy way (by just passing in the method names of the method you wish to
mock). The mock object created will support mocking of final methods and
invokes the default constructor (even if it's private).
@param <T> the type of the mock object
@param type the type of the mock object
@param methodNames The names of the methods that should be mocked. If
{@code null}, then this method will have the same effect
as just calling {@link #createMock(Class, Method...)} with the
second parameter as {@code new Method[0]} (i.e. all
methods in that class will be mocked).
@return the mock object. | [
"A",
"utility",
"method",
"that",
"may",
"be",
"used",
"to",
"strictly",
"mock",
"several",
"methods",
"in",
"an",
"easy",
"way",
"(",
"by",
"just",
"passing",
"in",
"the",
"method",
"names",
"of",
"the",
"method",
"you",
"wish",
"to",
"mock",
")",
".",
"The",
"mock",
"object",
"created",
"will",
"support",
"mocking",
"of",
"final",
"methods",
"and",
"invokes",
"the",
"default",
"constructor",
"(",
"even",
"if",
"it",
"s",
"private",
")",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L880-L884 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/ProfilePictureView.java | ProfilePictureView.onLayout | @Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
"""
In addition to calling super.Layout(), we also attempt to get a new image that
is properly size for the layout dimensions
"""
super.onLayout(changed, left, top, right, bottom);
// See if the image needs redrawing
refreshImage(false);
} | java | @Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// See if the image needs redrawing
refreshImage(false);
} | [
"@",
"Override",
"protected",
"void",
"onLayout",
"(",
"boolean",
"changed",
",",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
")",
"{",
"super",
".",
"onLayout",
"(",
"changed",
",",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
";",
"// See if the image needs redrawing",
"refreshImage",
"(",
"false",
")",
";",
"}"
] | In addition to calling super.Layout(), we also attempt to get a new image that
is properly size for the layout dimensions | [
"In",
"addition",
"to",
"calling",
"super",
".",
"Layout",
"()",
"we",
"also",
"attempt",
"to",
"get",
"a",
"new",
"image",
"that",
"is",
"properly",
"size",
"for",
"the",
"layout",
"dimensions"
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/ProfilePictureView.java#L302-L308 |
wildfly/wildfly-core | protocol/src/main/java/org/jboss/as/protocol/ProtocolConnectionUtils.java | ProtocolConnectionUtils.connectSync | public static Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {
"""
Connect sync.
@param configuration the protocol configuration
@return the connection
@throws IOException
"""
long timeoutMillis = configuration.getConnectionTimeout();
CallbackHandler handler = configuration.getCallbackHandler();
final CallbackHandler actualHandler;
ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();
// Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.
if (timeoutHandler == null) {
GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();
// No point wrapping our AnonymousCallbackHandler.
actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;
timeoutHandler = defaultTimeoutHandler;
} else {
actualHandler = handler;
}
final IoFuture<Connection> future = connect(actualHandler, configuration);
IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);
if (status == IoFuture.Status.DONE) {
return future.get();
}
if (status == IoFuture.Status.FAILED) {
throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());
}
throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());
} | java | public static Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {
long timeoutMillis = configuration.getConnectionTimeout();
CallbackHandler handler = configuration.getCallbackHandler();
final CallbackHandler actualHandler;
ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();
// Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.
if (timeoutHandler == null) {
GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();
// No point wrapping our AnonymousCallbackHandler.
actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;
timeoutHandler = defaultTimeoutHandler;
} else {
actualHandler = handler;
}
final IoFuture<Connection> future = connect(actualHandler, configuration);
IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);
if (status == IoFuture.Status.DONE) {
return future.get();
}
if (status == IoFuture.Status.FAILED) {
throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());
}
throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());
} | [
"public",
"static",
"Connection",
"connectSync",
"(",
"final",
"ProtocolConnectionConfiguration",
"configuration",
")",
"throws",
"IOException",
"{",
"long",
"timeoutMillis",
"=",
"configuration",
".",
"getConnectionTimeout",
"(",
")",
";",
"CallbackHandler",
"handler",
"=",
"configuration",
".",
"getCallbackHandler",
"(",
")",
";",
"final",
"CallbackHandler",
"actualHandler",
";",
"ProtocolTimeoutHandler",
"timeoutHandler",
"=",
"configuration",
".",
"getTimeoutHandler",
"(",
")",
";",
"// Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.",
"if",
"(",
"timeoutHandler",
"==",
"null",
")",
"{",
"GeneralTimeoutHandler",
"defaultTimeoutHandler",
"=",
"new",
"GeneralTimeoutHandler",
"(",
")",
";",
"// No point wrapping our AnonymousCallbackHandler.",
"actualHandler",
"=",
"handler",
"!=",
"null",
"?",
"new",
"WrapperCallbackHandler",
"(",
"defaultTimeoutHandler",
",",
"handler",
")",
":",
"null",
";",
"timeoutHandler",
"=",
"defaultTimeoutHandler",
";",
"}",
"else",
"{",
"actualHandler",
"=",
"handler",
";",
"}",
"final",
"IoFuture",
"<",
"Connection",
">",
"future",
"=",
"connect",
"(",
"actualHandler",
",",
"configuration",
")",
";",
"IoFuture",
".",
"Status",
"status",
"=",
"timeoutHandler",
".",
"await",
"(",
"future",
",",
"timeoutMillis",
")",
";",
"if",
"(",
"status",
"==",
"IoFuture",
".",
"Status",
".",
"DONE",
")",
"{",
"return",
"future",
".",
"get",
"(",
")",
";",
"}",
"if",
"(",
"status",
"==",
"IoFuture",
".",
"Status",
".",
"FAILED",
")",
"{",
"throw",
"ProtocolLogger",
".",
"ROOT_LOGGER",
".",
"failedToConnect",
"(",
"configuration",
".",
"getUri",
"(",
")",
",",
"future",
".",
"getException",
"(",
")",
")",
";",
"}",
"throw",
"ProtocolLogger",
".",
"ROOT_LOGGER",
".",
"couldNotConnect",
"(",
"configuration",
".",
"getUri",
"(",
")",
")",
";",
"}"
] | Connect sync.
@param configuration the protocol configuration
@return the connection
@throws IOException | [
"Connect",
"sync",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/ProtocolConnectionUtils.java#L105-L131 |
gosu-lang/gosu-lang | gosu-core/src/main/java/gw/internal/gosu/parser/ParsedElement.java | ParsedElement.getContainedParsedElementsByType | @SuppressWarnings("unchecked" )
public <E extends IParsedElement> boolean getContainedParsedElementsByType( Class<E> parsedElementType, List<E> listResults ) {
"""
Find all the parsed elements of a given type contained within this parsed
element.
@param parsedElementType The type of parsed element to find.
@param listResults A list of all the contained parsed elements matching the
specified type. Can be null if you are only interested in whether or not
parsedElementType exists in this element.
@return True iff one or more parseElementType are found.
"""
return getContainedParsedElementsByTypes( (List<IParsedElement>)listResults, parsedElementType );
} | java | @SuppressWarnings("unchecked" )
public <E extends IParsedElement> boolean getContainedParsedElementsByType( Class<E> parsedElementType, List<E> listResults )
{
return getContainedParsedElementsByTypes( (List<IParsedElement>)listResults, parsedElementType );
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"E",
"extends",
"IParsedElement",
">",
"boolean",
"getContainedParsedElementsByType",
"(",
"Class",
"<",
"E",
">",
"parsedElementType",
",",
"List",
"<",
"E",
">",
"listResults",
")",
"{",
"return",
"getContainedParsedElementsByTypes",
"(",
"(",
"List",
"<",
"IParsedElement",
">",
")",
"listResults",
",",
"parsedElementType",
")",
";",
"}"
] | Find all the parsed elements of a given type contained within this parsed
element.
@param parsedElementType The type of parsed element to find.
@param listResults A list of all the contained parsed elements matching the
specified type. Can be null if you are only interested in whether or not
parsedElementType exists in this element.
@return True iff one or more parseElementType are found. | [
"Find",
"all",
"the",
"parsed",
"elements",
"of",
"a",
"given",
"type",
"contained",
"within",
"this",
"parsed",
"element",
"."
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/ParsedElement.java#L765-L769 |
intellimate/Izou | src/main/java/org/intellimate/izou/security/SecurityManager.java | SecurityManager.createSecurityManager | public static SecurityManager createSecurityManager(SystemMail systemMail, Main main) throws IllegalAccessException {
"""
Creates a SecurityManager. There can only be one single SecurityManager, so calling this method twice
will cause an illegal access exception.
@param systemMail the system mail object in order to send e-mails to owner in case of emergency
@param main a reference to the main instance
@return a SecurityManager from Izou
@throws IllegalAccessException thrown if this method is called more than once
"""
if (!exists) {
SecurityManager securityManager = new SecurityManager(systemMail, main);
exists = true;
return securityManager;
}
throw new IllegalAccessException("Cannot create more than one instance of IzouSecurityManager");
} | java | public static SecurityManager createSecurityManager(SystemMail systemMail, Main main) throws IllegalAccessException {
if (!exists) {
SecurityManager securityManager = new SecurityManager(systemMail, main);
exists = true;
return securityManager;
}
throw new IllegalAccessException("Cannot create more than one instance of IzouSecurityManager");
} | [
"public",
"static",
"SecurityManager",
"createSecurityManager",
"(",
"SystemMail",
"systemMail",
",",
"Main",
"main",
")",
"throws",
"IllegalAccessException",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"SecurityManager",
"securityManager",
"=",
"new",
"SecurityManager",
"(",
"systemMail",
",",
"main",
")",
";",
"exists",
"=",
"true",
";",
"return",
"securityManager",
";",
"}",
"throw",
"new",
"IllegalAccessException",
"(",
"\"Cannot create more than one instance of IzouSecurityManager\"",
")",
";",
"}"
] | Creates a SecurityManager. There can only be one single SecurityManager, so calling this method twice
will cause an illegal access exception.
@param systemMail the system mail object in order to send e-mails to owner in case of emergency
@param main a reference to the main instance
@return a SecurityManager from Izou
@throws IllegalAccessException thrown if this method is called more than once | [
"Creates",
"a",
"SecurityManager",
".",
"There",
"can",
"only",
"be",
"one",
"single",
"SecurityManager",
"so",
"calling",
"this",
"method",
"twice",
"will",
"cause",
"an",
"illegal",
"access",
"exception",
"."
] | train | https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/SecurityManager.java#L45-L52 |
Azure/azure-sdk-for-java | storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java | StorageAccountsInner.deleteManagementPoliciesAsync | public Observable<Void> deleteManagementPoliciesAsync(String resourceGroupName, String accountName) {
"""
Deletes the data policy rules associated with the specified storage account.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return deleteManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> deleteManagementPoliciesAsync(String resourceGroupName, String accountName) {
return deleteManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"deleteManagementPoliciesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"deleteManagementPoliciesWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Void",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponse",
"<",
"Void",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Deletes the data policy rules associated with the specified storage account.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Deletes",
"the",
"data",
"policy",
"rules",
"associated",
"with",
"the",
"specified",
"storage",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L1489-L1496 |
auth0/java-jwt | lib/src/main/java/com/auth0/jwt/TokenUtils.java | TokenUtils.splitToken | static String[] splitToken(String token) throws JWTDecodeException {
"""
Splits the given token on the "." chars into a String array with 3 parts.
@param token the string to split.
@return the array representing the 3 parts of the token.
@throws JWTDecodeException if the Token doesn't have 3 parts.
"""
String[] parts = token.split("\\.");
if (parts.length == 2 && token.endsWith(".")) {
//Tokens with alg='none' have empty String as Signature.
parts = new String[]{parts[0], parts[1], ""};
}
if (parts.length != 3) {
throw new JWTDecodeException(String.format("The token was expected to have 3 parts, but got %s.", parts.length));
}
return parts;
} | java | static String[] splitToken(String token) throws JWTDecodeException {
String[] parts = token.split("\\.");
if (parts.length == 2 && token.endsWith(".")) {
//Tokens with alg='none' have empty String as Signature.
parts = new String[]{parts[0], parts[1], ""};
}
if (parts.length != 3) {
throw new JWTDecodeException(String.format("The token was expected to have 3 parts, but got %s.", parts.length));
}
return parts;
} | [
"static",
"String",
"[",
"]",
"splitToken",
"(",
"String",
"token",
")",
"throws",
"JWTDecodeException",
"{",
"String",
"[",
"]",
"parts",
"=",
"token",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"if",
"(",
"parts",
".",
"length",
"==",
"2",
"&&",
"token",
".",
"endsWith",
"(",
"\".\"",
")",
")",
"{",
"//Tokens with alg='none' have empty String as Signature.",
"parts",
"=",
"new",
"String",
"[",
"]",
"{",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
",",
"\"\"",
"}",
";",
"}",
"if",
"(",
"parts",
".",
"length",
"!=",
"3",
")",
"{",
"throw",
"new",
"JWTDecodeException",
"(",
"String",
".",
"format",
"(",
"\"The token was expected to have 3 parts, but got %s.\"",
",",
"parts",
".",
"length",
")",
")",
";",
"}",
"return",
"parts",
";",
"}"
] | Splits the given token on the "." chars into a String array with 3 parts.
@param token the string to split.
@return the array representing the 3 parts of the token.
@throws JWTDecodeException if the Token doesn't have 3 parts. | [
"Splits",
"the",
"given",
"token",
"on",
"the",
".",
"chars",
"into",
"a",
"String",
"array",
"with",
"3",
"parts",
"."
] | train | https://github.com/auth0/java-jwt/blob/890538970a9699b7251a4bfe4f26e8d7605ad530/lib/src/main/java/com/auth0/jwt/TokenUtils.java#L14-L24 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BigIntegerExtensions.java | BigIntegerExtensions.operator_divide | @Inline(value="$1.divide($2)")
@Pure
public static BigInteger operator_divide(BigInteger a, BigInteger b) {
"""
The binary <code>divide</code> operator.
@param a
a BigInteger. May not be <code>null</code>.
@param b
a BigInteger. May not be <code>null</code>.
@return <code>a.divide(b)</code>
@throws NullPointerException
if {@code a} or {@code b} is <code>null</code>.
"""
return a.divide(b);
} | java | @Inline(value="$1.divide($2)")
@Pure
public static BigInteger operator_divide(BigInteger a, BigInteger b) {
return a.divide(b);
} | [
"@",
"Inline",
"(",
"value",
"=",
"\"$1.divide($2)\"",
")",
"@",
"Pure",
"public",
"static",
"BigInteger",
"operator_divide",
"(",
"BigInteger",
"a",
",",
"BigInteger",
"b",
")",
"{",
"return",
"a",
".",
"divide",
"(",
"b",
")",
";",
"}"
] | The binary <code>divide</code> operator.
@param a
a BigInteger. May not be <code>null</code>.
@param b
a BigInteger. May not be <code>null</code>.
@return <code>a.divide(b)</code>
@throws NullPointerException
if {@code a} or {@code b} is <code>null</code>. | [
"The",
"binary",
"<code",
">",
"divide<",
"/",
"code",
">",
"operator",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BigIntegerExtensions.java#L116-L120 |
apache/incubator-druid | core/src/main/java/org/apache/druid/collections/StupidPool.java | StupidPool.impossibleOffsetFailed | private void impossibleOffsetFailed(T object, ObjectId objectId, Cleaners.Cleanable cleanable, ObjectLeakNotifier notifier) {
"""
This should be impossible, because {@link ConcurrentLinkedQueue#offer(Object)} event don't have `return false;` in
it's body in OpenJDK 8.
"""
poolSize.decrementAndGet();
notifier.disable();
// Effectively does nothing, because notifier is disabled above. The purpose of this call is to deregister the
// cleaner from the internal global linked list of all cleaners in the JVM, and let it be reclaimed itself.
cleanable.clean();
log.error(
new ISE("Queue offer failed"),
"Could not offer object [%s] back into the queue, objectId [%s]",
object,
objectId
);
} | java | private void impossibleOffsetFailed(T object, ObjectId objectId, Cleaners.Cleanable cleanable, ObjectLeakNotifier notifier)
{
poolSize.decrementAndGet();
notifier.disable();
// Effectively does nothing, because notifier is disabled above. The purpose of this call is to deregister the
// cleaner from the internal global linked list of all cleaners in the JVM, and let it be reclaimed itself.
cleanable.clean();
log.error(
new ISE("Queue offer failed"),
"Could not offer object [%s] back into the queue, objectId [%s]",
object,
objectId
);
} | [
"private",
"void",
"impossibleOffsetFailed",
"(",
"T",
"object",
",",
"ObjectId",
"objectId",
",",
"Cleaners",
".",
"Cleanable",
"cleanable",
",",
"ObjectLeakNotifier",
"notifier",
")",
"{",
"poolSize",
".",
"decrementAndGet",
"(",
")",
";",
"notifier",
".",
"disable",
"(",
")",
";",
"// Effectively does nothing, because notifier is disabled above. The purpose of this call is to deregister the",
"// cleaner from the internal global linked list of all cleaners in the JVM, and let it be reclaimed itself.",
"cleanable",
".",
"clean",
"(",
")",
";",
"log",
".",
"error",
"(",
"new",
"ISE",
"(",
"\"Queue offer failed\"",
")",
",",
"\"Could not offer object [%s] back into the queue, objectId [%s]\"",
",",
"object",
",",
"objectId",
")",
";",
"}"
] | This should be impossible, because {@link ConcurrentLinkedQueue#offer(Object)} event don't have `return false;` in
it's body in OpenJDK 8. | [
"This",
"should",
"be",
"impossible",
"because",
"{"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/collections/StupidPool.java#L163-L176 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java | Node.getSubscriptions | public List<Subscription> getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
"""
Get the subscriptions currently associated with this node.
@return List of {@link Subscription}
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException
"""
return getSubscriptions(null, null);
} | java | public List<Subscription> getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return getSubscriptions(null, null);
} | [
"public",
"List",
"<",
"Subscription",
">",
"getSubscriptions",
"(",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"return",
"getSubscriptions",
"(",
"null",
",",
"null",
")",
";",
"}"
] | Get the subscriptions currently associated with this node.
@return List of {@link Subscription}
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException | [
"Get",
"the",
"subscriptions",
"currently",
"associated",
"with",
"this",
"node",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java#L135-L137 |
enasequence/sequencetools | src/main/java/uk/ac/ebi/embl/api/validation/check/feature/FeatureValidationCheck.java | FeatureValidationCheck.reportError | protected ValidationMessage<Origin> reportError(Origin origin, String messageKey,
Object... params) {
"""
Creates an error validation message for the feature and adds it to
the validation result.
@param origin the origin
@param messageKey a message key
@param params message parameters
"""
return reportMessage(Severity.ERROR, origin, messageKey, params);
} | java | protected ValidationMessage<Origin> reportError(Origin origin, String messageKey,
Object... params) {
return reportMessage(Severity.ERROR, origin, messageKey, params);
} | [
"protected",
"ValidationMessage",
"<",
"Origin",
">",
"reportError",
"(",
"Origin",
"origin",
",",
"String",
"messageKey",
",",
"Object",
"...",
"params",
")",
"{",
"return",
"reportMessage",
"(",
"Severity",
".",
"ERROR",
",",
"origin",
",",
"messageKey",
",",
"params",
")",
";",
"}"
] | Creates an error validation message for the feature and adds it to
the validation result.
@param origin the origin
@param messageKey a message key
@param params message parameters | [
"Creates",
"an",
"error",
"validation",
"message",
"for",
"the",
"feature",
"and",
"adds",
"it",
"to",
"the",
"validation",
"result",
"."
] | train | https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/check/feature/FeatureValidationCheck.java#L67-L70 |
glyptodon/guacamole-client | guacamole/src/main/java/org/apache/guacamole/extension/DirectoryClassLoader.java | DirectoryClassLoader.getJarURLs | private static URL[] getJarURLs(File dir) throws GuacamoleException {
"""
Returns all .jar files within the given directory as an array of URLs.
@param dir
The directory to retrieve all .jar files from.
@return
An array of the URLs of all .jar files within the given directory.
@throws GuacamoleException
If the given file is not a directory, or the contents of the given
directory cannot be read.
"""
// Validate directory is indeed a directory
if (!dir.isDirectory())
throw new GuacamoleException(dir + " is not a directory.");
// Get list of URLs for all .jar's in the lib directory
Collection<URL> jarURLs = new ArrayList<URL>();
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// If it ends with .jar, accept the file
return name.endsWith(".jar");
}
});
// Verify directory was successfully read
if (files == null)
throw new GuacamoleException("Unable to read contents of directory " + dir);
// Add the URL for each .jar to the jar URL list
for (File file : files) {
try {
jarURLs.add(file.toURI().toURL());
}
catch (MalformedURLException e) {
throw new GuacamoleException(e);
}
}
// Set delegate classloader to new URLClassLoader which loads from the .jars found above.
URL[] urls = new URL[jarURLs.size()];
return jarURLs.toArray(urls);
} | java | private static URL[] getJarURLs(File dir) throws GuacamoleException {
// Validate directory is indeed a directory
if (!dir.isDirectory())
throw new GuacamoleException(dir + " is not a directory.");
// Get list of URLs for all .jar's in the lib directory
Collection<URL> jarURLs = new ArrayList<URL>();
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// If it ends with .jar, accept the file
return name.endsWith(".jar");
}
});
// Verify directory was successfully read
if (files == null)
throw new GuacamoleException("Unable to read contents of directory " + dir);
// Add the URL for each .jar to the jar URL list
for (File file : files) {
try {
jarURLs.add(file.toURI().toURL());
}
catch (MalformedURLException e) {
throw new GuacamoleException(e);
}
}
// Set delegate classloader to new URLClassLoader which loads from the .jars found above.
URL[] urls = new URL[jarURLs.size()];
return jarURLs.toArray(urls);
} | [
"private",
"static",
"URL",
"[",
"]",
"getJarURLs",
"(",
"File",
"dir",
")",
"throws",
"GuacamoleException",
"{",
"// Validate directory is indeed a directory",
"if",
"(",
"!",
"dir",
".",
"isDirectory",
"(",
")",
")",
"throw",
"new",
"GuacamoleException",
"(",
"dir",
"+",
"\" is not a directory.\"",
")",
";",
"// Get list of URLs for all .jar's in the lib directory",
"Collection",
"<",
"URL",
">",
"jarURLs",
"=",
"new",
"ArrayList",
"<",
"URL",
">",
"(",
")",
";",
"File",
"[",
"]",
"files",
"=",
"dir",
".",
"listFiles",
"(",
"new",
"FilenameFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"File",
"dir",
",",
"String",
"name",
")",
"{",
"// If it ends with .jar, accept the file",
"return",
"name",
".",
"endsWith",
"(",
"\".jar\"",
")",
";",
"}",
"}",
")",
";",
"// Verify directory was successfully read",
"if",
"(",
"files",
"==",
"null",
")",
"throw",
"new",
"GuacamoleException",
"(",
"\"Unable to read contents of directory \"",
"+",
"dir",
")",
";",
"// Add the URL for each .jar to the jar URL list",
"for",
"(",
"File",
"file",
":",
"files",
")",
"{",
"try",
"{",
"jarURLs",
".",
"add",
"(",
"file",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"GuacamoleException",
"(",
"e",
")",
";",
"}",
"}",
"// Set delegate classloader to new URLClassLoader which loads from the .jars found above.",
"URL",
"[",
"]",
"urls",
"=",
"new",
"URL",
"[",
"jarURLs",
".",
"size",
"(",
")",
"]",
";",
"return",
"jarURLs",
".",
"toArray",
"(",
"urls",
")",
";",
"}"
] | Returns all .jar files within the given directory as an array of URLs.
@param dir
The directory to retrieve all .jar files from.
@return
An array of the URLs of all .jar files within the given directory.
@throws GuacamoleException
If the given file is not a directory, or the contents of the given
directory cannot be read. | [
"Returns",
"all",
".",
"jar",
"files",
"within",
"the",
"given",
"directory",
"as",
"an",
"array",
"of",
"URLs",
"."
] | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole/src/main/java/org/apache/guacamole/extension/DirectoryClassLoader.java#L91-L131 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/IntentUtils.java | IntentUtils.openPlayStore | public static Intent openPlayStore(Context context, boolean openInBrowser) {
"""
Open app page at Google Play
@param context Application context
@param openInBrowser Should we try to open application page in web browser
if Play Store app not found on device
"""
String appPackageName = context.getPackageName();
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
if (isIntentAvailable(context, marketIntent)) {
return marketIntent;
}
if (openInBrowser) {
return openLink("https://play.google.com/store/apps/details?id=" + appPackageName);
}
return marketIntent;
} | java | public static Intent openPlayStore(Context context, boolean openInBrowser) {
String appPackageName = context.getPackageName();
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
if (isIntentAvailable(context, marketIntent)) {
return marketIntent;
}
if (openInBrowser) {
return openLink("https://play.google.com/store/apps/details?id=" + appPackageName);
}
return marketIntent;
} | [
"public",
"static",
"Intent",
"openPlayStore",
"(",
"Context",
"context",
",",
"boolean",
"openInBrowser",
")",
"{",
"String",
"appPackageName",
"=",
"context",
".",
"getPackageName",
"(",
")",
";",
"Intent",
"marketIntent",
"=",
"new",
"Intent",
"(",
"Intent",
".",
"ACTION_VIEW",
",",
"Uri",
".",
"parse",
"(",
"\"market://details?id=\"",
"+",
"appPackageName",
")",
")",
";",
"if",
"(",
"isIntentAvailable",
"(",
"context",
",",
"marketIntent",
")",
")",
"{",
"return",
"marketIntent",
";",
"}",
"if",
"(",
"openInBrowser",
")",
"{",
"return",
"openLink",
"(",
"\"https://play.google.com/store/apps/details?id=\"",
"+",
"appPackageName",
")",
";",
"}",
"return",
"marketIntent",
";",
"}"
] | Open app page at Google Play
@param context Application context
@param openInBrowser Should we try to open application page in web browser
if Play Store app not found on device | [
"Open",
"app",
"page",
"at",
"Google",
"Play"
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/IntentUtils.java#L58-L68 |
structurizr/java | structurizr-client/src/com/structurizr/util/WorkspaceUtils.java | WorkspaceUtils.saveWorkspaceToJson | public static void saveWorkspaceToJson(Workspace workspace, File file) throws Exception {
"""
Saves a workspace to a JSON definition as a file.
@param workspace a Workspace object
@param file a File representing the JSON definition
@throws Exception if something goes wrong
"""
if (workspace == null) {
throw new IllegalArgumentException("A workspace must be provided.");
} else if (file == null) {
throw new IllegalArgumentException("The path to a JSON file must be specified.");
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
new JsonWriter(true).write(workspace, writer);
writer.flush();
writer.close();
} | java | public static void saveWorkspaceToJson(Workspace workspace, File file) throws Exception {
if (workspace == null) {
throw new IllegalArgumentException("A workspace must be provided.");
} else if (file == null) {
throw new IllegalArgumentException("The path to a JSON file must be specified.");
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
new JsonWriter(true).write(workspace, writer);
writer.flush();
writer.close();
} | [
"public",
"static",
"void",
"saveWorkspaceToJson",
"(",
"Workspace",
"workspace",
",",
"File",
"file",
")",
"throws",
"Exception",
"{",
"if",
"(",
"workspace",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"A workspace must be provided.\"",
")",
";",
"}",
"else",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The path to a JSON file must be specified.\"",
")",
";",
"}",
"OutputStreamWriter",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"new",
"JsonWriter",
"(",
"true",
")",
".",
"write",
"(",
"workspace",
",",
"writer",
")",
";",
"writer",
".",
"flush",
"(",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}"
] | Saves a workspace to a JSON definition as a file.
@param workspace a Workspace object
@param file a File representing the JSON definition
@throws Exception if something goes wrong | [
"Saves",
"a",
"workspace",
"to",
"a",
"JSON",
"definition",
"as",
"a",
"file",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-client/src/com/structurizr/util/WorkspaceUtils.java#L39-L50 |
Red5/red5-websocket | src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java | WebSocketDecoder.buildHandshakeResponse | private HandshakeResponse buildHandshakeResponse(WebSocketConnection conn, String clientKey) throws WebSocketException {
"""
Build a handshake response based on the given client key.
@param clientKey
@return response
@throws WebSocketException
"""
if (log.isDebugEnabled()) {
log.debug("buildHandshakeResponse: {} client key: {}", conn, clientKey);
}
byte[] accept;
try {
// performs the accept creation routine from RFC6455 @see <a href="http://tools.ietf.org/html/rfc6455">RFC6455</a>
// concatenate the key and magic string, then SHA1 hash and base64 encode
MessageDigest md = MessageDigest.getInstance("SHA1");
accept = Base64.encode(md.digest((clientKey + Constants.WEBSOCKET_MAGIC_STRING).getBytes()));
} catch (NoSuchAlgorithmException e) {
throw new WebSocketException("Algorithm is missing");
}
// make up reply data...
IoBuffer buf = IoBuffer.allocate(308);
buf.setAutoExpand(true);
buf.put("HTTP/1.1 101 Switching Protocols".getBytes());
buf.put(Constants.CRLF);
buf.put("Upgrade: websocket".getBytes());
buf.put(Constants.CRLF);
buf.put("Connection: Upgrade".getBytes());
buf.put(Constants.CRLF);
buf.put("Server: Red5".getBytes());
buf.put(Constants.CRLF);
buf.put("Sec-WebSocket-Version-Server: 13".getBytes());
buf.put(Constants.CRLF);
buf.put(String.format("Sec-WebSocket-Origin: %s", conn.getOrigin()).getBytes());
buf.put(Constants.CRLF);
buf.put(String.format("Sec-WebSocket-Location: %s", conn.getHost()).getBytes());
buf.put(Constants.CRLF);
// send back extensions if enabled
if (conn.hasExtensions()) {
buf.put(String.format("Sec-WebSocket-Extensions: %s", conn.getExtensionsAsString()).getBytes());
buf.put(Constants.CRLF);
}
// send back protocol if enabled
if (conn.hasProtocol()) {
buf.put(String.format("Sec-WebSocket-Protocol: %s", conn.getProtocol()).getBytes());
buf.put(Constants.CRLF);
}
buf.put(String.format("Sec-WebSocket-Accept: %s", new String(accept)).getBytes());
buf.put(Constants.CRLF);
buf.put(Constants.CRLF);
// if any bytes follow this crlf, the follow-up data will be corrupted
if (log.isTraceEnabled()) {
log.trace("Handshake response size: {}", buf.limit());
}
return new HandshakeResponse(buf);
} | java | private HandshakeResponse buildHandshakeResponse(WebSocketConnection conn, String clientKey) throws WebSocketException {
if (log.isDebugEnabled()) {
log.debug("buildHandshakeResponse: {} client key: {}", conn, clientKey);
}
byte[] accept;
try {
// performs the accept creation routine from RFC6455 @see <a href="http://tools.ietf.org/html/rfc6455">RFC6455</a>
// concatenate the key and magic string, then SHA1 hash and base64 encode
MessageDigest md = MessageDigest.getInstance("SHA1");
accept = Base64.encode(md.digest((clientKey + Constants.WEBSOCKET_MAGIC_STRING).getBytes()));
} catch (NoSuchAlgorithmException e) {
throw new WebSocketException("Algorithm is missing");
}
// make up reply data...
IoBuffer buf = IoBuffer.allocate(308);
buf.setAutoExpand(true);
buf.put("HTTP/1.1 101 Switching Protocols".getBytes());
buf.put(Constants.CRLF);
buf.put("Upgrade: websocket".getBytes());
buf.put(Constants.CRLF);
buf.put("Connection: Upgrade".getBytes());
buf.put(Constants.CRLF);
buf.put("Server: Red5".getBytes());
buf.put(Constants.CRLF);
buf.put("Sec-WebSocket-Version-Server: 13".getBytes());
buf.put(Constants.CRLF);
buf.put(String.format("Sec-WebSocket-Origin: %s", conn.getOrigin()).getBytes());
buf.put(Constants.CRLF);
buf.put(String.format("Sec-WebSocket-Location: %s", conn.getHost()).getBytes());
buf.put(Constants.CRLF);
// send back extensions if enabled
if (conn.hasExtensions()) {
buf.put(String.format("Sec-WebSocket-Extensions: %s", conn.getExtensionsAsString()).getBytes());
buf.put(Constants.CRLF);
}
// send back protocol if enabled
if (conn.hasProtocol()) {
buf.put(String.format("Sec-WebSocket-Protocol: %s", conn.getProtocol()).getBytes());
buf.put(Constants.CRLF);
}
buf.put(String.format("Sec-WebSocket-Accept: %s", new String(accept)).getBytes());
buf.put(Constants.CRLF);
buf.put(Constants.CRLF);
// if any bytes follow this crlf, the follow-up data will be corrupted
if (log.isTraceEnabled()) {
log.trace("Handshake response size: {}", buf.limit());
}
return new HandshakeResponse(buf);
} | [
"private",
"HandshakeResponse",
"buildHandshakeResponse",
"(",
"WebSocketConnection",
"conn",
",",
"String",
"clientKey",
")",
"throws",
"WebSocketException",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"buildHandshakeResponse: {} client key: {}\"",
",",
"conn",
",",
"clientKey",
")",
";",
"}",
"byte",
"[",
"]",
"accept",
";",
"try",
"{",
"// performs the accept creation routine from RFC6455 @see <a href=\"http://tools.ietf.org/html/rfc6455\">RFC6455</a>",
"// concatenate the key and magic string, then SHA1 hash and base64 encode",
"MessageDigest",
"md",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"SHA1\"",
")",
";",
"accept",
"=",
"Base64",
".",
"encode",
"(",
"md",
".",
"digest",
"(",
"(",
"clientKey",
"+",
"Constants",
".",
"WEBSOCKET_MAGIC_STRING",
")",
".",
"getBytes",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"e",
")",
"{",
"throw",
"new",
"WebSocketException",
"(",
"\"Algorithm is missing\"",
")",
";",
"}",
"// make up reply data...",
"IoBuffer",
"buf",
"=",
"IoBuffer",
".",
"allocate",
"(",
"308",
")",
";",
"buf",
".",
"setAutoExpand",
"(",
"true",
")",
";",
"buf",
".",
"put",
"(",
"\"HTTP/1.1 101 Switching Protocols\"",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"\"Upgrade: websocket\"",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"\"Connection: Upgrade\"",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"\"Server: Red5\"",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"\"Sec-WebSocket-Version-Server: 13\"",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"Sec-WebSocket-Origin: %s\"",
",",
"conn",
".",
"getOrigin",
"(",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"Sec-WebSocket-Location: %s\"",
",",
"conn",
".",
"getHost",
"(",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"// send back extensions if enabled",
"if",
"(",
"conn",
".",
"hasExtensions",
"(",
")",
")",
"{",
"buf",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"Sec-WebSocket-Extensions: %s\"",
",",
"conn",
".",
"getExtensionsAsString",
"(",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"}",
"// send back protocol if enabled",
"if",
"(",
"conn",
".",
"hasProtocol",
"(",
")",
")",
"{",
"buf",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"Sec-WebSocket-Protocol: %s\"",
",",
"conn",
".",
"getProtocol",
"(",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"}",
"buf",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"Sec-WebSocket-Accept: %s\"",
",",
"new",
"String",
"(",
"accept",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"buf",
".",
"put",
"(",
"Constants",
".",
"CRLF",
")",
";",
"// if any bytes follow this crlf, the follow-up data will be corrupted",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"trace",
"(",
"\"Handshake response size: {}\"",
",",
"buf",
".",
"limit",
"(",
")",
")",
";",
"}",
"return",
"new",
"HandshakeResponse",
"(",
"buf",
")",
";",
"}"
] | Build a handshake response based on the given client key.
@param clientKey
@return response
@throws WebSocketException | [
"Build",
"a",
"handshake",
"response",
"based",
"on",
"the",
"given",
"client",
"key",
"."
] | train | https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java#L390-L438 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java | HintRule.addRemoveVendor | public void addRemoveVendor(String source, String name, String value, boolean regex, Confidence confidence) {
"""
Adds a given vendor to the list of evidence to remove when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
"""
removeVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
} | java | public void addRemoveVendor(String source, String name, String value, boolean regex, Confidence confidence) {
removeVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
} | [
"public",
"void",
"addRemoveVendor",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"removeVendor",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] | Adds a given vendor to the list of evidence to remove when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence | [
"Adds",
"a",
"given",
"vendor",
"to",
"the",
"list",
"of",
"evidence",
"to",
"remove",
"when",
"matched",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L213-L215 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.beginCreateOrUpdateAsync | public Observable<DataMigrationServiceInner> beginCreateOrUpdateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) {
"""
Create or update DMS Instance.
The services resource is the top-level resource that represents the Data Migration Service. The PUT method creates a new service or updates an existing one. When a service is updated, existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, "vm", which refers to a VM-based service, although other kinds may be added in the future. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider will reply when successful with 200 OK or 201 Created. Long-running operations use the provisioningState property.
@param groupName Name of the resource group
@param serviceName Name of the service
@param parameters Information about the service
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DataMigrationServiceInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() {
@Override
public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) {
return response.body();
}
});
} | java | public Observable<DataMigrationServiceInner> beginCreateOrUpdateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() {
@Override
public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DataMigrationServiceInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
",",
"DataMigrationServiceInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"DataMigrationServiceInner",
">",
",",
"DataMigrationServiceInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"DataMigrationServiceInner",
"call",
"(",
"ServiceResponse",
"<",
"DataMigrationServiceInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Create or update DMS Instance.
The services resource is the top-level resource that represents the Data Migration Service. The PUT method creates a new service or updates an existing one. When a service is updated, existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, "vm", which refers to a VM-based service, although other kinds may be added in the future. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider will reply when successful with 200 OK or 201 Created. Long-running operations use the provisioningState property.
@param groupName Name of the resource group
@param serviceName Name of the service
@param parameters Information about the service
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DataMigrationServiceInner object | [
"Create",
"or",
"update",
"DMS",
"Instance",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"The",
"PUT",
"method",
"creates",
"a",
"new",
"service",
"or",
"updates",
"an",
"existing",
"one",
".",
"When",
"a",
"service",
"is",
"updated",
"existing",
"child",
"resources",
"(",
"i",
".",
"e",
".",
"tasks",
")",
"are",
"unaffected",
".",
"Services",
"currently",
"support",
"a",
"single",
"kind",
"vm",
"which",
"refers",
"to",
"a",
"VM",
"-",
"based",
"service",
"although",
"other",
"kinds",
"may",
"be",
"added",
"in",
"the",
"future",
".",
"This",
"method",
"can",
"change",
"the",
"kind",
"SKU",
"and",
"network",
"of",
"the",
"service",
"but",
"if",
"tasks",
"are",
"currently",
"running",
"(",
"i",
".",
"e",
".",
"the",
"service",
"is",
"busy",
")",
"this",
"will",
"fail",
"with",
"400",
"Bad",
"Request",
"(",
"ServiceIsBusy",
")",
".",
"The",
"provider",
"will",
"reply",
"when",
"successful",
"with",
"200",
"OK",
"or",
"201",
"Created",
".",
"Long",
"-",
"running",
"operations",
"use",
"the",
"provisioningState",
"property",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L274-L281 |
code4everything/util | src/main/java/com/zhazhapan/util/Checker.java | Checker.checkNull | public static Float checkNull(Float value, Float elseValue) {
"""
检查Float是否为null
@param value 值
@param elseValue 为null返回的值
@return {@link Float}
@since 1.0.8
"""
return isNull(value) ? elseValue : value;
} | java | public static Float checkNull(Float value, Float elseValue) {
return isNull(value) ? elseValue : value;
} | [
"public",
"static",
"Float",
"checkNull",
"(",
"Float",
"value",
",",
"Float",
"elseValue",
")",
"{",
"return",
"isNull",
"(",
"value",
")",
"?",
"elseValue",
":",
"value",
";",
"}"
] | 检查Float是否为null
@param value 值
@param elseValue 为null返回的值
@return {@link Float}
@since 1.0.8 | [
"检查Float是否为null"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L1294-L1296 |
BlueBrain/bluima | modules/bluima_pdf/src/main/java/edu/psu/seersuite/extractors/tableextractor/Debug.java | Debug.printTableMeta | public static void printTableMeta(String outputDirPath, File pdfFile, String meta) {
"""
After detecting and extracting a table, this method enables us to save the table metadata file locally for later performance evaluation.
@param outputDirPath
the directory path where the middle-stage results will go to
@param pdfFile
the PDF file being processed
@param meta
the table metadata to be printed
@throws IOException
"""
try {
File middleDir = new File(outputDirPath, "metadata");
if (!middleDir.exists()) {
middleDir.mkdirs();
}
File tableMetaFile = new File(middleDir, pdfFile.getName() + ".metadata");
BufferedWriter bw0 = new BufferedWriter(new FileWriter(tableMetaFile));
//System.out.println(meta);
bw0.write(meta);
bw0.close();
}
catch (IOException e){
System.out.printf("[Debug Error] IOException\n");
}
} | java | public static void printTableMeta(String outputDirPath, File pdfFile, String meta) {
try {
File middleDir = new File(outputDirPath, "metadata");
if (!middleDir.exists()) {
middleDir.mkdirs();
}
File tableMetaFile = new File(middleDir, pdfFile.getName() + ".metadata");
BufferedWriter bw0 = new BufferedWriter(new FileWriter(tableMetaFile));
//System.out.println(meta);
bw0.write(meta);
bw0.close();
}
catch (IOException e){
System.out.printf("[Debug Error] IOException\n");
}
} | [
"public",
"static",
"void",
"printTableMeta",
"(",
"String",
"outputDirPath",
",",
"File",
"pdfFile",
",",
"String",
"meta",
")",
"{",
"try",
"{",
"File",
"middleDir",
"=",
"new",
"File",
"(",
"outputDirPath",
",",
"\"metadata\"",
")",
";",
"if",
"(",
"!",
"middleDir",
".",
"exists",
"(",
")",
")",
"{",
"middleDir",
".",
"mkdirs",
"(",
")",
";",
"}",
"File",
"tableMetaFile",
"=",
"new",
"File",
"(",
"middleDir",
",",
"pdfFile",
".",
"getName",
"(",
")",
"+",
"\".metadata\"",
")",
";",
"BufferedWriter",
"bw0",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"tableMetaFile",
")",
")",
";",
"//System.out.println(meta);\r",
"bw0",
".",
"write",
"(",
"meta",
")",
";",
"bw0",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"System",
".",
"out",
".",
"printf",
"(",
"\"[Debug Error] IOException\\n\"",
")",
";",
"}",
"}"
] | After detecting and extracting a table, this method enables us to save the table metadata file locally for later performance evaluation.
@param outputDirPath
the directory path where the middle-stage results will go to
@param pdfFile
the PDF file being processed
@param meta
the table metadata to be printed
@throws IOException | [
"After",
"detecting",
"and",
"extracting",
"a",
"table",
"this",
"method",
"enables",
"us",
"to",
"save",
"the",
"table",
"metadata",
"file",
"locally",
"for",
"later",
"performance",
"evaluation",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/edu/psu/seersuite/extractors/tableextractor/Debug.java#L116-L131 |
thinkaurelius/faunus | src/main/java/com/thinkaurelius/faunus/hdfs/HDFSTools.java | HDFSTools.getFileSize | public static long getFileSize(final FileSystem fs, final Path path, final PathFilter filter) throws IOException {
"""
/*public static String getSuffix(final String file) {
if (file.contains("."))
return file.substring(file.indexOf(".") + 1);
else
return "";
}
"""
long totalSize = 0l;
for (final Path p : getAllFilePaths(fs, path, filter)) {
totalSize = totalSize + fs.getFileStatus(p).getLen();
}
return totalSize;
} | java | public static long getFileSize(final FileSystem fs, final Path path, final PathFilter filter) throws IOException {
long totalSize = 0l;
for (final Path p : getAllFilePaths(fs, path, filter)) {
totalSize = totalSize + fs.getFileStatus(p).getLen();
}
return totalSize;
} | [
"public",
"static",
"long",
"getFileSize",
"(",
"final",
"FileSystem",
"fs",
",",
"final",
"Path",
"path",
",",
"final",
"PathFilter",
"filter",
")",
"throws",
"IOException",
"{",
"long",
"totalSize",
"=",
"0l",
";",
"for",
"(",
"final",
"Path",
"p",
":",
"getAllFilePaths",
"(",
"fs",
",",
"path",
",",
"filter",
")",
")",
"{",
"totalSize",
"=",
"totalSize",
"+",
"fs",
".",
"getFileStatus",
"(",
"p",
")",
".",
"getLen",
"(",
")",
";",
"}",
"return",
"totalSize",
";",
"}"
] | /*public static String getSuffix(final String file) {
if (file.contains("."))
return file.substring(file.indexOf(".") + 1);
else
return "";
} | [
"/",
"*",
"public",
"static",
"String",
"getSuffix",
"(",
"final",
"String",
"file",
")",
"{",
"if",
"(",
"file",
".",
"contains",
"(",
".",
"))",
"return",
"file",
".",
"substring",
"(",
"file",
".",
"indexOf",
"(",
".",
")",
"+",
"1",
")",
";",
"else",
"return",
";",
"}"
] | train | https://github.com/thinkaurelius/faunus/blob/1eb8494eeb3fe3b84a98d810d304ba01d55b0d6e/src/main/java/com/thinkaurelius/faunus/hdfs/HDFSTools.java#L41-L47 |
thinkaurelius/faunus | src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java | FaunusPipeline.interval | public FaunusPipeline interval(final String key, final Object startValue, final Object endValue) {
"""
Emit the current element it has a property value equal within the provided range.
@param key the property key of the element
@param startValue the start of the range (inclusive)
@param endValue the end of the range (exclusive)
@return the extended FaunusPipeline
"""
this.state.assertNotLocked();
this.state.assertNoProperty();
this.compiler.addMap(IntervalFilterMap.Map.class,
NullWritable.class,
FaunusVertex.class,
IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue));
makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue);
return this;
} | java | public FaunusPipeline interval(final String key, final Object startValue, final Object endValue) {
this.state.assertNotLocked();
this.state.assertNoProperty();
this.compiler.addMap(IntervalFilterMap.Map.class,
NullWritable.class,
FaunusVertex.class,
IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue));
makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue);
return this;
} | [
"public",
"FaunusPipeline",
"interval",
"(",
"final",
"String",
"key",
",",
"final",
"Object",
"startValue",
",",
"final",
"Object",
"endValue",
")",
"{",
"this",
".",
"state",
".",
"assertNotLocked",
"(",
")",
";",
"this",
".",
"state",
".",
"assertNoProperty",
"(",
")",
";",
"this",
".",
"compiler",
".",
"addMap",
"(",
"IntervalFilterMap",
".",
"Map",
".",
"class",
",",
"NullWritable",
".",
"class",
",",
"FaunusVertex",
".",
"class",
",",
"IntervalFilterMap",
".",
"createConfiguration",
"(",
"this",
".",
"state",
".",
"getElementType",
"(",
")",
",",
"key",
",",
"startValue",
",",
"endValue",
")",
")",
";",
"makeMapReduceString",
"(",
"IntervalFilterMap",
".",
"class",
",",
"key",
",",
"startValue",
",",
"endValue",
")",
";",
"return",
"this",
";",
"}"
] | Emit the current element it has a property value equal within the provided range.
@param key the property key of the element
@param startValue the start of the range (inclusive)
@param endValue the end of the range (exclusive)
@return the extended FaunusPipeline | [
"Emit",
"the",
"current",
"element",
"it",
"has",
"a",
"property",
"value",
"equal",
"within",
"the",
"provided",
"range",
"."
] | train | https://github.com/thinkaurelius/faunus/blob/1eb8494eeb3fe3b84a98d810d304ba01d55b0d6e/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java#L705-L715 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_sr.java | xen_health_sr.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
xen_health_sr_responses result = (xen_health_sr_responses) service.get_payload_formatter().string_to_resource(xen_health_sr_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_sr_response_array);
}
xen_health_sr[] result_xen_health_sr = new xen_health_sr[result.xen_health_sr_response_array.length];
for(int i = 0; i < result.xen_health_sr_response_array.length; i++)
{
result_xen_health_sr[i] = result.xen_health_sr_response_array[i].xen_health_sr[0];
}
return result_xen_health_sr;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_sr_responses result = (xen_health_sr_responses) service.get_payload_formatter().string_to_resource(xen_health_sr_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_sr_response_array);
}
xen_health_sr[] result_xen_health_sr = new xen_health_sr[result.xen_health_sr_response_array.length];
for(int i = 0; i < result.xen_health_sr_response_array.length; i++)
{
result_xen_health_sr[i] = result.xen_health_sr_response_array[i].xen_health_sr[0];
}
return result_xen_health_sr;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_health_sr_responses",
"result",
"=",
"(",
"xen_health_sr_responses",
")",
"service",
".",
"get_payload_formatter",
"(",
")",
".",
"string_to_resource",
"(",
"xen_health_sr_responses",
".",
"class",
",",
"response",
")",
";",
"if",
"(",
"result",
".",
"errorcode",
"!=",
"0",
")",
"{",
"if",
"(",
"result",
".",
"errorcode",
"==",
"SESSION_NOT_EXISTS",
")",
"service",
".",
"clear_session",
"(",
")",
";",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
",",
"(",
"base_response",
"[",
"]",
")",
"result",
".",
"xen_health_sr_response_array",
")",
";",
"}",
"xen_health_sr",
"[",
"]",
"result_xen_health_sr",
"=",
"new",
"xen_health_sr",
"[",
"result",
".",
"xen_health_sr_response_array",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"result",
".",
"xen_health_sr_response_array",
".",
"length",
";",
"i",
"++",
")",
"{",
"result_xen_health_sr",
"[",
"i",
"]",
"=",
"result",
".",
"xen_health_sr_response_array",
"[",
"i",
"]",
".",
"xen_health_sr",
"[",
"0",
"]",
";",
"}",
"return",
"result_xen_health_sr",
";",
"}"
] | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_sr.java#L325-L342 |
pmlopes/yoke | framework/src/main/java/com/jetdrone/vertx/yoke/security/SecretSecurity.java | SecretSecurity.getMac | public Mac getMac(final @NotNull String alias) {
"""
Creates a new Message Authentication Code
@param alias algorithm to use e.g.: HmacSHA256
@return Mac implementation
"""
try {
Mac mac = Mac.getInstance(getAlgorithm(alias));
mac.init(new SecretKeySpec(secret, mac.getAlgorithm()));
return mac;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
} | java | public Mac getMac(final @NotNull String alias) {
try {
Mac mac = Mac.getInstance(getAlgorithm(alias));
mac.init(new SecretKeySpec(secret, mac.getAlgorithm()));
return mac;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
} | [
"public",
"Mac",
"getMac",
"(",
"final",
"@",
"NotNull",
"String",
"alias",
")",
"{",
"try",
"{",
"Mac",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"getAlgorithm",
"(",
"alias",
")",
")",
";",
"mac",
".",
"init",
"(",
"new",
"SecretKeySpec",
"(",
"secret",
",",
"mac",
".",
"getAlgorithm",
"(",
")",
")",
")",
";",
"return",
"mac",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"|",
"InvalidKeyException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Creates a new Message Authentication Code
@param alias algorithm to use e.g.: HmacSHA256
@return Mac implementation | [
"Creates",
"a",
"new",
"Message",
"Authentication",
"Code"
] | train | https://github.com/pmlopes/yoke/blob/fe8a64036f09fb745f0644faddd46162d64faf3c/framework/src/main/java/com/jetdrone/vertx/yoke/security/SecretSecurity.java#L45-L54 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/StringUtils.java | StringUtils.trimToBool | public static boolean trimToBool(final String aString, final boolean aBool) {
"""
Trims a string object down into a boolean and has the ability to define what the default value should be. We
only offer the method with the default value because most times a boolean with either exist or not (and in the
case of not a default should be specified).
@param aString A boolean in string form
@param aBool A default boolean value
@return The boolean representation of the string value or the default value
"""
final String boolString = trimTo(aString, Boolean.toString(aBool));
return Boolean.parseBoolean(boolString);
} | java | public static boolean trimToBool(final String aString, final boolean aBool) {
final String boolString = trimTo(aString, Boolean.toString(aBool));
return Boolean.parseBoolean(boolString);
} | [
"public",
"static",
"boolean",
"trimToBool",
"(",
"final",
"String",
"aString",
",",
"final",
"boolean",
"aBool",
")",
"{",
"final",
"String",
"boolString",
"=",
"trimTo",
"(",
"aString",
",",
"Boolean",
".",
"toString",
"(",
"aBool",
")",
")",
";",
"return",
"Boolean",
".",
"parseBoolean",
"(",
"boolString",
")",
";",
"}"
] | Trims a string object down into a boolean and has the ability to define what the default value should be. We
only offer the method with the default value because most times a boolean with either exist or not (and in the
case of not a default should be specified).
@param aString A boolean in string form
@param aBool A default boolean value
@return The boolean representation of the string value or the default value | [
"Trims",
"a",
"string",
"object",
"down",
"into",
"a",
"boolean",
"and",
"has",
"the",
"ability",
"to",
"define",
"what",
"the",
"default",
"value",
"should",
"be",
".",
"We",
"only",
"offer",
"the",
"method",
"with",
"the",
"default",
"value",
"because",
"most",
"times",
"a",
"boolean",
"with",
"either",
"exist",
"or",
"not",
"(",
"and",
"in",
"the",
"case",
"of",
"not",
"a",
"default",
"should",
"be",
"specified",
")",
"."
] | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/StringUtils.java#L56-L59 |
ops4j/org.ops4j.pax.exam2 | containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/container/internal/DependenciesDeployer.java | DependenciesDeployer.copyReferencedArtifactsToDeployFolder | public void copyReferencedArtifactsToDeployFolder() {
"""
Copy dependencies specified as ProvisionOption in system to the deploy folder
"""
File deploy = new File(karafBase, "deploy");
String[] fileEndings = new String[] { "jar", "war", "zip", "kar", "xml" };
ProvisionOption<?>[] options = subsystem.getOptions(ProvisionOption.class);
for (ProvisionOption<?> option : options) {
try {
File target = createUnique(option.getURL(), deploy, fileEndings);
FileUtils.copyURLToFile(new URL(option.getURL()), target);
}
// CHECKSTYLE:SKIP
catch (Exception e) {
// well, this can happen...
}
}
} | java | public void copyReferencedArtifactsToDeployFolder() {
File deploy = new File(karafBase, "deploy");
String[] fileEndings = new String[] { "jar", "war", "zip", "kar", "xml" };
ProvisionOption<?>[] options = subsystem.getOptions(ProvisionOption.class);
for (ProvisionOption<?> option : options) {
try {
File target = createUnique(option.getURL(), deploy, fileEndings);
FileUtils.copyURLToFile(new URL(option.getURL()), target);
}
// CHECKSTYLE:SKIP
catch (Exception e) {
// well, this can happen...
}
}
} | [
"public",
"void",
"copyReferencedArtifactsToDeployFolder",
"(",
")",
"{",
"File",
"deploy",
"=",
"new",
"File",
"(",
"karafBase",
",",
"\"deploy\"",
")",
";",
"String",
"[",
"]",
"fileEndings",
"=",
"new",
"String",
"[",
"]",
"{",
"\"jar\"",
",",
"\"war\"",
",",
"\"zip\"",
",",
"\"kar\"",
",",
"\"xml\"",
"}",
";",
"ProvisionOption",
"<",
"?",
">",
"[",
"]",
"options",
"=",
"subsystem",
".",
"getOptions",
"(",
"ProvisionOption",
".",
"class",
")",
";",
"for",
"(",
"ProvisionOption",
"<",
"?",
">",
"option",
":",
"options",
")",
"{",
"try",
"{",
"File",
"target",
"=",
"createUnique",
"(",
"option",
".",
"getURL",
"(",
")",
",",
"deploy",
",",
"fileEndings",
")",
";",
"FileUtils",
".",
"copyURLToFile",
"(",
"new",
"URL",
"(",
"option",
".",
"getURL",
"(",
")",
")",
",",
"target",
")",
";",
"}",
"// CHECKSTYLE:SKIP",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// well, this can happen...",
"}",
"}",
"}"
] | Copy dependencies specified as ProvisionOption in system to the deploy folder | [
"Copy",
"dependencies",
"specified",
"as",
"ProvisionOption",
"in",
"system",
"to",
"the",
"deploy",
"folder"
] | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/container/internal/DependenciesDeployer.java#L76-L90 |
jmeter-maven-plugin/jmeter-maven-plugin | src/main/java/com/lazerycode/jmeter/configuration/ArtifactHelpers.java | ArtifactHelpers.artifactIsNotExcluded | public static boolean artifactIsNotExcluded(Collection<Exclusion> exclusions, Artifact artifact) {
"""
Check that an artifact is not excluded
@param exclusions Collection of exclusions
@param artifact Specific artifact to search through collection for
@return boolean
"""
return Optional.ofNullable(exclusions).orElse(Collections.emptyList())
.stream().noneMatch(selectedExclusion ->
null != artifact && selectedExclusion.getGroupId().equals(artifact.getGroupId()) &&
(selectedExclusion.getArtifactId().equals(artifact.getArtifactId()) || (selectedExclusion.getArtifactId().equals(ARTIFACT_STAR)))
);
} | java | public static boolean artifactIsNotExcluded(Collection<Exclusion> exclusions, Artifact artifact) {
return Optional.ofNullable(exclusions).orElse(Collections.emptyList())
.stream().noneMatch(selectedExclusion ->
null != artifact && selectedExclusion.getGroupId().equals(artifact.getGroupId()) &&
(selectedExclusion.getArtifactId().equals(artifact.getArtifactId()) || (selectedExclusion.getArtifactId().equals(ARTIFACT_STAR)))
);
} | [
"public",
"static",
"boolean",
"artifactIsNotExcluded",
"(",
"Collection",
"<",
"Exclusion",
">",
"exclusions",
",",
"Artifact",
"artifact",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"exclusions",
")",
".",
"orElse",
"(",
"Collections",
".",
"emptyList",
"(",
")",
")",
".",
"stream",
"(",
")",
".",
"noneMatch",
"(",
"selectedExclusion",
"->",
"null",
"!=",
"artifact",
"&&",
"selectedExclusion",
".",
"getGroupId",
"(",
")",
".",
"equals",
"(",
"artifact",
".",
"getGroupId",
"(",
")",
")",
"&&",
"(",
"selectedExclusion",
".",
"getArtifactId",
"(",
")",
".",
"equals",
"(",
"artifact",
".",
"getArtifactId",
"(",
")",
")",
"||",
"(",
"selectedExclusion",
".",
"getArtifactId",
"(",
")",
".",
"equals",
"(",
"ARTIFACT_STAR",
")",
")",
")",
")",
";",
"}"
] | Check that an artifact is not excluded
@param exclusions Collection of exclusions
@param artifact Specific artifact to search through collection for
@return boolean | [
"Check",
"that",
"an",
"artifact",
"is",
"not",
"excluded"
] | train | https://github.com/jmeter-maven-plugin/jmeter-maven-plugin/blob/63dc8b49cc6b9542deb681e25a2ada6025ddbf6b/src/main/java/com/lazerycode/jmeter/configuration/ArtifactHelpers.java#L124-L130 |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/LanguageSelector.java | LanguageSelector.onRequest | @SuppressWarnings( {
"""
Associates the event with a {@link Selection} object
using `Selection.class` as association identifier.
@param event the event
""" "PMD.DataflowAnomalyAnalysis", "PMD.EmptyCatchBlock" })
@RequestHandler(priority = 990, dynamic = true)
public void onRequest(Request.In event) {
@SuppressWarnings("PMD.AccessorClassGeneration")
final Selection selection = event.associated(Session.class)
.map(session -> (Selection) session.computeIfAbsent(
Selection.class, newKey -> new Selection(cookieName, path)))
.orElseGet(() -> new Selection(cookieName, path));
selection.setCurrentEvent(event);
event.setAssociated(Selection.class, selection);
if (selection.isExplicitlySet()) {
return;
}
// Try to get locale from cookies
final HttpRequest request = event.httpRequest();
Optional<String> localeNames = request.findValue(
HttpField.COOKIE, Converters.COOKIE_LIST)
.flatMap(cookieList -> cookieList.valueForName(cookieName));
if (localeNames.isPresent()) {
try {
List<Locale> cookieLocales = LOCALE_LIST
.fromFieldValue(localeNames.get());
if (!cookieLocales.isEmpty()) {
Collections.reverse(cookieLocales);
cookieLocales.stream()
.forEach(locale -> selection.prefer(locale));
return;
}
} catch (ParseException e) {
// Unusable
}
}
// Last resport: Accept-Language header field
Optional<List<ParameterizedValue<Locale>>> accepted = request.findValue(
HttpField.ACCEPT_LANGUAGE, Converters.LANGUAGE_LIST);
if (accepted.isPresent()) {
Locale[] locales = accepted.get().stream()
.sorted(ParameterizedValue.WEIGHT_COMPARATOR)
.map(value -> value.value()).toArray(Locale[]::new);
selection.updateFallbacks(locales);
}
} | java | @SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.EmptyCatchBlock" })
@RequestHandler(priority = 990, dynamic = true)
public void onRequest(Request.In event) {
@SuppressWarnings("PMD.AccessorClassGeneration")
final Selection selection = event.associated(Session.class)
.map(session -> (Selection) session.computeIfAbsent(
Selection.class, newKey -> new Selection(cookieName, path)))
.orElseGet(() -> new Selection(cookieName, path));
selection.setCurrentEvent(event);
event.setAssociated(Selection.class, selection);
if (selection.isExplicitlySet()) {
return;
}
// Try to get locale from cookies
final HttpRequest request = event.httpRequest();
Optional<String> localeNames = request.findValue(
HttpField.COOKIE, Converters.COOKIE_LIST)
.flatMap(cookieList -> cookieList.valueForName(cookieName));
if (localeNames.isPresent()) {
try {
List<Locale> cookieLocales = LOCALE_LIST
.fromFieldValue(localeNames.get());
if (!cookieLocales.isEmpty()) {
Collections.reverse(cookieLocales);
cookieLocales.stream()
.forEach(locale -> selection.prefer(locale));
return;
}
} catch (ParseException e) {
// Unusable
}
}
// Last resport: Accept-Language header field
Optional<List<ParameterizedValue<Locale>>> accepted = request.findValue(
HttpField.ACCEPT_LANGUAGE, Converters.LANGUAGE_LIST);
if (accepted.isPresent()) {
Locale[] locales = accepted.get().stream()
.sorted(ParameterizedValue.WEIGHT_COMPARATOR)
.map(value -> value.value()).toArray(Locale[]::new);
selection.updateFallbacks(locales);
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"PMD.DataflowAnomalyAnalysis\"",
",",
"\"PMD.EmptyCatchBlock\"",
"}",
")",
"@",
"RequestHandler",
"(",
"priority",
"=",
"990",
",",
"dynamic",
"=",
"true",
")",
"public",
"void",
"onRequest",
"(",
"Request",
".",
"In",
"event",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"PMD.AccessorClassGeneration\"",
")",
"final",
"Selection",
"selection",
"=",
"event",
".",
"associated",
"(",
"Session",
".",
"class",
")",
".",
"map",
"(",
"session",
"->",
"(",
"Selection",
")",
"session",
".",
"computeIfAbsent",
"(",
"Selection",
".",
"class",
",",
"newKey",
"->",
"new",
"Selection",
"(",
"cookieName",
",",
"path",
")",
")",
")",
".",
"orElseGet",
"(",
"(",
")",
"->",
"new",
"Selection",
"(",
"cookieName",
",",
"path",
")",
")",
";",
"selection",
".",
"setCurrentEvent",
"(",
"event",
")",
";",
"event",
".",
"setAssociated",
"(",
"Selection",
".",
"class",
",",
"selection",
")",
";",
"if",
"(",
"selection",
".",
"isExplicitlySet",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Try to get locale from cookies",
"final",
"HttpRequest",
"request",
"=",
"event",
".",
"httpRequest",
"(",
")",
";",
"Optional",
"<",
"String",
">",
"localeNames",
"=",
"request",
".",
"findValue",
"(",
"HttpField",
".",
"COOKIE",
",",
"Converters",
".",
"COOKIE_LIST",
")",
".",
"flatMap",
"(",
"cookieList",
"->",
"cookieList",
".",
"valueForName",
"(",
"cookieName",
")",
")",
";",
"if",
"(",
"localeNames",
".",
"isPresent",
"(",
")",
")",
"{",
"try",
"{",
"List",
"<",
"Locale",
">",
"cookieLocales",
"=",
"LOCALE_LIST",
".",
"fromFieldValue",
"(",
"localeNames",
".",
"get",
"(",
")",
")",
";",
"if",
"(",
"!",
"cookieLocales",
".",
"isEmpty",
"(",
")",
")",
"{",
"Collections",
".",
"reverse",
"(",
"cookieLocales",
")",
";",
"cookieLocales",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"locale",
"->",
"selection",
".",
"prefer",
"(",
"locale",
")",
")",
";",
"return",
";",
"}",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"// Unusable",
"}",
"}",
"// Last resport: Accept-Language header field",
"Optional",
"<",
"List",
"<",
"ParameterizedValue",
"<",
"Locale",
">",
">",
">",
"accepted",
"=",
"request",
".",
"findValue",
"(",
"HttpField",
".",
"ACCEPT_LANGUAGE",
",",
"Converters",
".",
"LANGUAGE_LIST",
")",
";",
"if",
"(",
"accepted",
".",
"isPresent",
"(",
")",
")",
"{",
"Locale",
"[",
"]",
"locales",
"=",
"accepted",
".",
"get",
"(",
")",
".",
"stream",
"(",
")",
".",
"sorted",
"(",
"ParameterizedValue",
".",
"WEIGHT_COMPARATOR",
")",
".",
"map",
"(",
"value",
"->",
"value",
".",
"value",
"(",
")",
")",
".",
"toArray",
"(",
"Locale",
"[",
"]",
"::",
"new",
")",
";",
"selection",
".",
"updateFallbacks",
"(",
"locales",
")",
";",
"}",
"}"
] | Associates the event with a {@link Selection} object
using `Selection.class` as association identifier.
@param event the event | [
"Associates",
"the",
"event",
"with",
"a",
"{",
"@link",
"Selection",
"}",
"object",
"using",
"Selection",
".",
"class",
"as",
"association",
"identifier",
"."
] | train | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/LanguageSelector.java#L162-L205 |
dasein-cloud/dasein-cloud-aws | src/main/java/org/dasein/cloud/aws/AWSCloud.java | AWSCloud.getV4Authorization | public String getV4Authorization( String accessKey, String secretKey, String action, String url, String serviceId, Map<String, String> headers, String bodyHash ) throws InternalException {
"""
Generates an AWS v4 signature authorization string
@param accessKey Amazon credential
@param secretKey Amazon credential
@param action the HTTP method (GET, POST, etc)
@param url the full URL for the request, including any query parameters
@param serviceId the canonical name of the service targeted in the request (e.g. "glacier")
@param headers map of headers of request. MUST include x-amz-date or date header.
@param bodyHash a hex-encoded sha256 hash of the body of the request
@return a string suitable for including as the HTTP Authorization header
@throws InternalException
"""
serviceId = serviceId.toLowerCase();
String regionId = "us-east-1"; // default for IAM
// if( ctx != null && ctx.getRegionId() != null && !ctx.getRegionId().isEmpty() &&
// !serviceId.equalsIgnoreCase(IAMMethod.SERVICE_ID) ) {
// regionId = getContext().getRegionId();
// } else {
String host = url.replaceAll("https?:\\/\\/", "");
if( host.indexOf('/') > 0 ) {
host = host.substring(0, host.indexOf('/', 1));
}
if( !IAMMethod.SERVICE_ID.equalsIgnoreCase(serviceId) ) {
String[] urlParts = host.split("\\.");
// everywhere except s3 and iam this is: service.region.amazonaws.com or service.region.amazonaws.com.cn
if( urlParts.length > 2 ) {
regionId = urlParts[1];
if (regionId.startsWith("s3-")) {
regionId = regionId.substring(3);
}
}
}
String amzDate = extractV4Date(headers);
String credentialScope = getV4CredentialScope(amzDate, regionId, serviceId);
String signedHeaders = getV4SignedHeaders(headers);
String signature = signV4(secretKey, action, url, regionId, serviceId, headers, bodyHash);
return V4_ALGORITHM + " " + "Credential=" + accessKey + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
} | java | public String getV4Authorization( String accessKey, String secretKey, String action, String url, String serviceId, Map<String, String> headers, String bodyHash ) throws InternalException {
serviceId = serviceId.toLowerCase();
String regionId = "us-east-1"; // default for IAM
// if( ctx != null && ctx.getRegionId() != null && !ctx.getRegionId().isEmpty() &&
// !serviceId.equalsIgnoreCase(IAMMethod.SERVICE_ID) ) {
// regionId = getContext().getRegionId();
// } else {
String host = url.replaceAll("https?:\\/\\/", "");
if( host.indexOf('/') > 0 ) {
host = host.substring(0, host.indexOf('/', 1));
}
if( !IAMMethod.SERVICE_ID.equalsIgnoreCase(serviceId) ) {
String[] urlParts = host.split("\\.");
// everywhere except s3 and iam this is: service.region.amazonaws.com or service.region.amazonaws.com.cn
if( urlParts.length > 2 ) {
regionId = urlParts[1];
if (regionId.startsWith("s3-")) {
regionId = regionId.substring(3);
}
}
}
String amzDate = extractV4Date(headers);
String credentialScope = getV4CredentialScope(amzDate, regionId, serviceId);
String signedHeaders = getV4SignedHeaders(headers);
String signature = signV4(secretKey, action, url, regionId, serviceId, headers, bodyHash);
return V4_ALGORITHM + " " + "Credential=" + accessKey + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
} | [
"public",
"String",
"getV4Authorization",
"(",
"String",
"accessKey",
",",
"String",
"secretKey",
",",
"String",
"action",
",",
"String",
"url",
",",
"String",
"serviceId",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
",",
"String",
"bodyHash",
")",
"throws",
"InternalException",
"{",
"serviceId",
"=",
"serviceId",
".",
"toLowerCase",
"(",
")",
";",
"String",
"regionId",
"=",
"\"us-east-1\"",
";",
"// default for IAM",
"// if( ctx != null && ctx.getRegionId() != null && !ctx.getRegionId().isEmpty() &&",
"// !serviceId.equalsIgnoreCase(IAMMethod.SERVICE_ID) ) {",
"// regionId = getContext().getRegionId();",
"// } else {",
"String",
"host",
"=",
"url",
".",
"replaceAll",
"(",
"\"https?:\\\\/\\\\/\"",
",",
"\"\"",
")",
";",
"if",
"(",
"host",
".",
"indexOf",
"(",
"'",
"'",
")",
">",
"0",
")",
"{",
"host",
"=",
"host",
".",
"substring",
"(",
"0",
",",
"host",
".",
"indexOf",
"(",
"'",
"'",
",",
"1",
")",
")",
";",
"}",
"if",
"(",
"!",
"IAMMethod",
".",
"SERVICE_ID",
".",
"equalsIgnoreCase",
"(",
"serviceId",
")",
")",
"{",
"String",
"[",
"]",
"urlParts",
"=",
"host",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"// everywhere except s3 and iam this is: service.region.amazonaws.com or service.region.amazonaws.com.cn",
"if",
"(",
"urlParts",
".",
"length",
">",
"2",
")",
"{",
"regionId",
"=",
"urlParts",
"[",
"1",
"]",
";",
"if",
"(",
"regionId",
".",
"startsWith",
"(",
"\"s3-\"",
")",
")",
"{",
"regionId",
"=",
"regionId",
".",
"substring",
"(",
"3",
")",
";",
"}",
"}",
"}",
"String",
"amzDate",
"=",
"extractV4Date",
"(",
"headers",
")",
";",
"String",
"credentialScope",
"=",
"getV4CredentialScope",
"(",
"amzDate",
",",
"regionId",
",",
"serviceId",
")",
";",
"String",
"signedHeaders",
"=",
"getV4SignedHeaders",
"(",
"headers",
")",
";",
"String",
"signature",
"=",
"signV4",
"(",
"secretKey",
",",
"action",
",",
"url",
",",
"regionId",
",",
"serviceId",
",",
"headers",
",",
"bodyHash",
")",
";",
"return",
"V4_ALGORITHM",
"+",
"\" \"",
"+",
"\"Credential=\"",
"+",
"accessKey",
"+",
"\"/\"",
"+",
"credentialScope",
"+",
"\", \"",
"+",
"\"SignedHeaders=\"",
"+",
"signedHeaders",
"+",
"\", \"",
"+",
"\"Signature=\"",
"+",
"signature",
";",
"}"
] | Generates an AWS v4 signature authorization string
@param accessKey Amazon credential
@param secretKey Amazon credential
@param action the HTTP method (GET, POST, etc)
@param url the full URL for the request, including any query parameters
@param serviceId the canonical name of the service targeted in the request (e.g. "glacier")
@param headers map of headers of request. MUST include x-amz-date or date header.
@param bodyHash a hex-encoded sha256 hash of the body of the request
@return a string suitable for including as the HTTP Authorization header
@throws InternalException | [
"Generates",
"an",
"AWS",
"v4",
"signature",
"authorization",
"string"
] | train | https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/AWSCloud.java#L1015-L1042 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d1/dfx/GeomFactory1dfx.java | GeomFactory1dfx.newPoint | @SuppressWarnings("static-method")
public Point1dfx newPoint(ObjectProperty<WeakReference<Segment1D<?, ?>>> segment, DoubleProperty x, DoubleProperty y) {
"""
Create a point with properties.
@param segment the segment property.
@param x the x property.
@param y the y property.
@return the point.
"""
return new Point1dfx(segment, x, y);
} | java | @SuppressWarnings("static-method")
public Point1dfx newPoint(ObjectProperty<WeakReference<Segment1D<?, ?>>> segment, DoubleProperty x, DoubleProperty y) {
return new Point1dfx(segment, x, y);
} | [
"@",
"SuppressWarnings",
"(",
"\"static-method\"",
")",
"public",
"Point1dfx",
"newPoint",
"(",
"ObjectProperty",
"<",
"WeakReference",
"<",
"Segment1D",
"<",
"?",
",",
"?",
">",
">",
">",
"segment",
",",
"DoubleProperty",
"x",
",",
"DoubleProperty",
"y",
")",
"{",
"return",
"new",
"Point1dfx",
"(",
"segment",
",",
"x",
",",
"y",
")",
";",
"}"
] | Create a point with properties.
@param segment the segment property.
@param x the x property.
@param y the y property.
@return the point. | [
"Create",
"a",
"point",
"with",
"properties",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d1/dfx/GeomFactory1dfx.java#L104-L107 |
alkacon/opencms-core | src/org/opencms/site/xmlsitemap/CmsXmlSitemapGenerator.java | CmsXmlSitemapGenerator.addDetailLinks | protected void addDetailLinks(CmsResource containerPage, Locale locale) throws CmsException {
"""
Adds the detail page links for a given page to the results.<p>
@param containerPage the container page resource
@param locale the locale of the container page
@throws CmsException if something goes wrong
"""
List<I_CmsResourceType> types = getDetailTypesForPage(containerPage);
for (I_CmsResourceType type : types) {
List<CmsResource> resourcesForType = getDetailResources(type);
for (CmsResource detailRes : resourcesForType) {
if (!isValidDetailPageCombination(containerPage, locale, detailRes)) {
continue;
}
List<CmsProperty> detailProps = m_guestCms.readPropertyObjects(detailRes, true);
String detailLink = getDetailLink(containerPage, detailRes, locale);
detailLink = CmsFileUtil.removeTrailingSeparator(detailLink);
CmsXmlSitemapUrlBean detailUrlBean = new CmsXmlSitemapUrlBean(
replaceServerUri(detailLink),
detailRes.getDateLastModified(),
getChangeFrequency(detailProps),
getPriority(detailProps));
detailUrlBean.setOriginalResource(detailRes);
detailUrlBean.setDetailPageResource(containerPage);
addResult(detailUrlBean, 2);
}
}
} | java | protected void addDetailLinks(CmsResource containerPage, Locale locale) throws CmsException {
List<I_CmsResourceType> types = getDetailTypesForPage(containerPage);
for (I_CmsResourceType type : types) {
List<CmsResource> resourcesForType = getDetailResources(type);
for (CmsResource detailRes : resourcesForType) {
if (!isValidDetailPageCombination(containerPage, locale, detailRes)) {
continue;
}
List<CmsProperty> detailProps = m_guestCms.readPropertyObjects(detailRes, true);
String detailLink = getDetailLink(containerPage, detailRes, locale);
detailLink = CmsFileUtil.removeTrailingSeparator(detailLink);
CmsXmlSitemapUrlBean detailUrlBean = new CmsXmlSitemapUrlBean(
replaceServerUri(detailLink),
detailRes.getDateLastModified(),
getChangeFrequency(detailProps),
getPriority(detailProps));
detailUrlBean.setOriginalResource(detailRes);
detailUrlBean.setDetailPageResource(containerPage);
addResult(detailUrlBean, 2);
}
}
} | [
"protected",
"void",
"addDetailLinks",
"(",
"CmsResource",
"containerPage",
",",
"Locale",
"locale",
")",
"throws",
"CmsException",
"{",
"List",
"<",
"I_CmsResourceType",
">",
"types",
"=",
"getDetailTypesForPage",
"(",
"containerPage",
")",
";",
"for",
"(",
"I_CmsResourceType",
"type",
":",
"types",
")",
"{",
"List",
"<",
"CmsResource",
">",
"resourcesForType",
"=",
"getDetailResources",
"(",
"type",
")",
";",
"for",
"(",
"CmsResource",
"detailRes",
":",
"resourcesForType",
")",
"{",
"if",
"(",
"!",
"isValidDetailPageCombination",
"(",
"containerPage",
",",
"locale",
",",
"detailRes",
")",
")",
"{",
"continue",
";",
"}",
"List",
"<",
"CmsProperty",
">",
"detailProps",
"=",
"m_guestCms",
".",
"readPropertyObjects",
"(",
"detailRes",
",",
"true",
")",
";",
"String",
"detailLink",
"=",
"getDetailLink",
"(",
"containerPage",
",",
"detailRes",
",",
"locale",
")",
";",
"detailLink",
"=",
"CmsFileUtil",
".",
"removeTrailingSeparator",
"(",
"detailLink",
")",
";",
"CmsXmlSitemapUrlBean",
"detailUrlBean",
"=",
"new",
"CmsXmlSitemapUrlBean",
"(",
"replaceServerUri",
"(",
"detailLink",
")",
",",
"detailRes",
".",
"getDateLastModified",
"(",
")",
",",
"getChangeFrequency",
"(",
"detailProps",
")",
",",
"getPriority",
"(",
"detailProps",
")",
")",
";",
"detailUrlBean",
".",
"setOriginalResource",
"(",
"detailRes",
")",
";",
"detailUrlBean",
".",
"setDetailPageResource",
"(",
"containerPage",
")",
";",
"addResult",
"(",
"detailUrlBean",
",",
"2",
")",
";",
"}",
"}",
"}"
] | Adds the detail page links for a given page to the results.<p>
@param containerPage the container page resource
@param locale the locale of the container page
@throws CmsException if something goes wrong | [
"Adds",
"the",
"detail",
"page",
"links",
"for",
"a",
"given",
"page",
"to",
"the",
"results",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/site/xmlsitemap/CmsXmlSitemapGenerator.java#L402-L424 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.isSub | public static boolean isSub(File parent, File sub) {
"""
判断给定的目录是否为给定文件或文件夹的父目录
@param parent 父目录
@param sub 子目录
@return 子目录是否为父目录的子目录
@since 4.5.4
"""
Assert.notNull(parent);
Assert.notNull(sub);
return sub.toPath().startsWith(parent.toPath());
} | java | public static boolean isSub(File parent, File sub) {
Assert.notNull(parent);
Assert.notNull(sub);
return sub.toPath().startsWith(parent.toPath());
} | [
"public",
"static",
"boolean",
"isSub",
"(",
"File",
"parent",
",",
"File",
"sub",
")",
"{",
"Assert",
".",
"notNull",
"(",
"parent",
")",
";",
"Assert",
".",
"notNull",
"(",
"sub",
")",
";",
"return",
"sub",
".",
"toPath",
"(",
")",
".",
"startsWith",
"(",
"parent",
".",
"toPath",
"(",
")",
")",
";",
"}"
] | 判断给定的目录是否为给定文件或文件夹的父目录
@param parent 父目录
@param sub 子目录
@return 子目录是否为父目录的子目录
@since 4.5.4 | [
"判断给定的目录是否为给定文件或文件夹的父目录"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L3431-L3435 |
Nexmo/nexmo-java | src/main/java/com/nexmo/client/verify/VerifyClient.java | VerifyClient.cancelVerification | public ControlResponse cancelVerification(String requestId) throws IOException, NexmoClientException {
"""
Cancel a current verification request.
@param requestId The requestId of the ongoing verification request.
@return A {@link ControlResponse} representing the response from the API.
@throws IOException If an IO error occurred while making the request.
@throws NexmoClientException If the request failed for some reason.
"""
return this.control.execute(new ControlRequest(requestId, VerifyControlCommand.CANCEL));
} | java | public ControlResponse cancelVerification(String requestId) throws IOException, NexmoClientException {
return this.control.execute(new ControlRequest(requestId, VerifyControlCommand.CANCEL));
} | [
"public",
"ControlResponse",
"cancelVerification",
"(",
"String",
"requestId",
")",
"throws",
"IOException",
",",
"NexmoClientException",
"{",
"return",
"this",
".",
"control",
".",
"execute",
"(",
"new",
"ControlRequest",
"(",
"requestId",
",",
"VerifyControlCommand",
".",
"CANCEL",
")",
")",
";",
"}"
] | Cancel a current verification request.
@param requestId The requestId of the ongoing verification request.
@return A {@link ControlResponse} representing the response from the API.
@throws IOException If an IO error occurred while making the request.
@throws NexmoClientException If the request failed for some reason. | [
"Cancel",
"a",
"current",
"verification",
"request",
"."
] | train | https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/verify/VerifyClient.java#L231-L233 |
segmentio/analytics-android | analytics/src/main/java/com/segment/analytics/Options.java | Options.setIntegration | public Options setIntegration(String integrationKey, boolean enabled) {
"""
Sets whether an action will be sent to the target integration.
<p>By default, all integrations are sent a payload, and the value for the {@link
#ALL_INTEGRATIONS_KEY} is {@code true}. You can disable specific payloads.
<p>Example: <code>options.setIntegration("Google Analytics", false).setIntegration("Countly",
false)</code> will send the event to ALL integrations, except Google Analytic and Countly.
<p>If you want to enable only specific integrations, first override the defaults and then
enable specific integrations.
<p>Example: <code>options.setIntegration(Options.ALL_INTEGRATIONS_KEY,
false).setIntegration("Countly", true).setIntegration("Google Analytics", true)</code> will
only send events to ONLY Countly and Google Analytics.
@param integrationKey The integration key
@param enabled <code>true</code> for enabled, <code>false</code> for disabled
@return This options object for chaining
"""
if (SegmentIntegration.SEGMENT_KEY.equals(integrationKey)) {
throw new IllegalArgumentException("Segment integration cannot be enabled or disabled.");
}
integrations.put(integrationKey, enabled);
return this;
} | java | public Options setIntegration(String integrationKey, boolean enabled) {
if (SegmentIntegration.SEGMENT_KEY.equals(integrationKey)) {
throw new IllegalArgumentException("Segment integration cannot be enabled or disabled.");
}
integrations.put(integrationKey, enabled);
return this;
} | [
"public",
"Options",
"setIntegration",
"(",
"String",
"integrationKey",
",",
"boolean",
"enabled",
")",
"{",
"if",
"(",
"SegmentIntegration",
".",
"SEGMENT_KEY",
".",
"equals",
"(",
"integrationKey",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Segment integration cannot be enabled or disabled.\"",
")",
";",
"}",
"integrations",
".",
"put",
"(",
"integrationKey",
",",
"enabled",
")",
";",
"return",
"this",
";",
"}"
] | Sets whether an action will be sent to the target integration.
<p>By default, all integrations are sent a payload, and the value for the {@link
#ALL_INTEGRATIONS_KEY} is {@code true}. You can disable specific payloads.
<p>Example: <code>options.setIntegration("Google Analytics", false).setIntegration("Countly",
false)</code> will send the event to ALL integrations, except Google Analytic and Countly.
<p>If you want to enable only specific integrations, first override the defaults and then
enable specific integrations.
<p>Example: <code>options.setIntegration(Options.ALL_INTEGRATIONS_KEY,
false).setIntegration("Countly", true).setIntegration("Google Analytics", true)</code> will
only send events to ONLY Countly and Google Analytics.
@param integrationKey The integration key
@param enabled <code>true</code> for enabled, <code>false</code> for disabled
@return This options object for chaining | [
"Sets",
"whether",
"an",
"action",
"will",
"be",
"sent",
"to",
"the",
"target",
"integration",
"."
] | train | https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/Options.java#L71-L77 |
alkacon/opencms-core | src/org/opencms/ui/apps/lists/daterestrictions/CmsDateRestrictionParser.java | CmsDateRestrictionParser.parseRange | private I_CmsListDateRestriction parseRange(CmsXmlContentValueLocation dateRestriction) {
"""
Parses a date restriction of 'range' type.<p>
@param dateRestriction the location of the date restriction
@return the date restriction or null if it could not be parsed
"""
CmsXmlContentValueLocation location = dateRestriction.getSubValue(N_RANGE);
if (location == null) {
return null;
}
CmsXmlContentValueLocation fromLoc = location.getSubValue(N_FROM);
CmsXmlContentValueLocation toLoc = location.getSubValue(N_TO);
Date fromDate = parseDate(fromLoc);
Date toDate = parseDate(toLoc);
if ((fromDate != null) || (toDate != null)) {
return new CmsListDateRangeRestriction(fromDate, toDate);
} else {
return null;
}
} | java | private I_CmsListDateRestriction parseRange(CmsXmlContentValueLocation dateRestriction) {
CmsXmlContentValueLocation location = dateRestriction.getSubValue(N_RANGE);
if (location == null) {
return null;
}
CmsXmlContentValueLocation fromLoc = location.getSubValue(N_FROM);
CmsXmlContentValueLocation toLoc = location.getSubValue(N_TO);
Date fromDate = parseDate(fromLoc);
Date toDate = parseDate(toLoc);
if ((fromDate != null) || (toDate != null)) {
return new CmsListDateRangeRestriction(fromDate, toDate);
} else {
return null;
}
} | [
"private",
"I_CmsListDateRestriction",
"parseRange",
"(",
"CmsXmlContentValueLocation",
"dateRestriction",
")",
"{",
"CmsXmlContentValueLocation",
"location",
"=",
"dateRestriction",
".",
"getSubValue",
"(",
"N_RANGE",
")",
";",
"if",
"(",
"location",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"CmsXmlContentValueLocation",
"fromLoc",
"=",
"location",
".",
"getSubValue",
"(",
"N_FROM",
")",
";",
"CmsXmlContentValueLocation",
"toLoc",
"=",
"location",
".",
"getSubValue",
"(",
"N_TO",
")",
";",
"Date",
"fromDate",
"=",
"parseDate",
"(",
"fromLoc",
")",
";",
"Date",
"toDate",
"=",
"parseDate",
"(",
"toLoc",
")",
";",
"if",
"(",
"(",
"fromDate",
"!=",
"null",
")",
"||",
"(",
"toDate",
"!=",
"null",
")",
")",
"{",
"return",
"new",
"CmsListDateRangeRestriction",
"(",
"fromDate",
",",
"toDate",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Parses a date restriction of 'range' type.<p>
@param dateRestriction the location of the date restriction
@return the date restriction or null if it could not be parsed | [
"Parses",
"a",
"date",
"restriction",
"of",
"range",
"type",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/lists/daterestrictions/CmsDateRestrictionParser.java#L222-L237 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/log/FormatterFileLog.java | FormatterFileLog.formatMessage | String formatMessage(int msgLogLevel, String tag, String msg, Throwable exception) {
"""
Format log data into a log entry String.
@param msgLogLevel Log level of an entry.
@param tag Tag with SDK and version details.
@param msg Log message.
@param exception Exception with a stach
@return Formatted log entry.
"""
if (exception != null) {
return DateHelper.getUTC(System.currentTimeMillis()) + "/" + getLevelTag(msgLogLevel) + tag + ": " + msg + "\n" + getStackTrace(exception) + "\n";
} else {
return DateHelper.getUTC(System.currentTimeMillis()) + "/" + getLevelTag(msgLogLevel) + tag + ": " + msg + "\n";
}
} | java | String formatMessage(int msgLogLevel, String tag, String msg, Throwable exception) {
if (exception != null) {
return DateHelper.getUTC(System.currentTimeMillis()) + "/" + getLevelTag(msgLogLevel) + tag + ": " + msg + "\n" + getStackTrace(exception) + "\n";
} else {
return DateHelper.getUTC(System.currentTimeMillis()) + "/" + getLevelTag(msgLogLevel) + tag + ": " + msg + "\n";
}
} | [
"String",
"formatMessage",
"(",
"int",
"msgLogLevel",
",",
"String",
"tag",
",",
"String",
"msg",
",",
"Throwable",
"exception",
")",
"{",
"if",
"(",
"exception",
"!=",
"null",
")",
"{",
"return",
"DateHelper",
".",
"getUTC",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
"+",
"\"/\"",
"+",
"getLevelTag",
"(",
"msgLogLevel",
")",
"+",
"tag",
"+",
"\": \"",
"+",
"msg",
"+",
"\"\\n\"",
"+",
"getStackTrace",
"(",
"exception",
")",
"+",
"\"\\n\"",
";",
"}",
"else",
"{",
"return",
"DateHelper",
".",
"getUTC",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
"+",
"\"/\"",
"+",
"getLevelTag",
"(",
"msgLogLevel",
")",
"+",
"tag",
"+",
"\": \"",
"+",
"msg",
"+",
"\"\\n\"",
";",
"}",
"}"
] | Format log data into a log entry String.
@param msgLogLevel Log level of an entry.
@param tag Tag with SDK and version details.
@param msg Log message.
@param exception Exception with a stach
@return Formatted log entry. | [
"Format",
"log",
"data",
"into",
"a",
"log",
"entry",
"String",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/log/FormatterFileLog.java#L42-L48 |
kaazing/java.client | amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpChannel.java | AmqpChannel.publishBasic | public AmqpChannel publishBasic(ByteBuffer body, AmqpProperties properties, String exchange, String routingKey, boolean mandatory, boolean immediate) {
"""
This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to
any active consumers when the transaction, if any, is committed.
@param body
@param headers
@param exchange
@param routingKey
@param mandatory
@param immediate
@return AmqpChannel
"""
@SuppressWarnings("unchecked")
Map<String, Object> amqpProps = (Map<String, Object>)Collections.EMPTY_MAP;
if (properties != null) {
amqpProps = properties.getProperties();
}
HashMap<String, Object> props = (HashMap<String, Object>)amqpProps;
return publishBasic(body, props, exchange, routingKey, mandatory, immediate);
} | java | public AmqpChannel publishBasic(ByteBuffer body, AmqpProperties properties, String exchange, String routingKey, boolean mandatory, boolean immediate) {
@SuppressWarnings("unchecked")
Map<String, Object> amqpProps = (Map<String, Object>)Collections.EMPTY_MAP;
if (properties != null) {
amqpProps = properties.getProperties();
}
HashMap<String, Object> props = (HashMap<String, Object>)amqpProps;
return publishBasic(body, props, exchange, routingKey, mandatory, immediate);
} | [
"public",
"AmqpChannel",
"publishBasic",
"(",
"ByteBuffer",
"body",
",",
"AmqpProperties",
"properties",
",",
"String",
"exchange",
",",
"String",
"routingKey",
",",
"boolean",
"mandatory",
",",
"boolean",
"immediate",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"String",
",",
"Object",
">",
"amqpProps",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"Collections",
".",
"EMPTY_MAP",
";",
"if",
"(",
"properties",
"!=",
"null",
")",
"{",
"amqpProps",
"=",
"properties",
".",
"getProperties",
"(",
")",
";",
"}",
"HashMap",
"<",
"String",
",",
"Object",
">",
"props",
"=",
"(",
"HashMap",
"<",
"String",
",",
"Object",
">",
")",
"amqpProps",
";",
"return",
"publishBasic",
"(",
"body",
",",
"props",
",",
"exchange",
",",
"routingKey",
",",
"mandatory",
",",
"immediate",
")",
";",
"}"
] | This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to
any active consumers when the transaction, if any, is committed.
@param body
@param headers
@param exchange
@param routingKey
@param mandatory
@param immediate
@return AmqpChannel | [
"This",
"method",
"publishes",
"a",
"message",
"to",
"a",
"specific",
"exchange",
".",
"The",
"message",
"will",
"be",
"routed",
"to",
"queues",
"as",
"defined",
"by",
"the",
"exchange",
"configuration",
"and",
"distributed",
"to",
"any",
"active",
"consumers",
"when",
"the",
"transaction",
"if",
"any",
"is",
"committed",
"."
] | train | https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpChannel.java#L834-L843 |
Wikidata/Wikidata-Toolkit | wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/StatementUpdate.java | StatementUpdate.equivalentClaims | protected boolean equivalentClaims(Claim claim1, Claim claim2) {
"""
Checks if two claims are equivalent in the sense that they have the same
main snak and the same qualifiers, but possibly in a different order.
@param claim1
@param claim2
@return true if claims are equivalent
"""
return claim1.getMainSnak().equals(claim2.getMainSnak())
&& isSameSnakSet(claim1.getAllQualifiers(),
claim2.getAllQualifiers());
} | java | protected boolean equivalentClaims(Claim claim1, Claim claim2) {
return claim1.getMainSnak().equals(claim2.getMainSnak())
&& isSameSnakSet(claim1.getAllQualifiers(),
claim2.getAllQualifiers());
} | [
"protected",
"boolean",
"equivalentClaims",
"(",
"Claim",
"claim1",
",",
"Claim",
"claim2",
")",
"{",
"return",
"claim1",
".",
"getMainSnak",
"(",
")",
".",
"equals",
"(",
"claim2",
".",
"getMainSnak",
"(",
")",
")",
"&&",
"isSameSnakSet",
"(",
"claim1",
".",
"getAllQualifiers",
"(",
")",
",",
"claim2",
".",
"getAllQualifiers",
"(",
")",
")",
";",
"}"
] | Checks if two claims are equivalent in the sense that they have the same
main snak and the same qualifiers, but possibly in a different order.
@param claim1
@param claim2
@return true if claims are equivalent | [
"Checks",
"if",
"two",
"claims",
"are",
"equivalent",
"in",
"the",
"sense",
"that",
"they",
"have",
"the",
"same",
"main",
"snak",
"and",
"the",
"same",
"qualifiers",
"but",
"possibly",
"in",
"a",
"different",
"order",
"."
] | train | https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/StatementUpdate.java#L535-L539 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRSkeletonAnimation.java | GVRSkeletonAnimation.addChannel | public void addChannel(String boneName, GVRAnimationChannel channel) {
"""
Add a channel to the animation to animate the named bone.
@param boneName name of bone to animate.
@param channel The animation channel.
"""
int boneId = mSkeleton.getBoneIndex(boneName);
if (boneId >= 0)
{
mBoneChannels[boneId] = channel;
mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);
Log.d("BONE", "Adding animation channel %d %s ", boneId, boneName);
}
} | java | public void addChannel(String boneName, GVRAnimationChannel channel)
{
int boneId = mSkeleton.getBoneIndex(boneName);
if (boneId >= 0)
{
mBoneChannels[boneId] = channel;
mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);
Log.d("BONE", "Adding animation channel %d %s ", boneId, boneName);
}
} | [
"public",
"void",
"addChannel",
"(",
"String",
"boneName",
",",
"GVRAnimationChannel",
"channel",
")",
"{",
"int",
"boneId",
"=",
"mSkeleton",
".",
"getBoneIndex",
"(",
"boneName",
")",
";",
"if",
"(",
"boneId",
">=",
"0",
")",
"{",
"mBoneChannels",
"[",
"boneId",
"]",
"=",
"channel",
";",
"mSkeleton",
".",
"setBoneOptions",
"(",
"boneId",
",",
"GVRSkeleton",
".",
"BONE_ANIMATE",
")",
";",
"Log",
".",
"d",
"(",
"\"BONE\"",
",",
"\"Adding animation channel %d %s \"",
",",
"boneId",
",",
"boneName",
")",
";",
"}",
"}"
] | Add a channel to the animation to animate the named bone.
@param boneName name of bone to animate.
@param channel The animation channel. | [
"Add",
"a",
"channel",
"to",
"the",
"animation",
"to",
"animate",
"the",
"named",
"bone",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRSkeletonAnimation.java#L105-L114 |
spring-projects/spring-social | spring-social-web/src/main/java/org/springframework/social/connect/web/ProviderSignInAttempt.java | ProviderSignInAttempt.addConnection | void addConnection(String userId, ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository connectionRepository) {
"""
Connect the new local user to the provider.
@param userId the local user ID
@param connectionFactoryLocator A {@link ConnectionFactoryLocator} used to lookup the connection
@param connectionRepository a {@link UsersConnectionRepository}
@throws DuplicateConnectionException if the user already has this connection
"""
connectionRepository.createConnectionRepository(userId).addConnection(getConnection(connectionFactoryLocator));
} | java | void addConnection(String userId, ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository connectionRepository) {
connectionRepository.createConnectionRepository(userId).addConnection(getConnection(connectionFactoryLocator));
} | [
"void",
"addConnection",
"(",
"String",
"userId",
",",
"ConnectionFactoryLocator",
"connectionFactoryLocator",
",",
"UsersConnectionRepository",
"connectionRepository",
")",
"{",
"connectionRepository",
".",
"createConnectionRepository",
"(",
"userId",
")",
".",
"addConnection",
"(",
"getConnection",
"(",
"connectionFactoryLocator",
")",
")",
";",
"}"
] | Connect the new local user to the provider.
@param userId the local user ID
@param connectionFactoryLocator A {@link ConnectionFactoryLocator} used to lookup the connection
@param connectionRepository a {@link UsersConnectionRepository}
@throws DuplicateConnectionException if the user already has this connection | [
"Connect",
"the",
"new",
"local",
"user",
"to",
"the",
"provider",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-web/src/main/java/org/springframework/social/connect/web/ProviderSignInAttempt.java#L66-L68 |
googleapis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableClusterUtilities.java | BigtableClusterUtilities.setClusterSize | private void setClusterSize(String clusterName, int newSize)
throws InterruptedException {
"""
Update a specific cluster's server node count to the number specified
"""
Preconditions.checkArgument(newSize > 0, "Cluster size must be > 0");
logger.info("Updating cluster %s to size %d", clusterName, newSize);
Operation operation = client.updateCluster(Cluster.newBuilder()
.setName(clusterName)
.setServeNodes(newSize)
.build());
waitForOperation(operation.getName(), 60);
logger.info("Done updating cluster %s.", clusterName);
} | java | private void setClusterSize(String clusterName, int newSize)
throws InterruptedException {
Preconditions.checkArgument(newSize > 0, "Cluster size must be > 0");
logger.info("Updating cluster %s to size %d", clusterName, newSize);
Operation operation = client.updateCluster(Cluster.newBuilder()
.setName(clusterName)
.setServeNodes(newSize)
.build());
waitForOperation(operation.getName(), 60);
logger.info("Done updating cluster %s.", clusterName);
} | [
"private",
"void",
"setClusterSize",
"(",
"String",
"clusterName",
",",
"int",
"newSize",
")",
"throws",
"InterruptedException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"newSize",
">",
"0",
",",
"\"Cluster size must be > 0\"",
")",
";",
"logger",
".",
"info",
"(",
"\"Updating cluster %s to size %d\"",
",",
"clusterName",
",",
"newSize",
")",
";",
"Operation",
"operation",
"=",
"client",
".",
"updateCluster",
"(",
"Cluster",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"clusterName",
")",
".",
"setServeNodes",
"(",
"newSize",
")",
".",
"build",
"(",
")",
")",
";",
"waitForOperation",
"(",
"operation",
".",
"getName",
"(",
")",
",",
"60",
")",
";",
"logger",
".",
"info",
"(",
"\"Done updating cluster %s.\"",
",",
"clusterName",
")",
";",
"}"
] | Update a specific cluster's server node count to the number specified | [
"Update",
"a",
"specific",
"cluster",
"s",
"server",
"node",
"count",
"to",
"the",
"number",
"specified"
] | train | https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableClusterUtilities.java#L220-L230 |
js-lib-com/template.xhtml | src/main/java/js/template/xhtml/XhtmlTemplate.java | XhtmlTemplate.setProperty | @Override
public void setProperty(String name, Object value) {
"""
Set template instance properties overriding the template engine ones. Current implementation deals with
<code>js.template.serialize.prolog</code> and <code>js.template.serialize.operator</code> flags.
<p>
First is used to disable prolog serialization. By default prolog serialization is enabled, see
{@link #serializeProlog}. Use this property to disable it, that to not include XML prolog, respective X(H)MTL
DOCTYPE, into serialization output.
<p>
The second property is used to control operators serialization. By default, templates operators are not included
into resulting document. If one may want to include operators, perhaps in order to enable data extraction, uses
this method. But be warned that if document is validated operators syntax may collide with document grammar and
render document invalid.
@param name property name,
@param value property value.
"""
switch(name) {
case "js.template.serialize.prolog":
serializeProlog = (Boolean)value;
break;
case "js.template.serialize.operator":
serializeOperators = (Boolean)value;
break;
}
} | java | @Override
public void setProperty(String name, Object value)
{
switch(name) {
case "js.template.serialize.prolog":
serializeProlog = (Boolean)value;
break;
case "js.template.serialize.operator":
serializeOperators = (Boolean)value;
break;
}
} | [
"@",
"Override",
"public",
"void",
"setProperty",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"switch",
"(",
"name",
")",
"{",
"case",
"\"js.template.serialize.prolog\"",
":",
"serializeProlog",
"=",
"(",
"Boolean",
")",
"value",
";",
"break",
";",
"case",
"\"js.template.serialize.operator\"",
":",
"serializeOperators",
"=",
"(",
"Boolean",
")",
"value",
";",
"break",
";",
"}",
"}"
] | Set template instance properties overriding the template engine ones. Current implementation deals with
<code>js.template.serialize.prolog</code> and <code>js.template.serialize.operator</code> flags.
<p>
First is used to disable prolog serialization. By default prolog serialization is enabled, see
{@link #serializeProlog}. Use this property to disable it, that to not include XML prolog, respective X(H)MTL
DOCTYPE, into serialization output.
<p>
The second property is used to control operators serialization. By default, templates operators are not included
into resulting document. If one may want to include operators, perhaps in order to enable data extraction, uses
this method. But be warned that if document is validated operators syntax may collide with document grammar and
render document invalid.
@param name property name,
@param value property value. | [
"Set",
"template",
"instance",
"properties",
"overriding",
"the",
"template",
"engine",
"ones",
".",
"Current",
"implementation",
"deals",
"with",
"<code",
">",
"js",
".",
"template",
".",
"serialize",
".",
"prolog<",
"/",
"code",
">",
"and",
"<code",
">",
"js",
".",
"template",
".",
"serialize",
".",
"operator<",
"/",
"code",
">",
"flags",
".",
"<p",
">",
"First",
"is",
"used",
"to",
"disable",
"prolog",
"serialization",
".",
"By",
"default",
"prolog",
"serialization",
"is",
"enabled",
"see",
"{",
"@link",
"#serializeProlog",
"}",
".",
"Use",
"this",
"property",
"to",
"disable",
"it",
"that",
"to",
"not",
"include",
"XML",
"prolog",
"respective",
"X",
"(",
"H",
")",
"MTL",
"DOCTYPE",
"into",
"serialization",
"output",
".",
"<p",
">",
"The",
"second",
"property",
"is",
"used",
"to",
"control",
"operators",
"serialization",
".",
"By",
"default",
"templates",
"operators",
"are",
"not",
"included",
"into",
"resulting",
"document",
".",
"If",
"one",
"may",
"want",
"to",
"include",
"operators",
"perhaps",
"in",
"order",
"to",
"enable",
"data",
"extraction",
"uses",
"this",
"method",
".",
"But",
"be",
"warned",
"that",
"if",
"document",
"is",
"validated",
"operators",
"syntax",
"may",
"collide",
"with",
"document",
"grammar",
"and",
"render",
"document",
"invalid",
"."
] | train | https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/XhtmlTemplate.java#L85-L97 |
bwkimmel/java-util | src/main/java/ca/eandb/util/classloader/MapClassLoaderStrategy.java | MapClassLoaderStrategy.setClassDefinition | public void setClassDefinition(String name, byte[] def) {
"""
Sets the definition of a class.
@param name The name of the class to define.
@param def The definition of the class.
"""
classDefs.put(name, ByteBuffer.wrap(def));
} | java | public void setClassDefinition(String name, byte[] def) {
classDefs.put(name, ByteBuffer.wrap(def));
} | [
"public",
"void",
"setClassDefinition",
"(",
"String",
"name",
",",
"byte",
"[",
"]",
"def",
")",
"{",
"classDefs",
".",
"put",
"(",
"name",
",",
"ByteBuffer",
".",
"wrap",
"(",
"def",
")",
")",
";",
"}"
] | Sets the definition of a class.
@param name The name of the class to define.
@param def The definition of the class. | [
"Sets",
"the",
"definition",
"of",
"a",
"class",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/classloader/MapClassLoaderStrategy.java#L70-L72 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPoliciesInner.java | ServiceEndpointPoliciesInner.beginUpdateAsync | public Observable<ServiceEndpointPolicyInner> beginUpdateAsync(String resourceGroupName, String serviceEndpointPolicyName) {
"""
Updates service Endpoint Policies.
@param resourceGroupName The name of the resource group.
@param serviceEndpointPolicyName The name of the service endpoint policy.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ServiceEndpointPolicyInner object
"""
return beginUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName).map(new Func1<ServiceResponse<ServiceEndpointPolicyInner>, ServiceEndpointPolicyInner>() {
@Override
public ServiceEndpointPolicyInner call(ServiceResponse<ServiceEndpointPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<ServiceEndpointPolicyInner> beginUpdateAsync(String resourceGroupName, String serviceEndpointPolicyName) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName).map(new Func1<ServiceResponse<ServiceEndpointPolicyInner>, ServiceEndpointPolicyInner>() {
@Override
public ServiceEndpointPolicyInner call(ServiceResponse<ServiceEndpointPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ServiceEndpointPolicyInner",
">",
"beginUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serviceEndpointPolicyName",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serviceEndpointPolicyName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ServiceEndpointPolicyInner",
">",
",",
"ServiceEndpointPolicyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ServiceEndpointPolicyInner",
"call",
"(",
"ServiceResponse",
"<",
"ServiceEndpointPolicyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Updates service Endpoint Policies.
@param resourceGroupName The name of the resource group.
@param serviceEndpointPolicyName The name of the service endpoint policy.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ServiceEndpointPolicyInner object | [
"Updates",
"service",
"Endpoint",
"Policies",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPoliciesInner.java#L779-L786 |
italiangrid/voms-api-java | src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java | DefaultVOMSTrustStore.loadCertificateFromFile | private void loadCertificateFromFile(File file) {
"""
Loads a VOMS AA certificate from a given file and stores this certificate
in the local map of trusted VOMS AA certificate.
@param file
"""
certificateFileSanityChecks(file);
try {
X509Certificate aaCert = CertificateUtils.loadCertificate(
new FileInputStream(file), Encoding.PEM);
// Get certificate subject hash, using the CANL implementation for CA
// files
String aaCertHash = getOpensslCAHash(aaCert.getSubjectX500Principal());
// Store certificate in the local map
localAACertificatesByHash.put(aaCertHash, aaCert);
synchronized (listenerLock) {
listener.notifyCertificateLoadEvent(aaCert, file);
}
} catch (IOException e) {
String errorMessage = String.format(
"Error parsing VOMS trusted certificate from %s. Reason: %s",
file.getAbsolutePath(), e.getMessage());
throw new VOMSError(errorMessage, e);
}
} | java | private void loadCertificateFromFile(File file) {
certificateFileSanityChecks(file);
try {
X509Certificate aaCert = CertificateUtils.loadCertificate(
new FileInputStream(file), Encoding.PEM);
// Get certificate subject hash, using the CANL implementation for CA
// files
String aaCertHash = getOpensslCAHash(aaCert.getSubjectX500Principal());
// Store certificate in the local map
localAACertificatesByHash.put(aaCertHash, aaCert);
synchronized (listenerLock) {
listener.notifyCertificateLoadEvent(aaCert, file);
}
} catch (IOException e) {
String errorMessage = String.format(
"Error parsing VOMS trusted certificate from %s. Reason: %s",
file.getAbsolutePath(), e.getMessage());
throw new VOMSError(errorMessage, e);
}
} | [
"private",
"void",
"loadCertificateFromFile",
"(",
"File",
"file",
")",
"{",
"certificateFileSanityChecks",
"(",
"file",
")",
";",
"try",
"{",
"X509Certificate",
"aaCert",
"=",
"CertificateUtils",
".",
"loadCertificate",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
",",
"Encoding",
".",
"PEM",
")",
";",
"// Get certificate subject hash, using the CANL implementation for CA",
"// files",
"String",
"aaCertHash",
"=",
"getOpensslCAHash",
"(",
"aaCert",
".",
"getSubjectX500Principal",
"(",
")",
")",
";",
"// Store certificate in the local map",
"localAACertificatesByHash",
".",
"put",
"(",
"aaCertHash",
",",
"aaCert",
")",
";",
"synchronized",
"(",
"listenerLock",
")",
"{",
"listener",
".",
"notifyCertificateLoadEvent",
"(",
"aaCert",
",",
"file",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"String",
"errorMessage",
"=",
"String",
".",
"format",
"(",
"\"Error parsing VOMS trusted certificate from %s. Reason: %s\"",
",",
"file",
".",
"getAbsolutePath",
"(",
")",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"VOMSError",
"(",
"errorMessage",
",",
"e",
")",
";",
"}",
"}"
] | Loads a VOMS AA certificate from a given file and stores this certificate
in the local map of trusted VOMS AA certificate.
@param file | [
"Loads",
"a",
"VOMS",
"AA",
"certificate",
"from",
"a",
"given",
"file",
"and",
"stores",
"this",
"certificate",
"in",
"the",
"local",
"map",
"of",
"trusted",
"VOMS",
"AA",
"certificate",
"."
] | train | https://github.com/italiangrid/voms-api-java/blob/b33d6cf98ca9449bed87b1cc307d411514589deb/src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java#L247-L274 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/source/workunit/MultiWorkUnitWeightedQueue.java | MultiWorkUnitWeightedQueue.addWorkUnit | public void addWorkUnit(WorkUnit workUnit, long weight) {
"""
Adds a {@link WorkUnit} to this queue, along with an associated weight for that WorkUnit.
"""
WeightedMultiWorkUnit weightMultiWorkUnit;
if (this.numMultiWorkUnits < this.maxMultiWorkUnits) {
weightMultiWorkUnit = new WeightedMultiWorkUnit();
this.numMultiWorkUnits++;
} else {
weightMultiWorkUnit = this.weightedWorkUnitQueue.poll();
}
weightMultiWorkUnit.addWorkUnit(weight, workUnit);
this.weightedWorkUnitQueue.offer(weightMultiWorkUnit);
} | java | public void addWorkUnit(WorkUnit workUnit, long weight) {
WeightedMultiWorkUnit weightMultiWorkUnit;
if (this.numMultiWorkUnits < this.maxMultiWorkUnits) {
weightMultiWorkUnit = new WeightedMultiWorkUnit();
this.numMultiWorkUnits++;
} else {
weightMultiWorkUnit = this.weightedWorkUnitQueue.poll();
}
weightMultiWorkUnit.addWorkUnit(weight, workUnit);
this.weightedWorkUnitQueue.offer(weightMultiWorkUnit);
} | [
"public",
"void",
"addWorkUnit",
"(",
"WorkUnit",
"workUnit",
",",
"long",
"weight",
")",
"{",
"WeightedMultiWorkUnit",
"weightMultiWorkUnit",
";",
"if",
"(",
"this",
".",
"numMultiWorkUnits",
"<",
"this",
".",
"maxMultiWorkUnits",
")",
"{",
"weightMultiWorkUnit",
"=",
"new",
"WeightedMultiWorkUnit",
"(",
")",
";",
"this",
".",
"numMultiWorkUnits",
"++",
";",
"}",
"else",
"{",
"weightMultiWorkUnit",
"=",
"this",
".",
"weightedWorkUnitQueue",
".",
"poll",
"(",
")",
";",
"}",
"weightMultiWorkUnit",
".",
"addWorkUnit",
"(",
"weight",
",",
"workUnit",
")",
";",
"this",
".",
"weightedWorkUnitQueue",
".",
"offer",
"(",
"weightMultiWorkUnit",
")",
";",
"}"
] | Adds a {@link WorkUnit} to this queue, along with an associated weight for that WorkUnit. | [
"Adds",
"a",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/workunit/MultiWorkUnitWeightedQueue.java#L65-L81 |
ManfredTremmel/gwt-bean-validators | mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java | PhoneNumberUtil.formatE123National | public final String formatE123National(final String pphoneNumber, final String pcountryCode) {
"""
format phone number in E123 national format.
@param pphoneNumber phone number to format
@param pcountryCode iso code of country
@return formated phone number as String
"""
return this.formatE123National(this.parsePhoneNumber(pphoneNumber, pcountryCode));
} | java | public final String formatE123National(final String pphoneNumber, final String pcountryCode) {
return this.formatE123National(this.parsePhoneNumber(pphoneNumber, pcountryCode));
} | [
"public",
"final",
"String",
"formatE123National",
"(",
"final",
"String",
"pphoneNumber",
",",
"final",
"String",
"pcountryCode",
")",
"{",
"return",
"this",
".",
"formatE123National",
"(",
"this",
".",
"parsePhoneNumber",
"(",
"pphoneNumber",
",",
"pcountryCode",
")",
")",
";",
"}"
] | format phone number in E123 national format.
@param pphoneNumber phone number to format
@param pcountryCode iso code of country
@return formated phone number as String | [
"format",
"phone",
"number",
"in",
"E123",
"national",
"format",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java#L604-L606 |
drinkjava2/jDialects | core/src/main/java/com/github/drinkjava2/jdialects/springsrc/utils/ReflectionUtils.java | ReflectionUtils.doWithLocalFields | public static void doWithLocalFields(Class<?> clazz, FieldCallback fc) {
"""
Invoke the given callback on all fields in the target class, going up the
class hierarchy to get all declared fields.
@param clazz the target class to analyze
@param fc the callback to invoke for each field
@since 4.2
@see #doWithFields
"""
for (Field field : getDeclaredFields(clazz)) {
try {
fc.doWith(field);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
}
}
} | java | public static void doWithLocalFields(Class<?> clazz, FieldCallback fc) {
for (Field field : getDeclaredFields(clazz)) {
try {
fc.doWith(field);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
}
}
} | [
"public",
"static",
"void",
"doWithLocalFields",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"FieldCallback",
"fc",
")",
"{",
"for",
"(",
"Field",
"field",
":",
"getDeclaredFields",
"(",
"clazz",
")",
")",
"{",
"try",
"{",
"fc",
".",
"doWith",
"(",
"field",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"ex",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Not allowed to access field '\"",
"+",
"field",
".",
"getName",
"(",
")",
"+",
"\"': \"",
"+",
"ex",
")",
";",
"}",
"}",
"}"
] | Invoke the given callback on all fields in the target class, going up the
class hierarchy to get all declared fields.
@param clazz the target class to analyze
@param fc the callback to invoke for each field
@since 4.2
@see #doWithFields | [
"Invoke",
"the",
"given",
"callback",
"on",
"all",
"fields",
"in",
"the",
"target",
"class",
"going",
"up",
"the",
"class",
"hierarchy",
"to",
"get",
"all",
"declared",
"fields",
"."
] | train | https://github.com/drinkjava2/jDialects/blob/1c165f09c6042a599b681c279024abcc1b848b88/core/src/main/java/com/github/drinkjava2/jdialects/springsrc/utils/ReflectionUtils.java#L656-L665 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java | DefaultDatastoreWriter.updateWithOptimisticLock | public <E> List<E> updateWithOptimisticLock(List<E> entities) {
"""
Updates the given list of entities using optimistic locking feature, if the entities are set up
to support optimistic locking. Otherwise, a normal update is performed.
@param entities
the entities to update
@return the updated entities
"""
if (entities == null || entities.isEmpty()) {
return new ArrayList<>();
}
Class<?> entityClass = entities.get(0).getClass();
PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entityClass);
if (versionMetadata == null) {
return update(entities);
} else {
return updateWithOptimisticLockInternal(entities, versionMetadata);
}
} | java | public <E> List<E> updateWithOptimisticLock(List<E> entities) {
if (entities == null || entities.isEmpty()) {
return new ArrayList<>();
}
Class<?> entityClass = entities.get(0).getClass();
PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entityClass);
if (versionMetadata == null) {
return update(entities);
} else {
return updateWithOptimisticLockInternal(entities, versionMetadata);
}
} | [
"public",
"<",
"E",
">",
"List",
"<",
"E",
">",
"updateWithOptimisticLock",
"(",
"List",
"<",
"E",
">",
"entities",
")",
"{",
"if",
"(",
"entities",
"==",
"null",
"||",
"entities",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"Class",
"<",
"?",
">",
"entityClass",
"=",
"entities",
".",
"get",
"(",
"0",
")",
".",
"getClass",
"(",
")",
";",
"PropertyMetadata",
"versionMetadata",
"=",
"EntityIntrospector",
".",
"getVersionMetadata",
"(",
"entityClass",
")",
";",
"if",
"(",
"versionMetadata",
"==",
"null",
")",
"{",
"return",
"update",
"(",
"entities",
")",
";",
"}",
"else",
"{",
"return",
"updateWithOptimisticLockInternal",
"(",
"entities",
",",
"versionMetadata",
")",
";",
"}",
"}"
] | Updates the given list of entities using optimistic locking feature, if the entities are set up
to support optimistic locking. Otherwise, a normal update is performed.
@param entities
the entities to update
@return the updated entities | [
"Updates",
"the",
"given",
"list",
"of",
"entities",
"using",
"optimistic",
"locking",
"feature",
"if",
"the",
"entities",
"are",
"set",
"up",
"to",
"support",
"optimistic",
"locking",
".",
"Otherwise",
"a",
"normal",
"update",
"is",
"performed",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java#L235-L246 |
fuzzylite/jfuzzylite | jfuzzylite/src/main/java/com/fuzzylite/imex/Exporter.java | Exporter.toFile | public void toFile(File file, Engine engine) throws IOException {
"""
Stores the string representation of the engine into the specified file
@param file is the file to export the engine to
@param engine is the engine to export
@throws IOException if any problem occurs upon creation or writing to the
file
"""
if (!file.createNewFile()) {
FuzzyLite.logger().log(Level.FINE, "Replacing file: {0}", file.getAbsolutePath());
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), FuzzyLite.UTF_8));
try {
writer.write(toString(engine));
} catch (IOException ex) {
throw ex;
} finally {
writer.close();
}
} | java | public void toFile(File file, Engine engine) throws IOException {
if (!file.createNewFile()) {
FuzzyLite.logger().log(Level.FINE, "Replacing file: {0}", file.getAbsolutePath());
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), FuzzyLite.UTF_8));
try {
writer.write(toString(engine));
} catch (IOException ex) {
throw ex;
} finally {
writer.close();
}
} | [
"public",
"void",
"toFile",
"(",
"File",
"file",
",",
"Engine",
"engine",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"file",
".",
"createNewFile",
"(",
")",
")",
"{",
"FuzzyLite",
".",
"logger",
"(",
")",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Replacing file: {0}\"",
",",
"file",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
",",
"FuzzyLite",
".",
"UTF_8",
")",
")",
";",
"try",
"{",
"writer",
".",
"write",
"(",
"toString",
"(",
"engine",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"ex",
";",
"}",
"finally",
"{",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Stores the string representation of the engine into the specified file
@param file is the file to export the engine to
@param engine is the engine to export
@throws IOException if any problem occurs upon creation or writing to the
file | [
"Stores",
"the",
"string",
"representation",
"of",
"the",
"engine",
"into",
"the",
"specified",
"file"
] | train | https://github.com/fuzzylite/jfuzzylite/blob/583ac1928f39512af75de80d560e67448039595a/jfuzzylite/src/main/java/com/fuzzylite/imex/Exporter.java#L58-L71 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/quadtree/QuadTree.java | QuadTree.subDivide | public void subDivide() {
"""
Create four children
which fully divide this cell
into four quads of equal area
"""
northWest = new QuadTree(this, data, new Cell(boundary.getX() - .5 * boundary.getHw(),
boundary.getY() - .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
northEast = new QuadTree(this, data, new Cell(boundary.getX() + .5 * boundary.getHw(),
boundary.getY() - .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
southWest = new QuadTree(this, data, new Cell(boundary.getX() - .5 * boundary.getHw(),
boundary.getY() + .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
southEast = new QuadTree(this, data, new Cell(boundary.getX() + .5 * boundary.getHw(),
boundary.getY() + .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
} | java | public void subDivide() {
northWest = new QuadTree(this, data, new Cell(boundary.getX() - .5 * boundary.getHw(),
boundary.getY() - .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
northEast = new QuadTree(this, data, new Cell(boundary.getX() + .5 * boundary.getHw(),
boundary.getY() - .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
southWest = new QuadTree(this, data, new Cell(boundary.getX() - .5 * boundary.getHw(),
boundary.getY() + .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
southEast = new QuadTree(this, data, new Cell(boundary.getX() + .5 * boundary.getHw(),
boundary.getY() + .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
} | [
"public",
"void",
"subDivide",
"(",
")",
"{",
"northWest",
"=",
"new",
"QuadTree",
"(",
"this",
",",
"data",
",",
"new",
"Cell",
"(",
"boundary",
".",
"getX",
"(",
")",
"-",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
"boundary",
".",
"getY",
"(",
")",
"-",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
")",
")",
";",
"northEast",
"=",
"new",
"QuadTree",
"(",
"this",
",",
"data",
",",
"new",
"Cell",
"(",
"boundary",
".",
"getX",
"(",
")",
"+",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
"boundary",
".",
"getY",
"(",
")",
"-",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
")",
")",
";",
"southWest",
"=",
"new",
"QuadTree",
"(",
"this",
",",
"data",
",",
"new",
"Cell",
"(",
"boundary",
".",
"getX",
"(",
")",
"-",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
"boundary",
".",
"getY",
"(",
")",
"+",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
")",
")",
";",
"southEast",
"=",
"new",
"QuadTree",
"(",
"this",
",",
"data",
",",
"new",
"Cell",
"(",
"boundary",
".",
"getX",
"(",
")",
"+",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
"boundary",
".",
"getY",
"(",
")",
"+",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHw",
"(",
")",
",",
".5",
"*",
"boundary",
".",
"getHh",
"(",
")",
")",
")",
";",
"}"
] | Create four children
which fully divide this cell
into four quads of equal area | [
"Create",
"four",
"children",
"which",
"fully",
"divide",
"this",
"cell",
"into",
"four",
"quads",
"of",
"equal",
"area"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/quadtree/QuadTree.java#L216-L226 |
BlueBrain/bluima | modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/sentdetect/SDContextGenerator.java | SDContextGenerator.previousSpaceIndex | private static final int previousSpaceIndex(StringBuffer sb, int seek) {
"""
Finds the index of the nearest space before a specified index.
@param sb The string buffer which contains the text being examined.
@param seek The index to begin searching from.
@return The index which contains the nearest space.
"""
seek--;
while (seek > 0) {
if (sb.charAt(seek) == ' ') {
while (seek > 0 && sb.charAt(seek - 1) == ' ')
seek--;
return seek;
}
seek--;
}
return 0;
} | java | private static final int previousSpaceIndex(StringBuffer sb, int seek) {
seek--;
while (seek > 0) {
if (sb.charAt(seek) == ' ') {
while (seek > 0 && sb.charAt(seek - 1) == ' ')
seek--;
return seek;
}
seek--;
}
return 0;
} | [
"private",
"static",
"final",
"int",
"previousSpaceIndex",
"(",
"StringBuffer",
"sb",
",",
"int",
"seek",
")",
"{",
"seek",
"--",
";",
"while",
"(",
"seek",
">",
"0",
")",
"{",
"if",
"(",
"sb",
".",
"charAt",
"(",
"seek",
")",
"==",
"'",
"'",
")",
"{",
"while",
"(",
"seek",
">",
"0",
"&&",
"sb",
".",
"charAt",
"(",
"seek",
"-",
"1",
")",
"==",
"'",
"'",
")",
"seek",
"--",
";",
"return",
"seek",
";",
"}",
"seek",
"--",
";",
"}",
"return",
"0",
";",
"}"
] | Finds the index of the nearest space before a specified index.
@param sb The string buffer which contains the text being examined.
@param seek The index to begin searching from.
@return The index which contains the nearest space. | [
"Finds",
"the",
"index",
"of",
"the",
"nearest",
"space",
"before",
"a",
"specified",
"index",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/sentdetect/SDContextGenerator.java#L219-L230 |
square/wire | wire-schema/src/main/java/com/squareup/wire/schema/Options.java | Options.optionMatches | public boolean optionMatches(String namePattern, String valuePattern) {
"""
Returns true if any of the options in {@code options} matches both of the regular expressions
provided: its name matches the option's name and its value matches the option's value.
"""
Matcher nameMatcher = Pattern.compile(namePattern).matcher("");
Matcher valueMatcher = Pattern.compile(valuePattern).matcher("");
for (Map.Entry<ProtoMember, Object> entry : map.entrySet()) {
if (nameMatcher.reset(entry.getKey().member()).matches()
&& valueMatcher.reset(String.valueOf(entry.getValue())).matches()) {
return true;
}
}
return false;
} | java | public boolean optionMatches(String namePattern, String valuePattern) {
Matcher nameMatcher = Pattern.compile(namePattern).matcher("");
Matcher valueMatcher = Pattern.compile(valuePattern).matcher("");
for (Map.Entry<ProtoMember, Object> entry : map.entrySet()) {
if (nameMatcher.reset(entry.getKey().member()).matches()
&& valueMatcher.reset(String.valueOf(entry.getValue())).matches()) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"optionMatches",
"(",
"String",
"namePattern",
",",
"String",
"valuePattern",
")",
"{",
"Matcher",
"nameMatcher",
"=",
"Pattern",
".",
"compile",
"(",
"namePattern",
")",
".",
"matcher",
"(",
"\"\"",
")",
";",
"Matcher",
"valueMatcher",
"=",
"Pattern",
".",
"compile",
"(",
"valuePattern",
")",
".",
"matcher",
"(",
"\"\"",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"ProtoMember",
",",
"Object",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"nameMatcher",
".",
"reset",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"member",
"(",
")",
")",
".",
"matches",
"(",
")",
"&&",
"valueMatcher",
".",
"reset",
"(",
"String",
".",
"valueOf",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
".",
"matches",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if any of the options in {@code options} matches both of the regular expressions
provided: its name matches the option's name and its value matches the option's value. | [
"Returns",
"true",
"if",
"any",
"of",
"the",
"options",
"in",
"{"
] | train | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/Options.java#L78-L88 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/checker/AbstractInconsistencyRepair.java | AbstractInconsistencyRepair.getIdentifier | protected String getIdentifier(ResultSet resultSet, String column) throws SQLException {
"""
Returns internal identifier (container name plus identifier) of item placed
in {@link ResultSet}.
"""
String containerName = "";
try
{
containerName = resultSet.getString(DBConstants.CONTAINER_NAME);
}
catch (SQLException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("Can't get container name: " + e.getMessage());
}
}
return resultSet.getString(column).substring(containerName.length());
} | java | protected String getIdentifier(ResultSet resultSet, String column) throws SQLException
{
String containerName = "";
try
{
containerName = resultSet.getString(DBConstants.CONTAINER_NAME);
}
catch (SQLException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("Can't get container name: " + e.getMessage());
}
}
return resultSet.getString(column).substring(containerName.length());
} | [
"protected",
"String",
"getIdentifier",
"(",
"ResultSet",
"resultSet",
",",
"String",
"column",
")",
"throws",
"SQLException",
"{",
"String",
"containerName",
"=",
"\"\"",
";",
"try",
"{",
"containerName",
"=",
"resultSet",
".",
"getString",
"(",
"DBConstants",
".",
"CONTAINER_NAME",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"if",
"(",
"LOG",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Can't get container name: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"return",
"resultSet",
".",
"getString",
"(",
"column",
")",
".",
"substring",
"(",
"containerName",
".",
"length",
"(",
")",
")",
";",
"}"
] | Returns internal identifier (container name plus identifier) of item placed
in {@link ResultSet}. | [
"Returns",
"internal",
"identifier",
"(",
"container",
"name",
"plus",
"identifier",
")",
"of",
"item",
"placed",
"in",
"{"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/checker/AbstractInconsistencyRepair.java#L117-L133 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.j2ee.mbeans/src/com/ibm/ws/messaging/jms/j2ee/mbeans/JmsMBeanHelper.java | JmsMBeanHelper.getMBeanObject | static ObjectName getMBeanObject(String serverName, String jmsResourceName) {
"""
Constructs Objectname as per JSR 77 spec i.e
"WebSphere:j2eeType=JMSResource,J2EEServer=serverName,name=JmsResourceName"
for JMSResource parent-type is mandatory and it is J2EEServer.
@param serverName
@param jmsResourceName
@param jmsResourceType
@return
"""
ObjectName jmsMBeanObjectName = null;
Hashtable<String, String> properties = new Hashtable<String, String>();
//construct JMSProvider MBean object name.
properties.put(KEY_J2EETYPE, KEY_JMSRESOURCE);
//as per JSR 77 spec,J2EEServer(i.e server name) is parent for JMSResource.
properties.put(KEY_JMS_PARENT, serverName);
//actual JMSResource name
properties.put(KEY_NAME, jmsResourceName);
try {
jmsMBeanObjectName = new ObjectName(DOMAIN_NAME, properties);
} catch (MalformedObjectNameException e) {
// ignore exceptions - This will never happen
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "getMBeanObject", e);
}
return jmsMBeanObjectName;
} | java | static ObjectName getMBeanObject(String serverName, String jmsResourceName) {
ObjectName jmsMBeanObjectName = null;
Hashtable<String, String> properties = new Hashtable<String, String>();
//construct JMSProvider MBean object name.
properties.put(KEY_J2EETYPE, KEY_JMSRESOURCE);
//as per JSR 77 spec,J2EEServer(i.e server name) is parent for JMSResource.
properties.put(KEY_JMS_PARENT, serverName);
//actual JMSResource name
properties.put(KEY_NAME, jmsResourceName);
try {
jmsMBeanObjectName = new ObjectName(DOMAIN_NAME, properties);
} catch (MalformedObjectNameException e) {
// ignore exceptions - This will never happen
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "getMBeanObject", e);
}
return jmsMBeanObjectName;
} | [
"static",
"ObjectName",
"getMBeanObject",
"(",
"String",
"serverName",
",",
"String",
"jmsResourceName",
")",
"{",
"ObjectName",
"jmsMBeanObjectName",
"=",
"null",
";",
"Hashtable",
"<",
"String",
",",
"String",
">",
"properties",
"=",
"new",
"Hashtable",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"//construct JMSProvider MBean object name.",
"properties",
".",
"put",
"(",
"KEY_J2EETYPE",
",",
"KEY_JMSRESOURCE",
")",
";",
"//as per JSR 77 spec,J2EEServer(i.e server name) is parent for JMSResource.",
"properties",
".",
"put",
"(",
"KEY_JMS_PARENT",
",",
"serverName",
")",
";",
"//actual JMSResource name",
"properties",
".",
"put",
"(",
"KEY_NAME",
",",
"jmsResourceName",
")",
";",
"try",
"{",
"jmsMBeanObjectName",
"=",
"new",
"ObjectName",
"(",
"DOMAIN_NAME",
",",
"properties",
")",
";",
"}",
"catch",
"(",
"MalformedObjectNameException",
"e",
")",
"{",
"// ignore exceptions - This will never happen",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"getMBeanObject\"",
",",
"e",
")",
";",
"}",
"return",
"jmsMBeanObjectName",
";",
"}"
] | Constructs Objectname as per JSR 77 spec i.e
"WebSphere:j2eeType=JMSResource,J2EEServer=serverName,name=JmsResourceName"
for JMSResource parent-type is mandatory and it is J2EEServer.
@param serverName
@param jmsResourceName
@param jmsResourceType
@return | [
"Constructs",
"Objectname",
"as",
"per",
"JSR",
"77",
"spec",
"i",
".",
"e",
"WebSphere",
":",
"j2eeType",
"=",
"JMSResource",
"J2EEServer",
"=",
"serverName",
"name",
"=",
"JmsResourceName",
"for",
"JMSResource",
"parent",
"-",
"type",
"is",
"mandatory",
"and",
"it",
"is",
"J2EEServer",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.j2ee.mbeans/src/com/ibm/ws/messaging/jms/j2ee/mbeans/JmsMBeanHelper.java#L46-L69 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java | FilesImpl.listFromComputeNode | public PagedList<NodeFile> listFromComputeNode(final String poolId, final String nodeId) {
"""
Lists all of the files in task directories on the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node whose files you want to list.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PagedList<NodeFile> object if successful.
"""
ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders> response = listFromComputeNodeSinglePageAsync(poolId, nodeId).toBlocking().single();
return new PagedList<NodeFile>(response.body()) {
@Override
public Page<NodeFile> nextPage(String nextPageLink) {
return listFromComputeNodeNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | java | public PagedList<NodeFile> listFromComputeNode(final String poolId, final String nodeId) {
ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders> response = listFromComputeNodeSinglePageAsync(poolId, nodeId).toBlocking().single();
return new PagedList<NodeFile>(response.body()) {
@Override
public Page<NodeFile> nextPage(String nextPageLink) {
return listFromComputeNodeNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | [
"public",
"PagedList",
"<",
"NodeFile",
">",
"listFromComputeNode",
"(",
"final",
"String",
"poolId",
",",
"final",
"String",
"nodeId",
")",
"{",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"NodeFile",
">",
",",
"FileListFromComputeNodeHeaders",
">",
"response",
"=",
"listFromComputeNodeSinglePageAsync",
"(",
"poolId",
",",
"nodeId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
";",
"return",
"new",
"PagedList",
"<",
"NodeFile",
">",
"(",
"response",
".",
"body",
"(",
")",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"NodeFile",
">",
"nextPage",
"(",
"String",
"nextPageLink",
")",
"{",
"return",
"listFromComputeNodeNextSinglePageAsync",
"(",
"nextPageLink",
",",
"null",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}",
"}",
";",
"}"
] | Lists all of the files in task directories on the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node whose files you want to list.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PagedList<NodeFile> object if successful. | [
"Lists",
"all",
"of",
"the",
"files",
"in",
"task",
"directories",
"on",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java#L1918-L1926 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/HealthCheckClient.java | HealthCheckClient.insertHealthCheck | @BetaApi
public final Operation insertHealthCheck(ProjectName project, HealthCheck healthCheckResource) {
"""
Creates a HealthCheck resource in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (HealthCheckClient healthCheckClient = HealthCheckClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
HealthCheck healthCheckResource = HealthCheck.newBuilder().build();
Operation response = healthCheckClient.insertHealthCheck(project, healthCheckResource);
}
</code></pre>
@param project Project ID for this request.
@param healthCheckResource An HealthCheck resource. This resource defines a template for how
individual virtual machines should be checked for health, via one of the supported
protocols.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
InsertHealthCheckHttpRequest request =
InsertHealthCheckHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setHealthCheckResource(healthCheckResource)
.build();
return insertHealthCheck(request);
} | java | @BetaApi
public final Operation insertHealthCheck(ProjectName project, HealthCheck healthCheckResource) {
InsertHealthCheckHttpRequest request =
InsertHealthCheckHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setHealthCheckResource(healthCheckResource)
.build();
return insertHealthCheck(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertHealthCheck",
"(",
"ProjectName",
"project",
",",
"HealthCheck",
"healthCheckResource",
")",
"{",
"InsertHealthCheckHttpRequest",
"request",
"=",
"InsertHealthCheckHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setProject",
"(",
"project",
"==",
"null",
"?",
"null",
":",
"project",
".",
"toString",
"(",
")",
")",
".",
"setHealthCheckResource",
"(",
"healthCheckResource",
")",
".",
"build",
"(",
")",
";",
"return",
"insertHealthCheck",
"(",
"request",
")",
";",
"}"
] | Creates a HealthCheck resource in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (HealthCheckClient healthCheckClient = HealthCheckClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
HealthCheck healthCheckResource = HealthCheck.newBuilder().build();
Operation response = healthCheckClient.insertHealthCheck(project, healthCheckResource);
}
</code></pre>
@param project Project ID for this request.
@param healthCheckResource An HealthCheck resource. This resource defines a template for how
individual virtual machines should be checked for health, via one of the supported
protocols.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"HealthCheck",
"resource",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/HealthCheckClient.java#L373-L382 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/RegExUtils.java | RegExUtils.replaceFirst | public static String replaceFirst(final String text, final String regex, final String replacement) {
"""
<p>Replaces the first substring of the text string that matches the given regular expression
with the given replacement.</p>
This method is a {@code null} safe equivalent to:
<ul>
<li>{@code text.replaceFirst(regex, replacement)}</li>
<li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<p>The {@link Pattern#DOTALL} option is NOT automatically added.
To use the DOTALL option prepend <code>"(?s)"</code> to the regex.
DOTALL is also known as single-line mode in Perl.</p>
<pre>
StringUtils.replaceFirst(null, *, *) = null
StringUtils.replaceFirst("any", (String) null, *) = "any"
StringUtils.replaceFirst("any", *, null) = "any"
StringUtils.replaceFirst("", "", "zzz") = "zzz"
StringUtils.replaceFirst("", ".*", "zzz") = "zzz"
StringUtils.replaceFirst("", ".+", "zzz") = ""
StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc"
StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z") = "z\n<__>"
StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z") = "z"
StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123"
StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc"
StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc"
StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit"
</pre>
@param text text to search and replace in, may be null
@param regex the regular expression to which this string is to be matched
@param replacement the string to be substituted for the first match
@return the text with the first replacement processed,
{@code null} if null String input
@throws java.util.regex.PatternSyntaxException
if the regular expression's syntax is invalid
@see String#replaceFirst(String, String)
@see java.util.regex.Pattern
@see java.util.regex.Pattern#DOTALL
"""
if (text == null || regex == null|| replacement == null ) {
return text;
}
return text.replaceFirst(regex, replacement);
} | java | public static String replaceFirst(final String text, final String regex, final String replacement) {
if (text == null || regex == null|| replacement == null ) {
return text;
}
return text.replaceFirst(regex, replacement);
} | [
"public",
"static",
"String",
"replaceFirst",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"regex",
",",
"final",
"String",
"replacement",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"regex",
"==",
"null",
"||",
"replacement",
"==",
"null",
")",
"{",
"return",
"text",
";",
"}",
"return",
"text",
".",
"replaceFirst",
"(",
"regex",
",",
"replacement",
")",
";",
"}"
] | <p>Replaces the first substring of the text string that matches the given regular expression
with the given replacement.</p>
This method is a {@code null} safe equivalent to:
<ul>
<li>{@code text.replaceFirst(regex, replacement)}</li>
<li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<p>The {@link Pattern#DOTALL} option is NOT automatically added.
To use the DOTALL option prepend <code>"(?s)"</code> to the regex.
DOTALL is also known as single-line mode in Perl.</p>
<pre>
StringUtils.replaceFirst(null, *, *) = null
StringUtils.replaceFirst("any", (String) null, *) = "any"
StringUtils.replaceFirst("any", *, null) = "any"
StringUtils.replaceFirst("", "", "zzz") = "zzz"
StringUtils.replaceFirst("", ".*", "zzz") = "zzz"
StringUtils.replaceFirst("", ".+", "zzz") = ""
StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc"
StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z") = "z\n<__>"
StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z") = "z"
StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123"
StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc"
StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc"
StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit"
</pre>
@param text text to search and replace in, may be null
@param regex the regular expression to which this string is to be matched
@param replacement the string to be substituted for the first match
@return the text with the first replacement processed,
{@code null} if null String input
@throws java.util.regex.PatternSyntaxException
if the regular expression's syntax is invalid
@see String#replaceFirst(String, String)
@see java.util.regex.Pattern
@see java.util.regex.Pattern#DOTALL | [
"<p",
">",
"Replaces",
"the",
"first",
"substring",
"of",
"the",
"text",
"string",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"with",
"the",
"given",
"replacement",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L407-L412 |
hector-client/hector | core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyTemplate.java | ColumnFamilyTemplate.countColumns | public int countColumns(K key, N start, N end, int max) {
"""
Counts columns in the specified range of a standard column family
@param key
@param start
@param end
@param max
@return
"""
CountQuery<K, N> query = HFactory.createCountQuery(keyspace, keySerializer,
topSerializer);
query.setKey(key);
query.setColumnFamily(columnFamily);
query.setRange(start, end, max);
return query.execute().get();
} | java | public int countColumns(K key, N start, N end, int max) {
CountQuery<K, N> query = HFactory.createCountQuery(keyspace, keySerializer,
topSerializer);
query.setKey(key);
query.setColumnFamily(columnFamily);
query.setRange(start, end, max);
return query.execute().get();
} | [
"public",
"int",
"countColumns",
"(",
"K",
"key",
",",
"N",
"start",
",",
"N",
"end",
",",
"int",
"max",
")",
"{",
"CountQuery",
"<",
"K",
",",
"N",
">",
"query",
"=",
"HFactory",
".",
"createCountQuery",
"(",
"keyspace",
",",
"keySerializer",
",",
"topSerializer",
")",
";",
"query",
".",
"setKey",
"(",
"key",
")",
";",
"query",
".",
"setColumnFamily",
"(",
"columnFamily",
")",
";",
"query",
".",
"setRange",
"(",
"start",
",",
"end",
",",
"max",
")",
";",
"return",
"query",
".",
"execute",
"(",
")",
".",
"get",
"(",
")",
";",
"}"
] | Counts columns in the specified range of a standard column family
@param key
@param start
@param end
@param max
@return | [
"Counts",
"columns",
"in",
"the",
"specified",
"range",
"of",
"a",
"standard",
"column",
"family"
] | train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyTemplate.java#L103-L110 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/application/support/AbstractApplicationPage.java | AbstractApplicationPage.createPageComponent | protected PageComponent createPageComponent(PageComponentDescriptor descriptor) {
"""
Creates a PageComponent for the given PageComponentDescriptor.
@param descriptor
the descriptor
@return the created PageComponent
"""
PageComponent pageComponent = descriptor.createPageComponent();
pageComponent.setContext(new DefaultViewContext(this, createPageComponentPane(pageComponent)));
if (pageComponent instanceof ApplicationListener && getApplicationEventMulticaster() != null) {
getApplicationEventMulticaster().addApplicationListener((ApplicationListener) pageComponent);
}
return pageComponent;
} | java | protected PageComponent createPageComponent(PageComponentDescriptor descriptor) {
PageComponent pageComponent = descriptor.createPageComponent();
pageComponent.setContext(new DefaultViewContext(this, createPageComponentPane(pageComponent)));
if (pageComponent instanceof ApplicationListener && getApplicationEventMulticaster() != null) {
getApplicationEventMulticaster().addApplicationListener((ApplicationListener) pageComponent);
}
return pageComponent;
} | [
"protected",
"PageComponent",
"createPageComponent",
"(",
"PageComponentDescriptor",
"descriptor",
")",
"{",
"PageComponent",
"pageComponent",
"=",
"descriptor",
".",
"createPageComponent",
"(",
")",
";",
"pageComponent",
".",
"setContext",
"(",
"new",
"DefaultViewContext",
"(",
"this",
",",
"createPageComponentPane",
"(",
"pageComponent",
")",
")",
")",
";",
"if",
"(",
"pageComponent",
"instanceof",
"ApplicationListener",
"&&",
"getApplicationEventMulticaster",
"(",
")",
"!=",
"null",
")",
"{",
"getApplicationEventMulticaster",
"(",
")",
".",
"addApplicationListener",
"(",
"(",
"ApplicationListener",
")",
"pageComponent",
")",
";",
"}",
"return",
"pageComponent",
";",
"}"
] | Creates a PageComponent for the given PageComponentDescriptor.
@param descriptor
the descriptor
@return the created PageComponent | [
"Creates",
"a",
"PageComponent",
"for",
"the",
"given",
"PageComponentDescriptor",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/application/support/AbstractApplicationPage.java#L363-L371 |
UrielCh/ovh-java-sdk | ovh-java-sdk-licensedirectadmin/src/main/java/net/minidev/ovh/api/ApiOvhLicensedirectadmin.java | ApiOvhLicensedirectadmin.serviceName_changeOs_POST | public OvhTask serviceName_changeOs_POST(String serviceName, OvhDirectAdminOsEnum os) throws IOException {
"""
Change the Operating System for a license
REST: POST /license/directadmin/{serviceName}/changeOs
@param os [required] The operating system you want for this license
@param serviceName [required] The name of your DirectAdmin license
"""
String qPath = "/license/directadmin/{serviceName}/changeOs";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "os", os);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_changeOs_POST(String serviceName, OvhDirectAdminOsEnum os) throws IOException {
String qPath = "/license/directadmin/{serviceName}/changeOs";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "os", os);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_changeOs_POST",
"(",
"String",
"serviceName",
",",
"OvhDirectAdminOsEnum",
"os",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/license/directadmin/{serviceName}/changeOs\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"os\"",
",",
"os",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhTask",
".",
"class",
")",
";",
"}"
] | Change the Operating System for a license
REST: POST /license/directadmin/{serviceName}/changeOs
@param os [required] The operating system you want for this license
@param serviceName [required] The name of your DirectAdmin license | [
"Change",
"the",
"Operating",
"System",
"for",
"a",
"license"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-licensedirectadmin/src/main/java/net/minidev/ovh/api/ApiOvhLicensedirectadmin.java#L157-L164 |
hageldave/ImagingKit | ImagingKit_Fourier/src/main/java/hageldave/imagingkit/fourier/Fourier.java | Fourier.horizontalTransform | public static ComplexImg horizontalTransform(ColorImg img, int channel) {
"""
Executes row wise Fourier transforms of the specified channel of the specified {@link ColorImg}.
A 1-dimensional Fourier transform is done for each row of the image's channel.
@param img of which one channel is to be transformed
@param channel the channel which will be transformed
@return transform as ComplexImg
@throws IllegalArgumentException if the specified channel is out of range ([0..3]) or is alpha (3)
but the specified image does not have an alpha channel
"""
// sanity checks
sanityCheckForward(img, channel);
// make transforms
ComplexImg transformed = new ComplexImg(img.getDimension());
try(
NativeRealArray row = new NativeRealArray(img.getWidth());
NativeRealArray fft_r = new NativeRealArray(row.length);
NativeRealArray fft_i = new NativeRealArray(row.length);
) {
for(int y = 0; y < img.getHeight(); y++){
row.set(0, img.getWidth(), y*img.getWidth(), img.getData()[channel]);
FFTW_Guru.execute_split_r2c(row, fft_r, fft_i, img.getWidth());
fft_r.get(0, img.getWidth(), y*img.getWidth(), transformed.getDataReal());
fft_i.get(0, img.getWidth(), y*img.getWidth(), transformed.getDataImag());
}
}
return transformed;
} | java | public static ComplexImg horizontalTransform(ColorImg img, int channel) {
// sanity checks
sanityCheckForward(img, channel);
// make transforms
ComplexImg transformed = new ComplexImg(img.getDimension());
try(
NativeRealArray row = new NativeRealArray(img.getWidth());
NativeRealArray fft_r = new NativeRealArray(row.length);
NativeRealArray fft_i = new NativeRealArray(row.length);
) {
for(int y = 0; y < img.getHeight(); y++){
row.set(0, img.getWidth(), y*img.getWidth(), img.getData()[channel]);
FFTW_Guru.execute_split_r2c(row, fft_r, fft_i, img.getWidth());
fft_r.get(0, img.getWidth(), y*img.getWidth(), transformed.getDataReal());
fft_i.get(0, img.getWidth(), y*img.getWidth(), transformed.getDataImag());
}
}
return transformed;
} | [
"public",
"static",
"ComplexImg",
"horizontalTransform",
"(",
"ColorImg",
"img",
",",
"int",
"channel",
")",
"{",
"// sanity checks",
"sanityCheckForward",
"(",
"img",
",",
"channel",
")",
";",
"// make transforms",
"ComplexImg",
"transformed",
"=",
"new",
"ComplexImg",
"(",
"img",
".",
"getDimension",
"(",
")",
")",
";",
"try",
"(",
"NativeRealArray",
"row",
"=",
"new",
"NativeRealArray",
"(",
"img",
".",
"getWidth",
"(",
")",
")",
";",
"NativeRealArray",
"fft_r",
"=",
"new",
"NativeRealArray",
"(",
"row",
".",
"length",
")",
";",
"NativeRealArray",
"fft_i",
"=",
"new",
"NativeRealArray",
"(",
"row",
".",
"length",
")",
";",
")",
"{",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"img",
".",
"getHeight",
"(",
")",
";",
"y",
"++",
")",
"{",
"row",
".",
"set",
"(",
"0",
",",
"img",
".",
"getWidth",
"(",
")",
",",
"y",
"*",
"img",
".",
"getWidth",
"(",
")",
",",
"img",
".",
"getData",
"(",
")",
"[",
"channel",
"]",
")",
";",
"FFTW_Guru",
".",
"execute_split_r2c",
"(",
"row",
",",
"fft_r",
",",
"fft_i",
",",
"img",
".",
"getWidth",
"(",
")",
")",
";",
"fft_r",
".",
"get",
"(",
"0",
",",
"img",
".",
"getWidth",
"(",
")",
",",
"y",
"*",
"img",
".",
"getWidth",
"(",
")",
",",
"transformed",
".",
"getDataReal",
"(",
")",
")",
";",
"fft_i",
".",
"get",
"(",
"0",
",",
"img",
".",
"getWidth",
"(",
")",
",",
"y",
"*",
"img",
".",
"getWidth",
"(",
")",
",",
"transformed",
".",
"getDataImag",
"(",
")",
")",
";",
"}",
"}",
"return",
"transformed",
";",
"}"
] | Executes row wise Fourier transforms of the specified channel of the specified {@link ColorImg}.
A 1-dimensional Fourier transform is done for each row of the image's channel.
@param img of which one channel is to be transformed
@param channel the channel which will be transformed
@return transform as ComplexImg
@throws IllegalArgumentException if the specified channel is out of range ([0..3]) or is alpha (3)
but the specified image does not have an alpha channel | [
"Executes",
"row",
"wise",
"Fourier",
"transforms",
"of",
"the",
"specified",
"channel",
"of",
"the",
"specified",
"{",
"@link",
"ColorImg",
"}",
".",
"A",
"1",
"-",
"dimensional",
"Fourier",
"transform",
"is",
"done",
"for",
"each",
"row",
"of",
"the",
"image",
"s",
"channel",
".",
"@param",
"img",
"of",
"which",
"one",
"channel",
"is",
"to",
"be",
"transformed",
"@param",
"channel",
"the",
"channel",
"which",
"will",
"be",
"transformed",
"@return",
"transform",
"as",
"ComplexImg"
] | train | https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Fourier/src/main/java/hageldave/imagingkit/fourier/Fourier.java#L173-L191 |
mangstadt/biweekly | src/main/java/biweekly/util/Google2445Utils.java | Google2445Utils.createRecurrenceIterator | public static RecurrenceIterator createRecurrenceIterator(Recurrence recurrence, ICalDate start, TimeZone timezone) {
"""
Creates a recurrence iterator based on the given recurrence rule.
@param recurrence the recurrence rule
@param start the start date
@param timezone the timezone to iterate in. This is needed in order to
account for when the iterator passes over a daylight savings boundary.
@return the recurrence iterator
"""
DateValue startValue = convert(start, timezone);
return RecurrenceIteratorFactory.createRecurrenceIterator(recurrence, startValue, timezone);
} | java | public static RecurrenceIterator createRecurrenceIterator(Recurrence recurrence, ICalDate start, TimeZone timezone) {
DateValue startValue = convert(start, timezone);
return RecurrenceIteratorFactory.createRecurrenceIterator(recurrence, startValue, timezone);
} | [
"public",
"static",
"RecurrenceIterator",
"createRecurrenceIterator",
"(",
"Recurrence",
"recurrence",
",",
"ICalDate",
"start",
",",
"TimeZone",
"timezone",
")",
"{",
"DateValue",
"startValue",
"=",
"convert",
"(",
"start",
",",
"timezone",
")",
";",
"return",
"RecurrenceIteratorFactory",
".",
"createRecurrenceIterator",
"(",
"recurrence",
",",
"startValue",
",",
"timezone",
")",
";",
"}"
] | Creates a recurrence iterator based on the given recurrence rule.
@param recurrence the recurrence rule
@param start the start date
@param timezone the timezone to iterate in. This is needed in order to
account for when the iterator passes over a daylight savings boundary.
@return the recurrence iterator | [
"Creates",
"a",
"recurrence",
"iterator",
"based",
"on",
"the",
"given",
"recurrence",
"rule",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/util/Google2445Utils.java#L196-L199 |
wigforss/Ka-Commons-Reflection | src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java | AnnotationUtils.isAnyAnnotationPresent | public static boolean isAnyAnnotationPresent(Class<?> target, Class<? extends Annotation>... annotations) {
"""
Returns true if any of the supplied annotations is present on the target class
or any of its super classes.
@param annotations Annotations to find.
@return true if any of the supplied annotation is present on the target class
or any of its super classes.
"""
for (Class<? extends Annotation> annotationClass : annotations) {
if (isAnnotationPresent(target, annotationClass)) {
return true;
}
}
return false;
} | java | public static boolean isAnyAnnotationPresent(Class<?> target, Class<? extends Annotation>... annotations) {
for (Class<? extends Annotation> annotationClass : annotations) {
if (isAnnotationPresent(target, annotationClass)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"isAnyAnnotationPresent",
"(",
"Class",
"<",
"?",
">",
"target",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"...",
"annotations",
")",
"{",
"for",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
":",
"annotations",
")",
"{",
"if",
"(",
"isAnnotationPresent",
"(",
"target",
",",
"annotationClass",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if any of the supplied annotations is present on the target class
or any of its super classes.
@param annotations Annotations to find.
@return true if any of the supplied annotation is present on the target class
or any of its super classes. | [
"Returns",
"true",
"if",
"any",
"of",
"the",
"supplied",
"annotations",
"is",
"present",
"on",
"the",
"target",
"class",
"or",
"any",
"of",
"its",
"super",
"classes",
"."
] | train | https://github.com/wigforss/Ka-Commons-Reflection/blob/a80f7a164cd800089e4f4dd948ca6f0e7badcf33/src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java#L46-L53 |
thymeleaf/thymeleaf | src/main/java/org/thymeleaf/linkbuilder/StandardLinkBuilder.java | StandardLinkBuilder.formatParameterValueAsUnescapedVariableTemplate | private static String formatParameterValueAsUnescapedVariableTemplate(final Object parameterValue) {
"""
/*
This method will return a String containing all the values for a specific parameter, separated with commas
and suitable therefore to be used as variable template (path variables) replacements
"""
// Get the value
if (parameterValue == null) { // If null (= NO_VALUE), empty String
return "";
}
// If it is not multivalued (e.g. non-List) simply escape and return
if (!(parameterValue instanceof List<?>)) {
return parameterValue.toString();
}
// It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)
final List<?> values = (List<?>)parameterValue;
final int valuesLen = values.size();
final StringBuilder strBuilder = new StringBuilder(valuesLen * 16);
for (int i = 0; i < valuesLen; i++) {
final Object valueItem = values.get(i);
if (strBuilder.length() > 0) {
strBuilder.append(',');
}
strBuilder.append(valueItem == null? "" : valueItem.toString());
}
return strBuilder.toString();
} | java | private static String formatParameterValueAsUnescapedVariableTemplate(final Object parameterValue) {
// Get the value
if (parameterValue == null) { // If null (= NO_VALUE), empty String
return "";
}
// If it is not multivalued (e.g. non-List) simply escape and return
if (!(parameterValue instanceof List<?>)) {
return parameterValue.toString();
}
// It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)
final List<?> values = (List<?>)parameterValue;
final int valuesLen = values.size();
final StringBuilder strBuilder = new StringBuilder(valuesLen * 16);
for (int i = 0; i < valuesLen; i++) {
final Object valueItem = values.get(i);
if (strBuilder.length() > 0) {
strBuilder.append(',');
}
strBuilder.append(valueItem == null? "" : valueItem.toString());
}
return strBuilder.toString();
} | [
"private",
"static",
"String",
"formatParameterValueAsUnescapedVariableTemplate",
"(",
"final",
"Object",
"parameterValue",
")",
"{",
"// Get the value",
"if",
"(",
"parameterValue",
"==",
"null",
")",
"{",
"// If null (= NO_VALUE), empty String",
"return",
"\"\"",
";",
"}",
"// If it is not multivalued (e.g. non-List) simply escape and return",
"if",
"(",
"!",
"(",
"parameterValue",
"instanceof",
"List",
"<",
"?",
">",
")",
")",
"{",
"return",
"parameterValue",
".",
"toString",
"(",
")",
";",
"}",
"// It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)",
"final",
"List",
"<",
"?",
">",
"values",
"=",
"(",
"List",
"<",
"?",
">",
")",
"parameterValue",
";",
"final",
"int",
"valuesLen",
"=",
"values",
".",
"size",
"(",
")",
";",
"final",
"StringBuilder",
"strBuilder",
"=",
"new",
"StringBuilder",
"(",
"valuesLen",
"*",
"16",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"valuesLen",
";",
"i",
"++",
")",
"{",
"final",
"Object",
"valueItem",
"=",
"values",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"strBuilder",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"strBuilder",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"strBuilder",
".",
"append",
"(",
"valueItem",
"==",
"null",
"?",
"\"\"",
":",
"valueItem",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"strBuilder",
".",
"toString",
"(",
")",
";",
"}"
] | /*
This method will return a String containing all the values for a specific parameter, separated with commas
and suitable therefore to be used as variable template (path variables) replacements | [
"/",
"*",
"This",
"method",
"will",
"return",
"a",
"String",
"containing",
"all",
"the",
"values",
"for",
"a",
"specific",
"parameter",
"separated",
"with",
"commas",
"and",
"suitable",
"therefore",
"to",
"be",
"used",
"as",
"variable",
"template",
"(",
"path",
"variables",
")",
"replacements"
] | train | https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/linkbuilder/StandardLinkBuilder.java#L384-L405 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getUntilLastIncl | @Nullable
public static String getUntilLastIncl (@Nullable final String sStr, @Nullable final String sSearch) {
"""
Get everything from the string up to and including the first passed string.
@param sStr
The source string. May be <code>null</code>.
@param sSearch
The string to search. May be <code>null</code>.
@return <code>null</code> if the passed string does not contain the search
string. If the search string is empty, the empty string is returned.
"""
return _getUntilLast (sStr, sSearch, true);
} | java | @Nullable
public static String getUntilLastIncl (@Nullable final String sStr, @Nullable final String sSearch)
{
return _getUntilLast (sStr, sSearch, true);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getUntilLastIncl",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nullable",
"final",
"String",
"sSearch",
")",
"{",
"return",
"_getUntilLast",
"(",
"sStr",
",",
"sSearch",
",",
"true",
")",
";",
"}"
] | Get everything from the string up to and including the first passed string.
@param sStr
The source string. May be <code>null</code>.
@param sSearch
The string to search. May be <code>null</code>.
@return <code>null</code> if the passed string does not contain the search
string. If the search string is empty, the empty string is returned. | [
"Get",
"everything",
"from",
"the",
"string",
"up",
"to",
"and",
"including",
"the",
"first",
"passed",
"string",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L4891-L4895 |
medallia/Word2VecJava | src/main/java/com/medallia/word2vec/util/Common.java | Common.readResourceToStringChecked | public static String readResourceToStringChecked(Class<?> clazz, String fn) throws IOException {
"""
Read the lines (as UTF8) of the resource file fn from the package of the given class into a string
"""
try (InputStream stream = getResourceAsStream(clazz, fn)) {
return IOUtils.toString(asReaderUTF8Lenient(stream));
}
} | java | public static String readResourceToStringChecked(Class<?> clazz, String fn) throws IOException {
try (InputStream stream = getResourceAsStream(clazz, fn)) {
return IOUtils.toString(asReaderUTF8Lenient(stream));
}
} | [
"public",
"static",
"String",
"readResourceToStringChecked",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fn",
")",
"throws",
"IOException",
"{",
"try",
"(",
"InputStream",
"stream",
"=",
"getResourceAsStream",
"(",
"clazz",
",",
"fn",
")",
")",
"{",
"return",
"IOUtils",
".",
"toString",
"(",
"asReaderUTF8Lenient",
"(",
"stream",
")",
")",
";",
"}",
"}"
] | Read the lines (as UTF8) of the resource file fn from the package of the given class into a string | [
"Read",
"the",
"lines",
"(",
"as",
"UTF8",
")",
"of",
"the",
"resource",
"file",
"fn",
"from",
"the",
"package",
"of",
"the",
"given",
"class",
"into",
"a",
"string"
] | train | https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/Common.java#L136-L140 |
camunda/camunda-bpm-platform | engine-spring/core/src/main/java/org/camunda/bpm/engine/spring/components/scope/ProcessScope.java | ProcessScope.createSharedProcessInstance | private Object createSharedProcessInstance() {
"""
creates a proxy that dispatches invocations to the currently bound {@link ProcessInstance}
@return shareable {@link ProcessInstance}
"""
ProxyFactory proxyFactoryBean = new ProxyFactory(ProcessInstance.class, new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String methodName = methodInvocation.getMethod().getName() ;
logger.info("method invocation for " + methodName+ ".");
if(methodName.equals("toString"))
return "SharedProcessInstance";
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
Method method = methodInvocation.getMethod();
Object[] args = methodInvocation.getArguments();
Object result = method.invoke(processInstance, args);
return result;
}
});
return proxyFactoryBean.getProxy(this.classLoader);
} | java | private Object createSharedProcessInstance() {
ProxyFactory proxyFactoryBean = new ProxyFactory(ProcessInstance.class, new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String methodName = methodInvocation.getMethod().getName() ;
logger.info("method invocation for " + methodName+ ".");
if(methodName.equals("toString"))
return "SharedProcessInstance";
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
Method method = methodInvocation.getMethod();
Object[] args = methodInvocation.getArguments();
Object result = method.invoke(processInstance, args);
return result;
}
});
return proxyFactoryBean.getProxy(this.classLoader);
} | [
"private",
"Object",
"createSharedProcessInstance",
"(",
")",
"{",
"ProxyFactory",
"proxyFactoryBean",
"=",
"new",
"ProxyFactory",
"(",
"ProcessInstance",
".",
"class",
",",
"new",
"MethodInterceptor",
"(",
")",
"{",
"public",
"Object",
"invoke",
"(",
"MethodInvocation",
"methodInvocation",
")",
"throws",
"Throwable",
"{",
"String",
"methodName",
"=",
"methodInvocation",
".",
"getMethod",
"(",
")",
".",
"getName",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"method invocation for \"",
"+",
"methodName",
"+",
"\".\"",
")",
";",
"if",
"(",
"methodName",
".",
"equals",
"(",
"\"toString\"",
")",
")",
"return",
"\"SharedProcessInstance\"",
";",
"ProcessInstance",
"processInstance",
"=",
"Context",
".",
"getExecutionContext",
"(",
")",
".",
"getProcessInstance",
"(",
")",
";",
"Method",
"method",
"=",
"methodInvocation",
".",
"getMethod",
"(",
")",
";",
"Object",
"[",
"]",
"args",
"=",
"methodInvocation",
".",
"getArguments",
"(",
")",
";",
"Object",
"result",
"=",
"method",
".",
"invoke",
"(",
"processInstance",
",",
"args",
")",
";",
"return",
"result",
";",
"}",
"}",
")",
";",
"return",
"proxyFactoryBean",
".",
"getProxy",
"(",
"this",
".",
"classLoader",
")",
";",
"}"
] | creates a proxy that dispatches invocations to the currently bound {@link ProcessInstance}
@return shareable {@link ProcessInstance} | [
"creates",
"a",
"proxy",
"that",
"dispatches",
"invocations",
"to",
"the",
"currently",
"bound",
"{",
"@link",
"ProcessInstance",
"}"
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine-spring/core/src/main/java/org/camunda/bpm/engine/spring/components/scope/ProcessScope.java#L148-L166 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.setCertificateIssuerAsync | public ServiceFuture<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback<IssuerBundle> serviceCallback) {
"""
Sets the specified certificate issuer.
The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@param provider The issuer provider.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object
"""
return ServiceFuture.fromResponse(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider), serviceCallback);
} | java | public ServiceFuture<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, final ServiceCallback<IssuerBundle> serviceCallback) {
return ServiceFuture.fromResponse(setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"IssuerBundle",
">",
"setCertificateIssuerAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"issuerName",
",",
"String",
"provider",
",",
"final",
"ServiceCallback",
"<",
"IssuerBundle",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
".",
"fromResponse",
"(",
"setCertificateIssuerWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"issuerName",
",",
"provider",
")",
",",
"serviceCallback",
")",
";",
"}"
] | Sets the specified certificate issuer.
The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@param provider The issuer provider.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Sets",
"the",
"specified",
"certificate",
"issuer",
".",
"The",
"SetCertificateIssuer",
"operation",
"adds",
"or",
"updates",
"the",
"specified",
"certificate",
"issuer",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"setissuers",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5915-L5917 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF5.java | CommonOps_DDF5.elementMult | public static void elementMult( DMatrix5 a , DMatrix5 b , DMatrix5 c ) {
"""
<p>Performs an element by element multiplication operation:<br>
<br>
c<sub>i</sub> = a<sub>i</sub> * b<sub>j</sub> <br>
</p>
@param a The left vector in the multiplication operation. Not modified.
@param b The right vector in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified.
"""
c.a1 = a.a1*b.a1;
c.a2 = a.a2*b.a2;
c.a3 = a.a3*b.a3;
c.a4 = a.a4*b.a4;
c.a5 = a.a5*b.a5;
} | java | public static void elementMult( DMatrix5 a , DMatrix5 b , DMatrix5 c ) {
c.a1 = a.a1*b.a1;
c.a2 = a.a2*b.a2;
c.a3 = a.a3*b.a3;
c.a4 = a.a4*b.a4;
c.a5 = a.a5*b.a5;
} | [
"public",
"static",
"void",
"elementMult",
"(",
"DMatrix5",
"a",
",",
"DMatrix5",
"b",
",",
"DMatrix5",
"c",
")",
"{",
"c",
".",
"a1",
"=",
"a",
".",
"a1",
"*",
"b",
".",
"a1",
";",
"c",
".",
"a2",
"=",
"a",
".",
"a2",
"*",
"b",
".",
"a2",
";",
"c",
".",
"a3",
"=",
"a",
".",
"a3",
"*",
"b",
".",
"a3",
";",
"c",
".",
"a4",
"=",
"a",
".",
"a4",
"*",
"b",
".",
"a4",
";",
"c",
".",
"a5",
"=",
"a",
".",
"a5",
"*",
"b",
".",
"a5",
";",
"}"
] | <p>Performs an element by element multiplication operation:<br>
<br>
c<sub>i</sub> = a<sub>i</sub> * b<sub>j</sub> <br>
</p>
@param a The left vector in the multiplication operation. Not modified.
@param b The right vector in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"an",
"element",
"by",
"element",
"multiplication",
"operation",
":",
"<br",
">",
"<br",
">",
"c<sub",
">",
"i<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"j<",
"/",
"sub",
">",
"<br",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF5.java#L1652-L1658 |
shrinkwrap/resolver | maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolvedArtifactImpl.java | MavenResolvedArtifactImpl.artifactToFile | private static File artifactToFile(final Artifact artifact) throws IllegalArgumentException {
"""
Maps an artifact to a file. This allows ShrinkWrap Maven resolver to package reactor related dependencies.
"""
if (artifact == null) {
throw new IllegalArgumentException("ArtifactResult must not be null");
}
// FIXME: this is not a safe assumption, file can have a different name
if ("pom.xml".equals(artifact.getFile().getName())) {
String artifactId = artifact.getArtifactId();
String extension = artifact.getExtension();
String classifier = artifact.getClassifier();
File root = new File(artifact.getFile().getParentFile(), "target/classes");
if (!Validate.isNullOrEmpty(classifier) && "tests".equals(classifier)) {
// SHRINKRES-102, allow test classes to be packaged as well
root = new File(artifact.getFile().getParentFile(), "target/test-classes");
} else if ("war".equals(artifact.getProperty(ArtifactProperties.TYPE, null))) {
// SHRINKRES-263, allow .war files to be packaged as well
root = new File(artifact.getFile().getParentFile(), "target/" + artifactId + "-" + artifact.getVersion());
}
try {
File archive = File.createTempFile(artifactId + "-", "." + extension);
archive.deleteOnExit();
PackageDirHelper.packageDirectories(archive, root);
return archive;
} catch (IOException e) {
throw new IllegalArgumentException("Unable to get artifact " + artifactId + " from the classpath", e);
}
} else {
return artifact.getFile();
}
} | java | private static File artifactToFile(final Artifact artifact) throws IllegalArgumentException {
if (artifact == null) {
throw new IllegalArgumentException("ArtifactResult must not be null");
}
// FIXME: this is not a safe assumption, file can have a different name
if ("pom.xml".equals(artifact.getFile().getName())) {
String artifactId = artifact.getArtifactId();
String extension = artifact.getExtension();
String classifier = artifact.getClassifier();
File root = new File(artifact.getFile().getParentFile(), "target/classes");
if (!Validate.isNullOrEmpty(classifier) && "tests".equals(classifier)) {
// SHRINKRES-102, allow test classes to be packaged as well
root = new File(artifact.getFile().getParentFile(), "target/test-classes");
} else if ("war".equals(artifact.getProperty(ArtifactProperties.TYPE, null))) {
// SHRINKRES-263, allow .war files to be packaged as well
root = new File(artifact.getFile().getParentFile(), "target/" + artifactId + "-" + artifact.getVersion());
}
try {
File archive = File.createTempFile(artifactId + "-", "." + extension);
archive.deleteOnExit();
PackageDirHelper.packageDirectories(archive, root);
return archive;
} catch (IOException e) {
throw new IllegalArgumentException("Unable to get artifact " + artifactId + " from the classpath", e);
}
} else {
return artifact.getFile();
}
} | [
"private",
"static",
"File",
"artifactToFile",
"(",
"final",
"Artifact",
"artifact",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"artifact",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"ArtifactResult must not be null\"",
")",
";",
"}",
"// FIXME: this is not a safe assumption, file can have a different name",
"if",
"(",
"\"pom.xml\"",
".",
"equals",
"(",
"artifact",
".",
"getFile",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
"{",
"String",
"artifactId",
"=",
"artifact",
".",
"getArtifactId",
"(",
")",
";",
"String",
"extension",
"=",
"artifact",
".",
"getExtension",
"(",
")",
";",
"String",
"classifier",
"=",
"artifact",
".",
"getClassifier",
"(",
")",
";",
"File",
"root",
"=",
"new",
"File",
"(",
"artifact",
".",
"getFile",
"(",
")",
".",
"getParentFile",
"(",
")",
",",
"\"target/classes\"",
")",
";",
"if",
"(",
"!",
"Validate",
".",
"isNullOrEmpty",
"(",
"classifier",
")",
"&&",
"\"tests\"",
".",
"equals",
"(",
"classifier",
")",
")",
"{",
"// SHRINKRES-102, allow test classes to be packaged as well",
"root",
"=",
"new",
"File",
"(",
"artifact",
".",
"getFile",
"(",
")",
".",
"getParentFile",
"(",
")",
",",
"\"target/test-classes\"",
")",
";",
"}",
"else",
"if",
"(",
"\"war\"",
".",
"equals",
"(",
"artifact",
".",
"getProperty",
"(",
"ArtifactProperties",
".",
"TYPE",
",",
"null",
")",
")",
")",
"{",
"// SHRINKRES-263, allow .war files to be packaged as well",
"root",
"=",
"new",
"File",
"(",
"artifact",
".",
"getFile",
"(",
")",
".",
"getParentFile",
"(",
")",
",",
"\"target/\"",
"+",
"artifactId",
"+",
"\"-\"",
"+",
"artifact",
".",
"getVersion",
"(",
")",
")",
";",
"}",
"try",
"{",
"File",
"archive",
"=",
"File",
".",
"createTempFile",
"(",
"artifactId",
"+",
"\"-\"",
",",
"\".\"",
"+",
"extension",
")",
";",
"archive",
".",
"deleteOnExit",
"(",
")",
";",
"PackageDirHelper",
".",
"packageDirectories",
"(",
"archive",
",",
"root",
")",
";",
"return",
"archive",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unable to get artifact \"",
"+",
"artifactId",
"+",
"\" from the classpath\"",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"return",
"artifact",
".",
"getFile",
"(",
")",
";",
"}",
"}"
] | Maps an artifact to a file. This allows ShrinkWrap Maven resolver to package reactor related dependencies. | [
"Maps",
"an",
"artifact",
"to",
"a",
"file",
".",
"This",
"allows",
"ShrinkWrap",
"Maven",
"resolver",
"to",
"package",
"reactor",
"related",
"dependencies",
"."
] | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolvedArtifactImpl.java#L132-L166 |
korpling/ANNIS | annis-libgui/src/main/java/annis/libgui/Helper.java | Helper.getAnnisWebResource | public static WebResource getAnnisWebResource() {
"""
Gets or creates a web resource to the ANNIS service.
This is a convenience wrapper to {@link #getAnnisWebResource(java.lang.String, annis.security.AnnisUser)
}
that does not need any arguments
@return A reference to the ANNIS service root resource.
"""
VaadinSession vSession = VaadinSession.getCurrent();
// get URI used by the application
String uri = null;
if (vSession != null)
{
uri = (String) VaadinSession.getCurrent().getAttribute(
KEY_WEB_SERVICE_URL);
}
// if already authentificated the REST client is set as the "user" property
AnnisUser user = getUser();
return getAnnisWebResource(uri, user);
} | java | public static WebResource getAnnisWebResource()
{
VaadinSession vSession = VaadinSession.getCurrent();
// get URI used by the application
String uri = null;
if (vSession != null)
{
uri = (String) VaadinSession.getCurrent().getAttribute(
KEY_WEB_SERVICE_URL);
}
// if already authentificated the REST client is set as the "user" property
AnnisUser user = getUser();
return getAnnisWebResource(uri, user);
} | [
"public",
"static",
"WebResource",
"getAnnisWebResource",
"(",
")",
"{",
"VaadinSession",
"vSession",
"=",
"VaadinSession",
".",
"getCurrent",
"(",
")",
";",
"// get URI used by the application",
"String",
"uri",
"=",
"null",
";",
"if",
"(",
"vSession",
"!=",
"null",
")",
"{",
"uri",
"=",
"(",
"String",
")",
"VaadinSession",
".",
"getCurrent",
"(",
")",
".",
"getAttribute",
"(",
"KEY_WEB_SERVICE_URL",
")",
";",
"}",
"// if already authentificated the REST client is set as the \"user\" property",
"AnnisUser",
"user",
"=",
"getUser",
"(",
")",
";",
"return",
"getAnnisWebResource",
"(",
"uri",
",",
"user",
")",
";",
"}"
] | Gets or creates a web resource to the ANNIS service.
This is a convenience wrapper to {@link #getAnnisWebResource(java.lang.String, annis.security.AnnisUser)
}
that does not need any arguments
@return A reference to the ANNIS service root resource. | [
"Gets",
"or",
"creates",
"a",
"web",
"resource",
"to",
"the",
"ANNIS",
"service",
"."
] | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-libgui/src/main/java/annis/libgui/Helper.java#L322-L340 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.multAdd | public static void multAdd(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) {
"""
<p>
Performs the following operation:<br>
<br>
c = c + a * b<br>
c<sub>ij</sub> = c<sub>ij</sub> + ∑<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>kj</sub>}
</p>
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified.
"""
if( b.numCols == 1 ) {
MatrixVectorMult_DDRM.multAdd(a, b, c);
} else {
if( b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multAdd_reorder(a,b,c);
} else {
MatrixMatrixMult_DDRM.multAdd_small(a,b,c);
}
}
} | java | public static void multAdd(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
if( b.numCols == 1 ) {
MatrixVectorMult_DDRM.multAdd(a, b, c);
} else {
if( b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multAdd_reorder(a,b,c);
} else {
MatrixMatrixMult_DDRM.multAdd_small(a,b,c);
}
}
} | [
"public",
"static",
"void",
"multAdd",
"(",
"DMatrix1Row",
"a",
",",
"DMatrix1Row",
"b",
",",
"DMatrix1Row",
"c",
")",
"{",
"if",
"(",
"b",
".",
"numCols",
"==",
"1",
")",
"{",
"MatrixVectorMult_DDRM",
".",
"multAdd",
"(",
"a",
",",
"b",
",",
"c",
")",
";",
"}",
"else",
"{",
"if",
"(",
"b",
".",
"numCols",
">=",
"EjmlParameters",
".",
"MULT_COLUMN_SWITCH",
")",
"{",
"MatrixMatrixMult_DDRM",
".",
"multAdd_reorder",
"(",
"a",
",",
"b",
",",
"c",
")",
";",
"}",
"else",
"{",
"MatrixMatrixMult_DDRM",
".",
"multAdd_small",
"(",
"a",
",",
"b",
",",
"c",
")",
";",
"}",
"}",
"}"
] | <p>
Performs the following operation:<br>
<br>
c = c + a * b<br>
c<sub>ij</sub> = c<sub>ij</sub> + ∑<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>kj</sub>}
</p>
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"c",
"=",
"c",
"+",
"a",
"*",
"b<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"+",
"&sum",
";",
"<sub",
">",
"k",
"=",
"1",
":",
"n<",
"/",
"sub",
">",
"{",
"a<sub",
">",
"ik<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"kj<",
"/",
"sub",
">",
"}",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L333-L344 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/lang/GenericReflection.java | GenericReflection.getClassFromNameSafe | @Nullable
public static <DATATYPE> Class <DATATYPE> getClassFromNameSafe (@Nonnull final ClassLoader aClassLoader,
@Nonnull final String sName) {
"""
Get the class of the given name
@param <DATATYPE>
The return type
@param aClassLoader
The class loader to be used. May not be <code>null</code>.
@param sName
The name to be resolved.
@return <code>null</code> if the class could not be resolved
"""
ValueEnforcer.notNull (aClassLoader, "ClassLoader");
try
{
return getClassFromName (aClassLoader, sName);
}
catch (final ClassNotFoundException e)
{
return null;
}
} | java | @Nullable
public static <DATATYPE> Class <DATATYPE> getClassFromNameSafe (@Nonnull final ClassLoader aClassLoader,
@Nonnull final String sName)
{
ValueEnforcer.notNull (aClassLoader, "ClassLoader");
try
{
return getClassFromName (aClassLoader, sName);
}
catch (final ClassNotFoundException e)
{
return null;
}
} | [
"@",
"Nullable",
"public",
"static",
"<",
"DATATYPE",
">",
"Class",
"<",
"DATATYPE",
">",
"getClassFromNameSafe",
"(",
"@",
"Nonnull",
"final",
"ClassLoader",
"aClassLoader",
",",
"@",
"Nonnull",
"final",
"String",
"sName",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aClassLoader",
",",
"\"ClassLoader\"",
")",
";",
"try",
"{",
"return",
"getClassFromName",
"(",
"aClassLoader",
",",
"sName",
")",
";",
"}",
"catch",
"(",
"final",
"ClassNotFoundException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Get the class of the given name
@param <DATATYPE>
The return type
@param aClassLoader
The class loader to be used. May not be <code>null</code>.
@param sName
The name to be resolved.
@return <code>null</code> if the class could not be resolved | [
"Get",
"the",
"class",
"of",
"the",
"given",
"name"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/GenericReflection.java#L84-L97 |
windup/windup | config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationOperation.java | AbstractIterationOperation.checkVariableName | protected void checkVariableName(GraphRewrite event, EvaluationContext context) {
"""
Check the variable name and if not set, set it with the singleton variable name being on the top of the stack.
"""
if (variableName == null)
{
setVariableName(Iteration.getPayloadVariableName(event, context));
}
} | java | protected void checkVariableName(GraphRewrite event, EvaluationContext context)
{
if (variableName == null)
{
setVariableName(Iteration.getPayloadVariableName(event, context));
}
} | [
"protected",
"void",
"checkVariableName",
"(",
"GraphRewrite",
"event",
",",
"EvaluationContext",
"context",
")",
"{",
"if",
"(",
"variableName",
"==",
"null",
")",
"{",
"setVariableName",
"(",
"Iteration",
".",
"getPayloadVariableName",
"(",
"event",
",",
"context",
")",
")",
";",
"}",
"}"
] | Check the variable name and if not set, set it with the singleton variable name being on the top of the stack. | [
"Check",
"the",
"variable",
"name",
"and",
"if",
"not",
"set",
"set",
"it",
"with",
"the",
"singleton",
"variable",
"name",
"being",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationOperation.java#L77-L83 |
lightblueseas/file-worker | src/main/java/de/alpharogroup/file/write/WriteFileExtensions.java | WriteFileExtensions.writeLinesToFile | public static void writeLinesToFile(final File output, final List<String> input,
final String encoding) throws FileNotFoundException, IOException {
"""
Writes the input from the collection into the file.
@param output
The file to write the lines.
@param input
The list with the input data.
@param encoding
The encoding.
@throws FileNotFoundException
is thrown if an attempt to open the file denoted by a specified pathname has
failed.
@throws IOException
Signals that an I/O exception has occurred.
"""
final String lineSeparator = System.getProperty("line.separator");
try (FileOutputStream fos = new FileOutputStream(output);
OutputStreamWriter osw = (null == encoding)
? new OutputStreamWriter(fos)
: new OutputStreamWriter(fos, encoding);
PrintWriter out = new PrintWriter(osw);)
{
final int size = input.size();
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++)
{
final String entry = input.get(i);
sb.append(entry).append(lineSeparator);
}
out.write(sb.toString());
}
} | java | public static void writeLinesToFile(final File output, final List<String> input,
final String encoding) throws FileNotFoundException, IOException
{
final String lineSeparator = System.getProperty("line.separator");
try (FileOutputStream fos = new FileOutputStream(output);
OutputStreamWriter osw = (null == encoding)
? new OutputStreamWriter(fos)
: new OutputStreamWriter(fos, encoding);
PrintWriter out = new PrintWriter(osw);)
{
final int size = input.size();
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++)
{
final String entry = input.get(i);
sb.append(entry).append(lineSeparator);
}
out.write(sb.toString());
}
} | [
"public",
"static",
"void",
"writeLinesToFile",
"(",
"final",
"File",
"output",
",",
"final",
"List",
"<",
"String",
">",
"input",
",",
"final",
"String",
"encoding",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"final",
"String",
"lineSeparator",
"=",
"System",
".",
"getProperty",
"(",
"\"line.separator\"",
")",
";",
"try",
"(",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"output",
")",
";",
"OutputStreamWriter",
"osw",
"=",
"(",
"null",
"==",
"encoding",
")",
"?",
"new",
"OutputStreamWriter",
"(",
"fos",
")",
":",
"new",
"OutputStreamWriter",
"(",
"fos",
",",
"encoding",
")",
";",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"osw",
")",
";",
")",
"{",
"final",
"int",
"size",
"=",
"input",
".",
"size",
"(",
")",
";",
"final",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"final",
"String",
"entry",
"=",
"input",
".",
"get",
"(",
"i",
")",
";",
"sb",
".",
"append",
"(",
"entry",
")",
".",
"append",
"(",
"lineSeparator",
")",
";",
"}",
"out",
".",
"write",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] | Writes the input from the collection into the file.
@param output
The file to write the lines.
@param input
The list with the input data.
@param encoding
The encoding.
@throws FileNotFoundException
is thrown if an attempt to open the file denoted by a specified pathname has
failed.
@throws IOException
Signals that an I/O exception has occurred. | [
"Writes",
"the",
"input",
"from",
"the",
"collection",
"into",
"the",
"file",
"."
] | train | https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/write/WriteFileExtensions.java#L98-L117 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java | CommerceAvailabilityEstimatePersistenceImpl.removeByUUID_G | @Override
public CommerceAvailabilityEstimate removeByUUID_G(String uuid, long groupId)
throws NoSuchAvailabilityEstimateException {
"""
Removes the commerce availability estimate where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce availability estimate that was removed
"""
CommerceAvailabilityEstimate commerceAvailabilityEstimate = findByUUID_G(uuid,
groupId);
return remove(commerceAvailabilityEstimate);
} | java | @Override
public CommerceAvailabilityEstimate removeByUUID_G(String uuid, long groupId)
throws NoSuchAvailabilityEstimateException {
CommerceAvailabilityEstimate commerceAvailabilityEstimate = findByUUID_G(uuid,
groupId);
return remove(commerceAvailabilityEstimate);
} | [
"@",
"Override",
"public",
"CommerceAvailabilityEstimate",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchAvailabilityEstimateException",
"{",
"CommerceAvailabilityEstimate",
"commerceAvailabilityEstimate",
"=",
"findByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"return",
"remove",
"(",
"commerceAvailabilityEstimate",
")",
";",
"}"
] | Removes the commerce availability estimate where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce availability estimate that was removed | [
"Removes",
"the",
"commerce",
"availability",
"estimate",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java#L824-L831 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java | CacheOnDisk.readTemplate | public ValueSet readTemplate(String template, boolean delete) {
"""
Call this method to read a specified template which contains the cache ids from the disk.
@param template
- template id.
@param delete
- boolean to delete the template after reading
@return valueSet - the collection of cache ids.
"""
Result result = htod.readTemplate(template, delete);
if (result.returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(result.diskException);
this.htod.returnToResultPool(result);
return HTODDynacache.EMPTY_VS;
}
ValueSet valueSet = (ValueSet) result.data;
if (valueSet == null) {
valueSet = HTODDynacache.EMPTY_VS;
}
this.htod.returnToResultPool(result);
return valueSet;
} | java | public ValueSet readTemplate(String template, boolean delete) {
Result result = htod.readTemplate(template, delete);
if (result.returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(result.diskException);
this.htod.returnToResultPool(result);
return HTODDynacache.EMPTY_VS;
}
ValueSet valueSet = (ValueSet) result.data;
if (valueSet == null) {
valueSet = HTODDynacache.EMPTY_VS;
}
this.htod.returnToResultPool(result);
return valueSet;
} | [
"public",
"ValueSet",
"readTemplate",
"(",
"String",
"template",
",",
"boolean",
"delete",
")",
"{",
"Result",
"result",
"=",
"htod",
".",
"readTemplate",
"(",
"template",
",",
"delete",
")",
";",
"if",
"(",
"result",
".",
"returnCode",
"==",
"HTODDynacache",
".",
"DISK_EXCEPTION",
")",
"{",
"stopOnError",
"(",
"result",
".",
"diskException",
")",
";",
"this",
".",
"htod",
".",
"returnToResultPool",
"(",
"result",
")",
";",
"return",
"HTODDynacache",
".",
"EMPTY_VS",
";",
"}",
"ValueSet",
"valueSet",
"=",
"(",
"ValueSet",
")",
"result",
".",
"data",
";",
"if",
"(",
"valueSet",
"==",
"null",
")",
"{",
"valueSet",
"=",
"HTODDynacache",
".",
"EMPTY_VS",
";",
"}",
"this",
".",
"htod",
".",
"returnToResultPool",
"(",
"result",
")",
";",
"return",
"valueSet",
";",
"}"
] | Call this method to read a specified template which contains the cache ids from the disk.
@param template
- template id.
@param delete
- boolean to delete the template after reading
@return valueSet - the collection of cache ids. | [
"Call",
"this",
"method",
"to",
"read",
"a",
"specified",
"template",
"which",
"contains",
"the",
"cache",
"ids",
"from",
"the",
"disk",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java#L1334-L1347 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/html/Button.java | Button.addParameter | public void addParameter(String name, Object value, String facet)
throws JspException {
"""
Adds a URL parameter to the generated hyperlink.
@param name the name of the parameter to be added.
@param value the value of the parameter to be added (a String or String[]).
@param facet
"""
assert(name != null) : "Parameter 'name' must not be null";
if (_params == null) {
_params = new HashMap();
}
ParamHelper.addParam(_params, name, value);
} | java | public void addParameter(String name, Object value, String facet)
throws JspException
{
assert(name != null) : "Parameter 'name' must not be null";
if (_params == null) {
_params = new HashMap();
}
ParamHelper.addParam(_params, name, value);
} | [
"public",
"void",
"addParameter",
"(",
"String",
"name",
",",
"Object",
"value",
",",
"String",
"facet",
")",
"throws",
"JspException",
"{",
"assert",
"(",
"name",
"!=",
"null",
")",
":",
"\"Parameter 'name' must not be null\"",
";",
"if",
"(",
"_params",
"==",
"null",
")",
"{",
"_params",
"=",
"new",
"HashMap",
"(",
")",
";",
"}",
"ParamHelper",
".",
"addParam",
"(",
"_params",
",",
"name",
",",
"value",
")",
";",
"}"
] | Adds a URL parameter to the generated hyperlink.
@param name the name of the parameter to be added.
@param value the value of the parameter to be added (a String or String[]).
@param facet | [
"Adds",
"a",
"URL",
"parameter",
"to",
"the",
"generated",
"hyperlink",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/html/Button.java#L281-L290 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/ValidatingStreamReader.java | ValidatingStreamReader.resolveExtSubsetPath | private URI resolveExtSubsetPath(String systemId) throws IOException {
"""
Method called to resolve path to external DTD subset, given
system identifier.
"""
// Do we have a context to use for resolving?
URL ctxt = (mInput == null) ? null : mInput.getSource();
/* Ok, either got a context or not; let's create the URL based on
* the id, and optional context:
*/
if (ctxt == null) {
/* Call will try to figure out if system id has the protocol
* in it; if not, create a relative file, if it does, try to
* resolve it.
*/
return URLUtil.uriFromSystemId(systemId);
}
URL url = URLUtil.urlFromSystemId(systemId, ctxt);
try {
return new URI(url.toExternalForm());
} catch (URISyntaxException e) { // should never occur...
throw new IOException("Failed to construct URI for external subset, URL = "+url.toExternalForm()+": "+e.getMessage());
}
} | java | private URI resolveExtSubsetPath(String systemId) throws IOException
{
// Do we have a context to use for resolving?
URL ctxt = (mInput == null) ? null : mInput.getSource();
/* Ok, either got a context or not; let's create the URL based on
* the id, and optional context:
*/
if (ctxt == null) {
/* Call will try to figure out if system id has the protocol
* in it; if not, create a relative file, if it does, try to
* resolve it.
*/
return URLUtil.uriFromSystemId(systemId);
}
URL url = URLUtil.urlFromSystemId(systemId, ctxt);
try {
return new URI(url.toExternalForm());
} catch (URISyntaxException e) { // should never occur...
throw new IOException("Failed to construct URI for external subset, URL = "+url.toExternalForm()+": "+e.getMessage());
}
} | [
"private",
"URI",
"resolveExtSubsetPath",
"(",
"String",
"systemId",
")",
"throws",
"IOException",
"{",
"// Do we have a context to use for resolving?",
"URL",
"ctxt",
"=",
"(",
"mInput",
"==",
"null",
")",
"?",
"null",
":",
"mInput",
".",
"getSource",
"(",
")",
";",
"/* Ok, either got a context or not; let's create the URL based on\n * the id, and optional context:\n */",
"if",
"(",
"ctxt",
"==",
"null",
")",
"{",
"/* Call will try to figure out if system id has the protocol\n * in it; if not, create a relative file, if it does, try to\n * resolve it.\n */",
"return",
"URLUtil",
".",
"uriFromSystemId",
"(",
"systemId",
")",
";",
"}",
"URL",
"url",
"=",
"URLUtil",
".",
"urlFromSystemId",
"(",
"systemId",
",",
"ctxt",
")",
";",
"try",
"{",
"return",
"new",
"URI",
"(",
"url",
".",
"toExternalForm",
"(",
")",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"// should never occur...",
"throw",
"new",
"IOException",
"(",
"\"Failed to construct URI for external subset, URL = \"",
"+",
"url",
".",
"toExternalForm",
"(",
")",
"+",
"\": \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Method called to resolve path to external DTD subset, given
system identifier. | [
"Method",
"called",
"to",
"resolve",
"path",
"to",
"external",
"DTD",
"subset",
"given",
"system",
"identifier",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/ValidatingStreamReader.java#L507-L528 |
threerings/nenya | core/src/main/java/com/threerings/util/DirectionUtil.java | DirectionUtil.rotateCCW | public static int rotateCCW (int direction, int ticks) {
"""
Rotates the requested <em>fine</em> direction constant counter-clockwise by the requested
number of ticks.
"""
for (int ii = 0; ii < ticks; ii++) {
direction = FINE_CCW_ROTATE[direction];
}
return direction;
} | java | public static int rotateCCW (int direction, int ticks)
{
for (int ii = 0; ii < ticks; ii++) {
direction = FINE_CCW_ROTATE[direction];
}
return direction;
} | [
"public",
"static",
"int",
"rotateCCW",
"(",
"int",
"direction",
",",
"int",
"ticks",
")",
"{",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"ticks",
";",
"ii",
"++",
")",
"{",
"direction",
"=",
"FINE_CCW_ROTATE",
"[",
"direction",
"]",
";",
"}",
"return",
"direction",
";",
"}"
] | Rotates the requested <em>fine</em> direction constant counter-clockwise by the requested
number of ticks. | [
"Rotates",
"the",
"requested",
"<em",
">",
"fine<",
"/",
"em",
">",
"direction",
"constant",
"counter",
"-",
"clockwise",
"by",
"the",
"requested",
"number",
"of",
"ticks",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/util/DirectionUtil.java#L117-L123 |
dlemmermann/CalendarFX | CalendarFXRecurrence/src/main/java/com/google/ical/compat/jodatime/LocalDateIteratorFactory.java | LocalDateIteratorFactory.createLocalDateIterable | public static LocalDateIterable createLocalDateIterable(
String rdata, LocalDate start, boolean strict)
throws ParseException {
"""
given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse
them into a single local date iterable.
@param rdata RRULE, EXRULE, RDATE, and EXDATE lines.
@param start the first occurrence of the series.
@param strict true if any failure to parse should result in a
ParseException. false causes bad content lines to be logged and ignored.
"""
return createLocalDateIterable(rdata, start, DateTimeZone.UTC, strict);
} | java | public static LocalDateIterable createLocalDateIterable(
String rdata, LocalDate start, boolean strict)
throws ParseException {
return createLocalDateIterable(rdata, start, DateTimeZone.UTC, strict);
} | [
"public",
"static",
"LocalDateIterable",
"createLocalDateIterable",
"(",
"String",
"rdata",
",",
"LocalDate",
"start",
",",
"boolean",
"strict",
")",
"throws",
"ParseException",
"{",
"return",
"createLocalDateIterable",
"(",
"rdata",
",",
"start",
",",
"DateTimeZone",
".",
"UTC",
",",
"strict",
")",
";",
"}"
] | given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse
them into a single local date iterable.
@param rdata RRULE, EXRULE, RDATE, and EXDATE lines.
@param start the first occurrence of the series.
@param strict true if any failure to parse should result in a
ParseException. false causes bad content lines to be logged and ignored. | [
"given",
"a",
"block",
"of",
"RRULE",
"EXRULE",
"RDATE",
"and",
"EXDATE",
"content",
"lines",
"parse",
"them",
"into",
"a",
"single",
"local",
"date",
"iterable",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/compat/jodatime/LocalDateIteratorFactory.java#L104-L108 |
kiegroup/drools | drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java | DataProviderCompiler.compile | public String compile(final DataProvider dataProvider,
final InputStream templateStream) {
"""
Generates DRL from a data provider for the spreadsheet data and templates.
@param dataProvider the data provider for the spreadsheet data
@param templateStream the InputStream for reading the templates
@return the generated DRL text as a String
"""
return compile(dataProvider,templateStream, true );
} | java | public String compile(final DataProvider dataProvider,
final InputStream templateStream) {
return compile(dataProvider,templateStream, true );
} | [
"public",
"String",
"compile",
"(",
"final",
"DataProvider",
"dataProvider",
",",
"final",
"InputStream",
"templateStream",
")",
"{",
"return",
"compile",
"(",
"dataProvider",
",",
"templateStream",
",",
"true",
")",
";",
"}"
] | Generates DRL from a data provider for the spreadsheet data and templates.
@param dataProvider the data provider for the spreadsheet data
@param templateStream the InputStream for reading the templates
@return the generated DRL text as a String | [
"Generates",
"DRL",
"from",
"a",
"data",
"provider",
"for",
"the",
"spreadsheet",
"data",
"and",
"templates",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java#L55-L58 |
kiegroup/drools | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java | CompiledFEELSemanticMappings.or | public static Boolean or(Object left, Object right) {
"""
FEEL spec Table 38
Delegates to {@link InfixOpNode} except evaluationcontext
"""
return (Boolean) InfixOpNode.or(left, right, null);
} | java | public static Boolean or(Object left, Object right) {
return (Boolean) InfixOpNode.or(left, right, null);
} | [
"public",
"static",
"Boolean",
"or",
"(",
"Object",
"left",
",",
"Object",
"right",
")",
"{",
"return",
"(",
"Boolean",
")",
"InfixOpNode",
".",
"or",
"(",
"left",
",",
"right",
",",
"null",
")",
";",
"}"
] | FEEL spec Table 38
Delegates to {@link InfixOpNode} except evaluationcontext | [
"FEEL",
"spec",
"Table",
"38",
"Delegates",
"to",
"{"
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java#L278-L280 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java | IntegrationAccountAssembliesInner.getAsync | public Observable<AssemblyDefinitionInner> getAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) {
"""
Get an assembly for an integration account.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param assemblyArtifactName The assembly artifact name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AssemblyDefinitionInner object
"""
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).map(new Func1<ServiceResponse<AssemblyDefinitionInner>, AssemblyDefinitionInner>() {
@Override
public AssemblyDefinitionInner call(ServiceResponse<AssemblyDefinitionInner> response) {
return response.body();
}
});
} | java | public Observable<AssemblyDefinitionInner> getAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).map(new Func1<ServiceResponse<AssemblyDefinitionInner>, AssemblyDefinitionInner>() {
@Override
public AssemblyDefinitionInner call(ServiceResponse<AssemblyDefinitionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AssemblyDefinitionInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"String",
"assemblyArtifactName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"integrationAccountName",
",",
"assemblyArtifactName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"AssemblyDefinitionInner",
">",
",",
"AssemblyDefinitionInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"AssemblyDefinitionInner",
"call",
"(",
"ServiceResponse",
"<",
"AssemblyDefinitionInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get an assembly for an integration account.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param assemblyArtifactName The assembly artifact name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AssemblyDefinitionInner object | [
"Get",
"an",
"assembly",
"for",
"an",
"integration",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java#L211-L218 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java | CustomVisionPredictionManager.authenticate | public static PredictionEndpoint authenticate(String baseUrl, final String apiKey) {
"""
Initializes an instance of Custom Vision Prediction API client.
@param baseUrl the base URL of the service
@param apiKey the Custom Vision Prediction API key
@return the Custom Vision Prediction API client
"""
ServiceClientCredentials serviceClientCredentials = new ServiceClientCredentials() {
@Override
public void applyCredentialsFilter(OkHttpClient.Builder builder) {
}
};
return authenticate(baseUrl, serviceClientCredentials, apiKey);
} | java | public static PredictionEndpoint authenticate(String baseUrl, final String apiKey) {
ServiceClientCredentials serviceClientCredentials = new ServiceClientCredentials() {
@Override
public void applyCredentialsFilter(OkHttpClient.Builder builder) {
}
};
return authenticate(baseUrl, serviceClientCredentials, apiKey);
} | [
"public",
"static",
"PredictionEndpoint",
"authenticate",
"(",
"String",
"baseUrl",
",",
"final",
"String",
"apiKey",
")",
"{",
"ServiceClientCredentials",
"serviceClientCredentials",
"=",
"new",
"ServiceClientCredentials",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"applyCredentialsFilter",
"(",
"OkHttpClient",
".",
"Builder",
"builder",
")",
"{",
"}",
"}",
";",
"return",
"authenticate",
"(",
"baseUrl",
",",
"serviceClientCredentials",
",",
"apiKey",
")",
";",
"}"
] | Initializes an instance of Custom Vision Prediction API client.
@param baseUrl the base URL of the service
@param apiKey the Custom Vision Prediction API key
@return the Custom Vision Prediction API client | [
"Initializes",
"an",
"instance",
"of",
"Custom",
"Vision",
"Prediction",
"API",
"client",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java#L35-L42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.