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
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
javamelody/javamelody | javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java | PayloadNameRequestWrapper.scanForChildTag | static boolean scanForChildTag(XMLStreamReader reader, String tagName)
throws XMLStreamException {
"""
Scan xml for tag child of the current element
@param reader reader, must be at "start element" @nonnull
@param tagName name of child tag to find @nonnull
@return if found tag
@throws XMLStreamException on error
"""
assert reader.isStartElement();
int level = -1;
while (reader.hasNext()) {
//keep track of level so we only search children, not descendants
if (reader.isStartElement()) {
level++;
} else if (reader.isEndElement()) {
level--;
}
if (level < 0) {
//end parent tag - no more children
break;
}
reader.next();
if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) {
return true; //found
}
}
return false; //got to end of parent element and not found
} | java | static boolean scanForChildTag(XMLStreamReader reader, String tagName)
throws XMLStreamException {
assert reader.isStartElement();
int level = -1;
while (reader.hasNext()) {
//keep track of level so we only search children, not descendants
if (reader.isStartElement()) {
level++;
} else if (reader.isEndElement()) {
level--;
}
if (level < 0) {
//end parent tag - no more children
break;
}
reader.next();
if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) {
return true; //found
}
}
return false; //got to end of parent element and not found
} | [
"static",
"boolean",
"scanForChildTag",
"(",
"XMLStreamReader",
"reader",
",",
"String",
"tagName",
")",
"throws",
"XMLStreamException",
"{",
"assert",
"reader",
".",
"isStartElement",
"(",
")",
";",
"int",
"level",
"=",
"-",
"1",
";",
"while",
"(",
"reader",
".",
"hasNext",
"(",
")",
")",
"{",
"//keep track of level so we only search children, not descendants\r",
"if",
"(",
"reader",
".",
"isStartElement",
"(",
")",
")",
"{",
"level",
"++",
";",
"}",
"else",
"if",
"(",
"reader",
".",
"isEndElement",
"(",
")",
")",
"{",
"level",
"--",
";",
"}",
"if",
"(",
"level",
"<",
"0",
")",
"{",
"//end parent tag - no more children\r",
"break",
";",
"}",
"reader",
".",
"next",
"(",
")",
";",
"if",
"(",
"level",
"==",
"0",
"&&",
"reader",
".",
"isStartElement",
"(",
")",
"&&",
"reader",
".",
"getLocalName",
"(",
")",
".",
"equals",
"(",
"tagName",
")",
")",
"{",
"return",
"true",
";",
"//found\r",
"}",
"}",
"return",
"false",
";",
"//got to end of parent element and not found\r",
"}"
]
| Scan xml for tag child of the current element
@param reader reader, must be at "start element" @nonnull
@param tagName name of child tag to find @nonnull
@return if found tag
@throws XMLStreamException on error | [
"Scan",
"xml",
"for",
"tag",
"child",
"of",
"the",
"current",
"element"
]
| train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L201-L225 |
samskivert/samskivert | src/main/java/com/samskivert/velocity/FormTool.java | FormTool.imageSubmit | public String imageSubmit (String name, String value, String imagePath) {
"""
Constructs a image submit element with the specified parameter name
and image path.
"""
return fixedInput("image", name, value, "src=\"" + imagePath + "\"");
} | java | public String imageSubmit (String name, String value, String imagePath)
{
return fixedInput("image", name, value, "src=\"" + imagePath + "\"");
} | [
"public",
"String",
"imageSubmit",
"(",
"String",
"name",
",",
"String",
"value",
",",
"String",
"imagePath",
")",
"{",
"return",
"fixedInput",
"(",
"\"image\"",
",",
"name",
",",
"value",
",",
"\"src=\\\"\"",
"+",
"imagePath",
"+",
"\"\\\"\"",
")",
";",
"}"
]
| Constructs a image submit element with the specified parameter name
and image path. | [
"Constructs",
"a",
"image",
"submit",
"element",
"with",
"the",
"specified",
"parameter",
"name",
"and",
"image",
"path",
"."
]
| train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/FormTool.java#L194-L197 |
EasyinnovaSL/Tiff-Library-4J | src/main/java/com/easyinnova/tiff/profiles/BaselineProfile.java | BaselineProfile.CheckPalleteImage | private void CheckPalleteImage(IfdTags metadata, int nifd) {
"""
Check Pallete Color Image.
@param metadata the metadata
@param nifd the IFD number
"""
// Color Map
if (!metadata.containsTagId(TiffTags.getTagId("ColorMap"))) {
validation.addErrorLoc("Missing Color Map", "IFD" + nifd);
} else {
int n = metadata.get(TiffTags.getTagId("ColorMap")).getCardinality();
if (n != 3 * (int) Math.pow(2, metadata.get(TiffTags.getTagId("BitsPerSample"))
.getFirstNumericValue()))
validation.addError("Incorrect Color Map Cardinality", "IFD" + nifd, metadata.get(320)
.getCardinality());
}
// Bits per Sample
long bps = metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
if (bps != 4 && bps != 8)
validation.addError("Invalid Bits per Sample", "IFD" + nifd, bps);
// Compression
long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
// if (comp != 1 && comp != 32773)
if (comp < 1)
validation.addError("Invalid Compression", "IFD" + nifd, comp);
} | java | private void CheckPalleteImage(IfdTags metadata, int nifd) {
// Color Map
if (!metadata.containsTagId(TiffTags.getTagId("ColorMap"))) {
validation.addErrorLoc("Missing Color Map", "IFD" + nifd);
} else {
int n = metadata.get(TiffTags.getTagId("ColorMap")).getCardinality();
if (n != 3 * (int) Math.pow(2, metadata.get(TiffTags.getTagId("BitsPerSample"))
.getFirstNumericValue()))
validation.addError("Incorrect Color Map Cardinality", "IFD" + nifd, metadata.get(320)
.getCardinality());
}
// Bits per Sample
long bps = metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
if (bps != 4 && bps != 8)
validation.addError("Invalid Bits per Sample", "IFD" + nifd, bps);
// Compression
long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
// if (comp != 1 && comp != 32773)
if (comp < 1)
validation.addError("Invalid Compression", "IFD" + nifd, comp);
} | [
"private",
"void",
"CheckPalleteImage",
"(",
"IfdTags",
"metadata",
",",
"int",
"nifd",
")",
"{",
"// Color Map",
"if",
"(",
"!",
"metadata",
".",
"containsTagId",
"(",
"TiffTags",
".",
"getTagId",
"(",
"\"ColorMap\"",
")",
")",
")",
"{",
"validation",
".",
"addErrorLoc",
"(",
"\"Missing Color Map\"",
",",
"\"IFD\"",
"+",
"nifd",
")",
";",
"}",
"else",
"{",
"int",
"n",
"=",
"metadata",
".",
"get",
"(",
"TiffTags",
".",
"getTagId",
"(",
"\"ColorMap\"",
")",
")",
".",
"getCardinality",
"(",
")",
";",
"if",
"(",
"n",
"!=",
"3",
"*",
"(",
"int",
")",
"Math",
".",
"pow",
"(",
"2",
",",
"metadata",
".",
"get",
"(",
"TiffTags",
".",
"getTagId",
"(",
"\"BitsPerSample\"",
")",
")",
".",
"getFirstNumericValue",
"(",
")",
")",
")",
"validation",
".",
"addError",
"(",
"\"Incorrect Color Map Cardinality\"",
",",
"\"IFD\"",
"+",
"nifd",
",",
"metadata",
".",
"get",
"(",
"320",
")",
".",
"getCardinality",
"(",
")",
")",
";",
"}",
"// Bits per Sample",
"long",
"bps",
"=",
"metadata",
".",
"get",
"(",
"TiffTags",
".",
"getTagId",
"(",
"\"BitsPerSample\"",
")",
")",
".",
"getFirstNumericValue",
"(",
")",
";",
"if",
"(",
"bps",
"!=",
"4",
"&&",
"bps",
"!=",
"8",
")",
"validation",
".",
"addError",
"(",
"\"Invalid Bits per Sample\"",
",",
"\"IFD\"",
"+",
"nifd",
",",
"bps",
")",
";",
"// Compression",
"long",
"comp",
"=",
"metadata",
".",
"get",
"(",
"TiffTags",
".",
"getTagId",
"(",
"\"Compression\"",
")",
")",
".",
"getFirstNumericValue",
"(",
")",
";",
"// if (comp != 1 && comp != 32773)",
"if",
"(",
"comp",
"<",
"1",
")",
"validation",
".",
"addError",
"(",
"\"Invalid Compression\"",
",",
"\"IFD\"",
"+",
"nifd",
",",
"comp",
")",
";",
"}"
]
| Check Pallete Color Image.
@param metadata the metadata
@param nifd the IFD number | [
"Check",
"Pallete",
"Color",
"Image",
"."
]
| train | https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/profiles/BaselineProfile.java#L288-L310 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/message/event/ModelMessageHandler.java | ModelMessageHandler.init | public void init(BaseMessageReceiver messageReceiver, AbstractTableModel model) {
"""
Constructor.
@param messageReceiver The message receiver that this listener is added to.
@param model The target table model.
"""
super.init(messageReceiver, null);
m_model = model;
} | java | public void init(BaseMessageReceiver messageReceiver, AbstractTableModel model)
{
super.init(messageReceiver, null);
m_model = model;
} | [
"public",
"void",
"init",
"(",
"BaseMessageReceiver",
"messageReceiver",
",",
"AbstractTableModel",
"model",
")",
"{",
"super",
".",
"init",
"(",
"messageReceiver",
",",
"null",
")",
";",
"m_model",
"=",
"model",
";",
"}"
]
| Constructor.
@param messageReceiver The message receiver that this listener is added to.
@param model The target table model. | [
"Constructor",
"."
]
| train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/message/event/ModelMessageHandler.java#L74-L78 |
javamelody/javamelody | javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java | PayloadNameRequestWrapper.parseSoapMethodName | private static String parseSoapMethodName(InputStream stream, String charEncoding) {
"""
Try to parse SOAP method name from request body stream. Does not close the stream.
@param stream SOAP request body stream @nonnull
@param charEncoding character encoding of stream, or null for platform default @null
@return SOAP method name, or null if unable to parse @null
"""
try {
// newInstance() et pas newFactory() pour java 1.5 (issue 367)
final XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities
final XMLStreamReader xmlReader;
if (charEncoding != null) {
xmlReader = factory.createXMLStreamReader(stream, charEncoding);
} else {
xmlReader = factory.createXMLStreamReader(stream);
}
//best-effort parsing
//start document, go to first tag
xmlReader.nextTag();
//expect first tag to be "Envelope"
if (!"Envelope".equals(xmlReader.getLocalName())) {
LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName()
+ "' (expected 'Envelope')");
return null; //failed
}
//scan for body tag
if (!scanForChildTag(xmlReader, "Body")) {
LOG.debug("Unable to find SOAP 'Body' tag");
return null; //failed
}
xmlReader.nextTag();
//tag is method name
return "." + xmlReader.getLocalName();
} catch (final XMLStreamException e) {
LOG.debug("Unable to parse SOAP request", e);
//failed
return null;
}
} | java | private static String parseSoapMethodName(InputStream stream, String charEncoding) {
try {
// newInstance() et pas newFactory() pour java 1.5 (issue 367)
final XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities
final XMLStreamReader xmlReader;
if (charEncoding != null) {
xmlReader = factory.createXMLStreamReader(stream, charEncoding);
} else {
xmlReader = factory.createXMLStreamReader(stream);
}
//best-effort parsing
//start document, go to first tag
xmlReader.nextTag();
//expect first tag to be "Envelope"
if (!"Envelope".equals(xmlReader.getLocalName())) {
LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName()
+ "' (expected 'Envelope')");
return null; //failed
}
//scan for body tag
if (!scanForChildTag(xmlReader, "Body")) {
LOG.debug("Unable to find SOAP 'Body' tag");
return null; //failed
}
xmlReader.nextTag();
//tag is method name
return "." + xmlReader.getLocalName();
} catch (final XMLStreamException e) {
LOG.debug("Unable to parse SOAP request", e);
//failed
return null;
}
} | [
"private",
"static",
"String",
"parseSoapMethodName",
"(",
"InputStream",
"stream",
",",
"String",
"charEncoding",
")",
"{",
"try",
"{",
"// newInstance() et pas newFactory() pour java 1.5 (issue 367)\r",
"final",
"XMLInputFactory",
"factory",
"=",
"XMLInputFactory",
".",
"newInstance",
"(",
")",
";",
"factory",
".",
"setProperty",
"(",
"XMLInputFactory",
".",
"SUPPORT_DTD",
",",
"false",
")",
";",
"// disable DTDs entirely for that factory\r",
"factory",
".",
"setProperty",
"(",
"XMLInputFactory",
".",
"IS_SUPPORTING_EXTERNAL_ENTITIES",
",",
"false",
")",
";",
"// disable external entities\r",
"final",
"XMLStreamReader",
"xmlReader",
";",
"if",
"(",
"charEncoding",
"!=",
"null",
")",
"{",
"xmlReader",
"=",
"factory",
".",
"createXMLStreamReader",
"(",
"stream",
",",
"charEncoding",
")",
";",
"}",
"else",
"{",
"xmlReader",
"=",
"factory",
".",
"createXMLStreamReader",
"(",
"stream",
")",
";",
"}",
"//best-effort parsing\r",
"//start document, go to first tag\r",
"xmlReader",
".",
"nextTag",
"(",
")",
";",
"//expect first tag to be \"Envelope\"\r",
"if",
"(",
"!",
"\"Envelope\"",
".",
"equals",
"(",
"xmlReader",
".",
"getLocalName",
"(",
")",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Unexpected first tag of SOAP request: '\"",
"+",
"xmlReader",
".",
"getLocalName",
"(",
")",
"+",
"\"' (expected 'Envelope')\"",
")",
";",
"return",
"null",
";",
"//failed\r",
"}",
"//scan for body tag\r",
"if",
"(",
"!",
"scanForChildTag",
"(",
"xmlReader",
",",
"\"Body\"",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Unable to find SOAP 'Body' tag\"",
")",
";",
"return",
"null",
";",
"//failed\r",
"}",
"xmlReader",
".",
"nextTag",
"(",
")",
";",
"//tag is method name\r",
"return",
"\".\"",
"+",
"xmlReader",
".",
"getLocalName",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"XMLStreamException",
"e",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Unable to parse SOAP request\"",
",",
"e",
")",
";",
"//failed\r",
"return",
"null",
";",
"}",
"}"
]
| Try to parse SOAP method name from request body stream. Does not close the stream.
@param stream SOAP request body stream @nonnull
@param charEncoding character encoding of stream, or null for platform default @null
@return SOAP method name, or null if unable to parse @null | [
"Try",
"to",
"parse",
"SOAP",
"method",
"name",
"from",
"request",
"body",
"stream",
".",
"Does",
"not",
"close",
"the",
"stream",
"."
]
| train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/PayloadNameRequestWrapper.java#L234-L274 |
openbase/jul | exception/src/main/java/org/openbase/jul/exception/MultiException.java | MultiException.checkAndThrow | public static void checkAndThrow(final Callable<String> messageProvider, final ExceptionStack exceptionStack) throws MultiException {
"""
Method throws an exception if the given {@code exceptionStack} contains any exceptions, otherwise this method has no effect.
<p>
Note: The message provider is only used in case the {@code MultiException} is generated, which means any operations within the call body are only performed in case of an exception.
@param messageProvider the message provider is used to deliver the {@code MultiException} headline message in case the {@code exceptionStack} contains any exceptions.
@param exceptionStack the stack to check.
@throws MultiException is thrown if the {@code exceptionStack} contains any exceptions.
"""
if (exceptionStack == null || exceptionStack.isEmpty()) {
return;
}
String message;
try {
message = messageProvider.call();
} catch (Exception ex) {
message = "?";
ExceptionPrinter.printHistory(new NotAvailableException("MultiException", "Message", ex), LOGGER);
}
throw new MultiException(message, exceptionStack);
} | java | public static void checkAndThrow(final Callable<String> messageProvider, final ExceptionStack exceptionStack) throws MultiException {
if (exceptionStack == null || exceptionStack.isEmpty()) {
return;
}
String message;
try {
message = messageProvider.call();
} catch (Exception ex) {
message = "?";
ExceptionPrinter.printHistory(new NotAvailableException("MultiException", "Message", ex), LOGGER);
}
throw new MultiException(message, exceptionStack);
} | [
"public",
"static",
"void",
"checkAndThrow",
"(",
"final",
"Callable",
"<",
"String",
">",
"messageProvider",
",",
"final",
"ExceptionStack",
"exceptionStack",
")",
"throws",
"MultiException",
"{",
"if",
"(",
"exceptionStack",
"==",
"null",
"||",
"exceptionStack",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"String",
"message",
";",
"try",
"{",
"message",
"=",
"messageProvider",
".",
"call",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"message",
"=",
"\"?\"",
";",
"ExceptionPrinter",
".",
"printHistory",
"(",
"new",
"NotAvailableException",
"(",
"\"MultiException\"",
",",
"\"Message\"",
",",
"ex",
")",
",",
"LOGGER",
")",
";",
"}",
"throw",
"new",
"MultiException",
"(",
"message",
",",
"exceptionStack",
")",
";",
"}"
]
| Method throws an exception if the given {@code exceptionStack} contains any exceptions, otherwise this method has no effect.
<p>
Note: The message provider is only used in case the {@code MultiException} is generated, which means any operations within the call body are only performed in case of an exception.
@param messageProvider the message provider is used to deliver the {@code MultiException} headline message in case the {@code exceptionStack} contains any exceptions.
@param exceptionStack the stack to check.
@throws MultiException is thrown if the {@code exceptionStack} contains any exceptions. | [
"Method",
"throws",
"an",
"exception",
"if",
"the",
"given",
"{",
"@code",
"exceptionStack",
"}",
"contains",
"any",
"exceptions",
"otherwise",
"this",
"method",
"has",
"no",
"effect",
".",
"<p",
">",
"Note",
":",
"The",
"message",
"provider",
"is",
"only",
"used",
"in",
"case",
"the",
"{",
"@code",
"MultiException",
"}",
"is",
"generated",
"which",
"means",
"any",
"operations",
"within",
"the",
"call",
"body",
"are",
"only",
"performed",
"in",
"case",
"of",
"an",
"exception",
"."
]
| train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/MultiException.java#L70-L83 |
ironjacamar/ironjacamar | core/src/main/java/org/ironjacamar/core/tracer/Tracer.java | Tracer.destroyManagedConnectionPool | public static synchronized void destroyManagedConnectionPool(String poolName, Object mcp) {
"""
Destroy managed connection pool
@param poolName The name of the pool
@param mcp The managed connection pool
"""
log.tracef("%s", new TraceEvent(poolName,
Integer.toHexString(System.identityHashCode(mcp)),
TraceEvent.MANAGED_CONNECTION_POOL_DESTROY,
"NONE"));
} | java | public static synchronized void destroyManagedConnectionPool(String poolName, Object mcp)
{
log.tracef("%s", new TraceEvent(poolName,
Integer.toHexString(System.identityHashCode(mcp)),
TraceEvent.MANAGED_CONNECTION_POOL_DESTROY,
"NONE"));
} | [
"public",
"static",
"synchronized",
"void",
"destroyManagedConnectionPool",
"(",
"String",
"poolName",
",",
"Object",
"mcp",
")",
"{",
"log",
".",
"tracef",
"(",
"\"%s\"",
",",
"new",
"TraceEvent",
"(",
"poolName",
",",
"Integer",
".",
"toHexString",
"(",
"System",
".",
"identityHashCode",
"(",
"mcp",
")",
")",
",",
"TraceEvent",
".",
"MANAGED_CONNECTION_POOL_DESTROY",
",",
"\"NONE\"",
")",
")",
";",
"}"
]
| Destroy managed connection pool
@param poolName The name of the pool
@param mcp The managed connection pool | [
"Destroy",
"managed",
"connection",
"pool"
]
| train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/tracer/Tracer.java#L571-L577 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_storage_containerId_cors_DELETE | public void project_serviceName_storage_containerId_cors_DELETE(String serviceName, String containerId, String origin) throws IOException {
"""
Delete CORS support on your container
REST: DELETE /cloud/project/{serviceName}/storage/{containerId}/cors
@param containerId [required] Container id
@param origin [required] Delete this origin
@param serviceName [required] Service name
"""
String qPath = "/cloud/project/{serviceName}/storage/{containerId}/cors";
StringBuilder sb = path(qPath, serviceName, containerId);
query(sb, "origin", origin);
exec(qPath, "DELETE", sb.toString(), null);
} | java | public void project_serviceName_storage_containerId_cors_DELETE(String serviceName, String containerId, String origin) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage/{containerId}/cors";
StringBuilder sb = path(qPath, serviceName, containerId);
query(sb, "origin", origin);
exec(qPath, "DELETE", sb.toString(), null);
} | [
"public",
"void",
"project_serviceName_storage_containerId_cors_DELETE",
"(",
"String",
"serviceName",
",",
"String",
"containerId",
",",
"String",
"origin",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/storage/{containerId}/cors\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"containerId",
")",
";",
"query",
"(",
"sb",
",",
"\"origin\"",
",",
"origin",
")",
";",
"exec",
"(",
"qPath",
",",
"\"DELETE\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"}"
]
| Delete CORS support on your container
REST: DELETE /cloud/project/{serviceName}/storage/{containerId}/cors
@param containerId [required] Container id
@param origin [required] Delete this origin
@param serviceName [required] Service name | [
"Delete",
"CORS",
"support",
"on",
"your",
"container"
]
| train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L650-L655 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/core/mtc/MessageToClientManager.java | MessageToClientManager.injectSession | void injectSession(Class<?>[] parameterTypes, List<Object> arguments, T session) {
"""
Inject Session or HttpSession if necessary
@param parameterTypes
@param arguments
@param session
"""
if (parameterTypes != null) {
int i = 0;
for (Class<?> parameterType : parameterTypes) {
if (parameterType.isInstance(session)) {
arguments.set(i, session);
break;
}
i++;
}
}
} | java | void injectSession(Class<?>[] parameterTypes, List<Object> arguments, T session) {
if (parameterTypes != null) {
int i = 0;
for (Class<?> parameterType : parameterTypes) {
if (parameterType.isInstance(session)) {
arguments.set(i, session);
break;
}
i++;
}
}
} | [
"void",
"injectSession",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
",",
"List",
"<",
"Object",
">",
"arguments",
",",
"T",
"session",
")",
"{",
"if",
"(",
"parameterTypes",
"!=",
"null",
")",
"{",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"parameterType",
":",
"parameterTypes",
")",
"{",
"if",
"(",
"parameterType",
".",
"isInstance",
"(",
"session",
")",
")",
"{",
"arguments",
".",
"set",
"(",
"i",
",",
"session",
")",
";",
"break",
";",
"}",
"i",
"++",
";",
"}",
"}",
"}"
]
| Inject Session or HttpSession if necessary
@param parameterTypes
@param arguments
@param session | [
"Inject",
"Session",
"or",
"HttpSession",
"if",
"necessary"
]
| train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/core/mtc/MessageToClientManager.java#L174-L185 |
bugsnag/bugsnag-java | bugsnag/src/main/java/com/bugsnag/Bugsnag.java | Bugsnag.setEndpoints | public void setEndpoints(String notify, String sessions) throws IllegalArgumentException {
"""
Set the endpoints to send data to. By default we'll send error reports to
https://notify.bugsnag.com, and sessions to https://sessions.bugsnag.com, but you can
override this if you are using Bugsnag Enterprise to point to your own Bugsnag endpoint.
Please note that it is recommended that you set both endpoints. If the notify endpoint is
missing, an exception will be thrown. If the session endpoint is missing, a warning will be
logged and sessions will not be sent automatically.
Note that if you are setting a custom {@link Delivery}, this method should be called after
the custom implementation has been set.
@param notify the notify endpoint
@param sessions the sessions endpoint
@throws IllegalArgumentException if the notify endpoint is empty or null
"""
config.setEndpoints(notify, sessions);
} | java | public void setEndpoints(String notify, String sessions) throws IllegalArgumentException {
config.setEndpoints(notify, sessions);
} | [
"public",
"void",
"setEndpoints",
"(",
"String",
"notify",
",",
"String",
"sessions",
")",
"throws",
"IllegalArgumentException",
"{",
"config",
".",
"setEndpoints",
"(",
"notify",
",",
"sessions",
")",
";",
"}"
]
| Set the endpoints to send data to. By default we'll send error reports to
https://notify.bugsnag.com, and sessions to https://sessions.bugsnag.com, but you can
override this if you are using Bugsnag Enterprise to point to your own Bugsnag endpoint.
Please note that it is recommended that you set both endpoints. If the notify endpoint is
missing, an exception will be thrown. If the session endpoint is missing, a warning will be
logged and sessions will not be sent automatically.
Note that if you are setting a custom {@link Delivery}, this method should be called after
the custom implementation has been set.
@param notify the notify endpoint
@param sessions the sessions endpoint
@throws IllegalArgumentException if the notify endpoint is empty or null | [
"Set",
"the",
"endpoints",
"to",
"send",
"data",
"to",
".",
"By",
"default",
"we",
"ll",
"send",
"error",
"reports",
"to",
"https",
":",
"//",
"notify",
".",
"bugsnag",
".",
"com",
"and",
"sessions",
"to",
"https",
":",
"//",
"sessions",
".",
"bugsnag",
".",
"com",
"but",
"you",
"can",
"override",
"this",
"if",
"you",
"are",
"using",
"Bugsnag",
"Enterprise",
"to",
"point",
"to",
"your",
"own",
"Bugsnag",
"endpoint",
"."
]
| train | https://github.com/bugsnag/bugsnag-java/blob/11817d63949bcf2b2b6b765a1d37305cdec356f2/bugsnag/src/main/java/com/bugsnag/Bugsnag.java#L592-L594 |
BlueBrain/bluima | modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java | diff_match_patch.diff_main | private LinkedList<Diff> diff_main(String text1, String text2,
boolean checklines, long deadline) {
"""
Find the differences between two texts. Simplifies the problem by
stripping any common prefix or suffix off the texts before diffing.
@param text1
Old string to be diffed.
@param text2
New string to be diffed.
@param checklines
Speedup flag. If false, then don't run a line-level diff first
to identify the changed areas. If true, then run a faster
slightly less optimal diff.
@param deadline
Time when the diff should be complete by. Used internally for
recursive calls. Users should set DiffTimeout instead.
@return Linked List of Diff objects.
"""
// Check for null inputs.
if (text1 == null || text2 == null) {
throw new IllegalArgumentException("Null inputs. (diff_main)");
}
// Check for equality (speedup).
LinkedList<Diff> diffs;
if (text1.equals(text2)) {
diffs = new LinkedList<Diff>();
if (text1.length() != 0) {
diffs.add(new Diff(Operation.EQUAL, text1));
}
return diffs;
}
// Trim off common prefix (speedup).
int commonlength = diff_commonPrefix(text1, text2);
String commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = diff_commonSuffix(text1, text2);
String commonsuffix = text1.substring(text1.length() - commonlength);
text1 = text1.substring(0, text1.length() - commonlength);
text2 = text2.substring(0, text2.length() - commonlength);
// Compute the diff on the middle block.
diffs = diff_compute(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix.length() != 0) {
diffs.addFirst(new Diff(Operation.EQUAL, commonprefix));
}
if (commonsuffix.length() != 0) {
diffs.addLast(new Diff(Operation.EQUAL, commonsuffix));
}
diff_cleanupMerge(diffs);
return diffs;
} | java | private LinkedList<Diff> diff_main(String text1, String text2,
boolean checklines, long deadline) {
// Check for null inputs.
if (text1 == null || text2 == null) {
throw new IllegalArgumentException("Null inputs. (diff_main)");
}
// Check for equality (speedup).
LinkedList<Diff> diffs;
if (text1.equals(text2)) {
diffs = new LinkedList<Diff>();
if (text1.length() != 0) {
diffs.add(new Diff(Operation.EQUAL, text1));
}
return diffs;
}
// Trim off common prefix (speedup).
int commonlength = diff_commonPrefix(text1, text2);
String commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = diff_commonSuffix(text1, text2);
String commonsuffix = text1.substring(text1.length() - commonlength);
text1 = text1.substring(0, text1.length() - commonlength);
text2 = text2.substring(0, text2.length() - commonlength);
// Compute the diff on the middle block.
diffs = diff_compute(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix.length() != 0) {
diffs.addFirst(new Diff(Operation.EQUAL, commonprefix));
}
if (commonsuffix.length() != 0) {
diffs.addLast(new Diff(Operation.EQUAL, commonsuffix));
}
diff_cleanupMerge(diffs);
return diffs;
} | [
"private",
"LinkedList",
"<",
"Diff",
">",
"diff_main",
"(",
"String",
"text1",
",",
"String",
"text2",
",",
"boolean",
"checklines",
",",
"long",
"deadline",
")",
"{",
"// Check for null inputs.",
"if",
"(",
"text1",
"==",
"null",
"||",
"text2",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Null inputs. (diff_main)\"",
")",
";",
"}",
"// Check for equality (speedup).",
"LinkedList",
"<",
"Diff",
">",
"diffs",
";",
"if",
"(",
"text1",
".",
"equals",
"(",
"text2",
")",
")",
"{",
"diffs",
"=",
"new",
"LinkedList",
"<",
"Diff",
">",
"(",
")",
";",
"if",
"(",
"text1",
".",
"length",
"(",
")",
"!=",
"0",
")",
"{",
"diffs",
".",
"add",
"(",
"new",
"Diff",
"(",
"Operation",
".",
"EQUAL",
",",
"text1",
")",
")",
";",
"}",
"return",
"diffs",
";",
"}",
"// Trim off common prefix (speedup).",
"int",
"commonlength",
"=",
"diff_commonPrefix",
"(",
"text1",
",",
"text2",
")",
";",
"String",
"commonprefix",
"=",
"text1",
".",
"substring",
"(",
"0",
",",
"commonlength",
")",
";",
"text1",
"=",
"text1",
".",
"substring",
"(",
"commonlength",
")",
";",
"text2",
"=",
"text2",
".",
"substring",
"(",
"commonlength",
")",
";",
"// Trim off common suffix (speedup).",
"commonlength",
"=",
"diff_commonSuffix",
"(",
"text1",
",",
"text2",
")",
";",
"String",
"commonsuffix",
"=",
"text1",
".",
"substring",
"(",
"text1",
".",
"length",
"(",
")",
"-",
"commonlength",
")",
";",
"text1",
"=",
"text1",
".",
"substring",
"(",
"0",
",",
"text1",
".",
"length",
"(",
")",
"-",
"commonlength",
")",
";",
"text2",
"=",
"text2",
".",
"substring",
"(",
"0",
",",
"text2",
".",
"length",
"(",
")",
"-",
"commonlength",
")",
";",
"// Compute the diff on the middle block.",
"diffs",
"=",
"diff_compute",
"(",
"text1",
",",
"text2",
",",
"checklines",
",",
"deadline",
")",
";",
"// Restore the prefix and suffix.",
"if",
"(",
"commonprefix",
".",
"length",
"(",
")",
"!=",
"0",
")",
"{",
"diffs",
".",
"addFirst",
"(",
"new",
"Diff",
"(",
"Operation",
".",
"EQUAL",
",",
"commonprefix",
")",
")",
";",
"}",
"if",
"(",
"commonsuffix",
".",
"length",
"(",
")",
"!=",
"0",
")",
"{",
"diffs",
".",
"addLast",
"(",
"new",
"Diff",
"(",
"Operation",
".",
"EQUAL",
",",
"commonsuffix",
")",
")",
";",
"}",
"diff_cleanupMerge",
"(",
"diffs",
")",
";",
"return",
"diffs",
";",
"}"
]
| Find the differences between two texts. Simplifies the problem by
stripping any common prefix or suffix off the texts before diffing.
@param text1
Old string to be diffed.
@param text2
New string to be diffed.
@param checklines
Speedup flag. If false, then don't run a line-level diff first
to identify the changed areas. If true, then run a faster
slightly less optimal diff.
@param deadline
Time when the diff should be complete by. Used internally for
recursive calls. Users should set DiffTimeout instead.
@return Linked List of Diff objects. | [
"Find",
"the",
"differences",
"between",
"two",
"texts",
".",
"Simplifies",
"the",
"problem",
"by",
"stripping",
"any",
"common",
"prefix",
"or",
"suffix",
"off",
"the",
"texts",
"before",
"diffing",
"."
]
| train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java#L177-L219 |
xwiki/xwiki-rendering | xwiki-rendering-macros/xwiki-rendering-macro-html/src/main/java/org/xwiki/rendering/internal/macro/html/HTMLMacro.java | HTMLMacro.renderWikiSyntax | private String renderWikiSyntax(String content, Transformation transformation, MacroTransformationContext context)
throws MacroExecutionException {
"""
Parse the passed context using a wiki syntax parser and render the result as an XHTML string.
@param content the content to parse
@param transformation the macro transformation to execute macros when wiki is set to true
@param context the context of the macros transformation process
@return the output XHTML as a string containing the XWiki Syntax resolved as XHTML
@throws MacroExecutionException in case there's a parsing problem
"""
String xhtml;
try {
// Parse the wiki syntax
XDOM xdom = this.contentParser.parse(content, context, false, false);
// Force clean=false for sub HTML macro:
// - at this point we don't know the context of the macro, it can be some <div> directly followed by the
// html macro, it this case the macro will be parsed as inline block
// - by forcing clean=false, we also make the html macro merge the whole html before cleaning so the cleaner
// have the chole context and can clean better
List<MacroBlock> macros = xdom.getBlocks(MACROBLOCKMATCHER, Axes.DESCENDANT);
for (MacroBlock macro : macros) {
if ("html".equals(macro.getId())) {
macro.setParameter("clean", "false");
}
}
MacroBlock htmlMacroBlock = context.getCurrentMacroBlock();
MacroMarkerBlock htmlMacroMarker =
new MacroMarkerBlock(htmlMacroBlock.getId(), htmlMacroBlock.getParameters(),
htmlMacroBlock.getContent(), xdom.getChildren(), htmlMacroBlock.isInline());
// Make sure the context XDOM contains the html macro content
htmlMacroBlock.getParent().replaceChild(htmlMacroMarker, htmlMacroBlock);
try {
// Execute the Macro transformation
((MutableRenderingContext) this.renderingContext).transformInContext(transformation,
context.getTransformationContext(), htmlMacroMarker);
} finally {
// Restore context XDOM to its previous state
htmlMacroMarker.getParent().replaceChild(htmlMacroBlock, htmlMacroMarker);
}
// Render the whole parsed content as a XHTML string
WikiPrinter printer = new DefaultWikiPrinter();
PrintRenderer renderer = this.xhtmlRendererFactory.createRenderer(printer);
for (Block block : htmlMacroMarker.getChildren()) {
block.traverse(renderer);
}
xhtml = printer.toString();
} catch (Exception e) {
throw new MacroExecutionException("Failed to parse content [" + content + "].", e);
}
return xhtml;
} | java | private String renderWikiSyntax(String content, Transformation transformation, MacroTransformationContext context)
throws MacroExecutionException
{
String xhtml;
try {
// Parse the wiki syntax
XDOM xdom = this.contentParser.parse(content, context, false, false);
// Force clean=false for sub HTML macro:
// - at this point we don't know the context of the macro, it can be some <div> directly followed by the
// html macro, it this case the macro will be parsed as inline block
// - by forcing clean=false, we also make the html macro merge the whole html before cleaning so the cleaner
// have the chole context and can clean better
List<MacroBlock> macros = xdom.getBlocks(MACROBLOCKMATCHER, Axes.DESCENDANT);
for (MacroBlock macro : macros) {
if ("html".equals(macro.getId())) {
macro.setParameter("clean", "false");
}
}
MacroBlock htmlMacroBlock = context.getCurrentMacroBlock();
MacroMarkerBlock htmlMacroMarker =
new MacroMarkerBlock(htmlMacroBlock.getId(), htmlMacroBlock.getParameters(),
htmlMacroBlock.getContent(), xdom.getChildren(), htmlMacroBlock.isInline());
// Make sure the context XDOM contains the html macro content
htmlMacroBlock.getParent().replaceChild(htmlMacroMarker, htmlMacroBlock);
try {
// Execute the Macro transformation
((MutableRenderingContext) this.renderingContext).transformInContext(transformation,
context.getTransformationContext(), htmlMacroMarker);
} finally {
// Restore context XDOM to its previous state
htmlMacroMarker.getParent().replaceChild(htmlMacroBlock, htmlMacroMarker);
}
// Render the whole parsed content as a XHTML string
WikiPrinter printer = new DefaultWikiPrinter();
PrintRenderer renderer = this.xhtmlRendererFactory.createRenderer(printer);
for (Block block : htmlMacroMarker.getChildren()) {
block.traverse(renderer);
}
xhtml = printer.toString();
} catch (Exception e) {
throw new MacroExecutionException("Failed to parse content [" + content + "].", e);
}
return xhtml;
} | [
"private",
"String",
"renderWikiSyntax",
"(",
"String",
"content",
",",
"Transformation",
"transformation",
",",
"MacroTransformationContext",
"context",
")",
"throws",
"MacroExecutionException",
"{",
"String",
"xhtml",
";",
"try",
"{",
"// Parse the wiki syntax",
"XDOM",
"xdom",
"=",
"this",
".",
"contentParser",
".",
"parse",
"(",
"content",
",",
"context",
",",
"false",
",",
"false",
")",
";",
"// Force clean=false for sub HTML macro:",
"// - at this point we don't know the context of the macro, it can be some <div> directly followed by the",
"// html macro, it this case the macro will be parsed as inline block",
"// - by forcing clean=false, we also make the html macro merge the whole html before cleaning so the cleaner",
"// have the chole context and can clean better",
"List",
"<",
"MacroBlock",
">",
"macros",
"=",
"xdom",
".",
"getBlocks",
"(",
"MACROBLOCKMATCHER",
",",
"Axes",
".",
"DESCENDANT",
")",
";",
"for",
"(",
"MacroBlock",
"macro",
":",
"macros",
")",
"{",
"if",
"(",
"\"html\"",
".",
"equals",
"(",
"macro",
".",
"getId",
"(",
")",
")",
")",
"{",
"macro",
".",
"setParameter",
"(",
"\"clean\"",
",",
"\"false\"",
")",
";",
"}",
"}",
"MacroBlock",
"htmlMacroBlock",
"=",
"context",
".",
"getCurrentMacroBlock",
"(",
")",
";",
"MacroMarkerBlock",
"htmlMacroMarker",
"=",
"new",
"MacroMarkerBlock",
"(",
"htmlMacroBlock",
".",
"getId",
"(",
")",
",",
"htmlMacroBlock",
".",
"getParameters",
"(",
")",
",",
"htmlMacroBlock",
".",
"getContent",
"(",
")",
",",
"xdom",
".",
"getChildren",
"(",
")",
",",
"htmlMacroBlock",
".",
"isInline",
"(",
")",
")",
";",
"// Make sure the context XDOM contains the html macro content",
"htmlMacroBlock",
".",
"getParent",
"(",
")",
".",
"replaceChild",
"(",
"htmlMacroMarker",
",",
"htmlMacroBlock",
")",
";",
"try",
"{",
"// Execute the Macro transformation",
"(",
"(",
"MutableRenderingContext",
")",
"this",
".",
"renderingContext",
")",
".",
"transformInContext",
"(",
"transformation",
",",
"context",
".",
"getTransformationContext",
"(",
")",
",",
"htmlMacroMarker",
")",
";",
"}",
"finally",
"{",
"// Restore context XDOM to its previous state",
"htmlMacroMarker",
".",
"getParent",
"(",
")",
".",
"replaceChild",
"(",
"htmlMacroBlock",
",",
"htmlMacroMarker",
")",
";",
"}",
"// Render the whole parsed content as a XHTML string",
"WikiPrinter",
"printer",
"=",
"new",
"DefaultWikiPrinter",
"(",
")",
";",
"PrintRenderer",
"renderer",
"=",
"this",
".",
"xhtmlRendererFactory",
".",
"createRenderer",
"(",
"printer",
")",
";",
"for",
"(",
"Block",
"block",
":",
"htmlMacroMarker",
".",
"getChildren",
"(",
")",
")",
"{",
"block",
".",
"traverse",
"(",
"renderer",
")",
";",
"}",
"xhtml",
"=",
"printer",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"MacroExecutionException",
"(",
"\"Failed to parse content [\"",
"+",
"content",
"+",
"\"].\"",
",",
"e",
")",
";",
"}",
"return",
"xhtml",
";",
"}"
]
| Parse the passed context using a wiki syntax parser and render the result as an XHTML string.
@param content the content to parse
@param transformation the macro transformation to execute macros when wiki is set to true
@param context the context of the macros transformation process
@return the output XHTML as a string containing the XWiki Syntax resolved as XHTML
@throws MacroExecutionException in case there's a parsing problem | [
"Parse",
"the",
"passed",
"context",
"using",
"a",
"wiki",
"syntax",
"parser",
"and",
"render",
"the",
"result",
"as",
"an",
"XHTML",
"string",
"."
]
| train | https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-macros/xwiki-rendering-macro-html/src/main/java/org/xwiki/rendering/internal/macro/html/HTMLMacro.java#L242-L295 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBQuery.java | DBQuery.notIn | public static Query notIn(String field, Object... values) {
"""
The field is not in the given set of values
@param field The field to compare
@param values The value to compare to
@return the query
"""
return new Query().notIn(field, values);
} | java | public static Query notIn(String field, Object... values) {
return new Query().notIn(field, values);
} | [
"public",
"static",
"Query",
"notIn",
"(",
"String",
"field",
",",
"Object",
"...",
"values",
")",
"{",
"return",
"new",
"Query",
"(",
")",
".",
"notIn",
"(",
"field",
",",
"values",
")",
";",
"}"
]
| The field is not in the given set of values
@param field The field to compare
@param values The value to compare to
@return the query | [
"The",
"field",
"is",
"not",
"in",
"the",
"given",
"set",
"of",
"values"
]
| train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBQuery.java#L139-L141 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java | CPInstancePersistenceImpl.findByCompanyId | @Override
public List<CPInstance> findByCompanyId(long companyId, int start, int end) {
"""
Returns a range of all the cp instances where companyId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPInstanceModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param companyId the company ID
@param start the lower bound of the range of cp instances
@param end the upper bound of the range of cp instances (not inclusive)
@return the range of matching cp instances
"""
return findByCompanyId(companyId, start, end, null);
} | java | @Override
public List<CPInstance> findByCompanyId(long companyId, int start, int end) {
return findByCompanyId(companyId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPInstance",
">",
"findByCompanyId",
"(",
"long",
"companyId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCompanyId",
"(",
"companyId",
",",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
]
| Returns a range of all the cp instances where companyId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPInstanceModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param companyId the company ID
@param start the lower bound of the range of cp instances
@param end the upper bound of the range of cp instances (not inclusive)
@return the range of matching cp instances | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"instances",
"where",
"companyId",
"=",
"?",
";",
"."
]
| train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L2028-L2031 |
bmwcarit/joynr | java/backend-services/domain-access-controller-jee/src/main/java/io/joynr/accesscontrol/global/jee/DomainRoleEntryManager.java | DomainRoleEntryManager.hasCurrentUserGotRoleForDomain | public boolean hasCurrentUserGotRoleForDomain(Role role, String domain) {
"""
Determine whether the joynr calling principal, if available, has the given role for the given domain.
The result will default to <code>true</code> if there is no current user - that is, the call is being
made from without of a {@link io.joynr.jeeintegration.api.JoynrJeeMessageScoped joynr calling scope}.
This way, the bean functionality can be used to create an admin API which doesn't require a user to
be already available in the database, e.g. for initial creation of security settings or providing a
RESTful API which is secured by other means.
@param role the role the user should have.
@param domain the domain for which the current user must have the role.
@return <code>true</code> if there is a current user, and that user has the specified role in the given
domain, <code>false</code> if there is a current user and they don't. <code>true</code> if there is no
current user.
"""
try {
DomainRoleEntryEntity domainRoleEntry = findByUserIdAndRole(joynrCallingPrincipal.getUsername(), role);
return domainRoleEntry != null && domainRoleEntry.getDomains().contains(domain);
} catch (ContextNotActiveException e) {
logger.debug("No joynr message scope context active. Defaulting to 'true'.");
}
return true;
} | java | public boolean hasCurrentUserGotRoleForDomain(Role role, String domain) {
try {
DomainRoleEntryEntity domainRoleEntry = findByUserIdAndRole(joynrCallingPrincipal.getUsername(), role);
return domainRoleEntry != null && domainRoleEntry.getDomains().contains(domain);
} catch (ContextNotActiveException e) {
logger.debug("No joynr message scope context active. Defaulting to 'true'.");
}
return true;
} | [
"public",
"boolean",
"hasCurrentUserGotRoleForDomain",
"(",
"Role",
"role",
",",
"String",
"domain",
")",
"{",
"try",
"{",
"DomainRoleEntryEntity",
"domainRoleEntry",
"=",
"findByUserIdAndRole",
"(",
"joynrCallingPrincipal",
".",
"getUsername",
"(",
")",
",",
"role",
")",
";",
"return",
"domainRoleEntry",
"!=",
"null",
"&&",
"domainRoleEntry",
".",
"getDomains",
"(",
")",
".",
"contains",
"(",
"domain",
")",
";",
"}",
"catch",
"(",
"ContextNotActiveException",
"e",
")",
"{",
"logger",
".",
"debug",
"(",
"\"No joynr message scope context active. Defaulting to 'true'.\"",
")",
";",
"}",
"return",
"true",
";",
"}"
]
| Determine whether the joynr calling principal, if available, has the given role for the given domain.
The result will default to <code>true</code> if there is no current user - that is, the call is being
made from without of a {@link io.joynr.jeeintegration.api.JoynrJeeMessageScoped joynr calling scope}.
This way, the bean functionality can be used to create an admin API which doesn't require a user to
be already available in the database, e.g. for initial creation of security settings or providing a
RESTful API which is secured by other means.
@param role the role the user should have.
@param domain the domain for which the current user must have the role.
@return <code>true</code> if there is a current user, and that user has the specified role in the given
domain, <code>false</code> if there is a current user and they don't. <code>true</code> if there is no
current user. | [
"Determine",
"whether",
"the",
"joynr",
"calling",
"principal",
"if",
"available",
"has",
"the",
"given",
"role",
"for",
"the",
"given",
"domain",
".",
"The",
"result",
"will",
"default",
"to",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"there",
"is",
"no",
"current",
"user",
"-",
"that",
"is",
"the",
"call",
"is",
"being",
"made",
"from",
"without",
"of",
"a",
"{",
"@link",
"io",
".",
"joynr",
".",
"jeeintegration",
".",
"api",
".",
"JoynrJeeMessageScoped",
"joynr",
"calling",
"scope",
"}",
".",
"This",
"way",
"the",
"bean",
"functionality",
"can",
"be",
"used",
"to",
"create",
"an",
"admin",
"API",
"which",
"doesn",
"t",
"require",
"a",
"user",
"to",
"be",
"already",
"available",
"in",
"the",
"database",
"e",
".",
"g",
".",
"for",
"initial",
"creation",
"of",
"security",
"settings",
"or",
"providing",
"a",
"RESTful",
"API",
"which",
"is",
"secured",
"by",
"other",
"means",
"."
]
| train | https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/backend-services/domain-access-controller-jee/src/main/java/io/joynr/accesscontrol/global/jee/DomainRoleEntryManager.java#L136-L144 |
datasalt/pangool | core/src/main/java/org/apache/avro/mapreduce/lib/output/AvroOutputFormat.java | AvroOutputFormat.setDeflateLevel | public static void setDeflateLevel(Job job, int level) {
"""
Enable output compression using the deflate codec and specify its level.
"""
FileOutputFormat.setCompressOutput(job, true);
job.getConfiguration().setInt(DEFLATE_LEVEL_KEY, level);
} | java | public static void setDeflateLevel(Job job, int level) {
FileOutputFormat.setCompressOutput(job, true);
job.getConfiguration().setInt(DEFLATE_LEVEL_KEY, level);
} | [
"public",
"static",
"void",
"setDeflateLevel",
"(",
"Job",
"job",
",",
"int",
"level",
")",
"{",
"FileOutputFormat",
".",
"setCompressOutput",
"(",
"job",
",",
"true",
")",
";",
"job",
".",
"getConfiguration",
"(",
")",
".",
"setInt",
"(",
"DEFLATE_LEVEL_KEY",
",",
"level",
")",
";",
"}"
]
| Enable output compression using the deflate codec and specify its level. | [
"Enable",
"output",
"compression",
"using",
"the",
"deflate",
"codec",
"and",
"specify",
"its",
"level",
"."
]
| train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/org/apache/avro/mapreduce/lib/output/AvroOutputFormat.java#L66-L69 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/ZipFile.java | ZipFile.getInputStream | public InputStream getInputStream(ZipEntry entry) throws IOException {
"""
Returns an input stream for reading the contents of the specified
zip file entry.
<p> Closing this ZIP file will, in turn, close all input
streams that have been returned by invocations of this method.
@param entry the zip file entry
@return the input stream for reading the contents of the specified
zip file entry.
@throws ZipException if a ZIP format error has occurred
@throws IOException if an I/O error has occurred
@throws IllegalStateException if the zip file has been closed
"""
if (entry == null) {
throw new NullPointerException("entry");
}
long jzentry = 0;
ZipFileInputStream in = null;
synchronized (this) {
ensureOpen();
if (!zc.isUTF8() && (entry.flag & EFS) != 0) {
jzentry = getEntry(jzfile, zc.getBytesUTF8(entry.name), true);
} else {
jzentry = getEntry(jzfile, zc.getBytes(entry.name), true);
}
if (jzentry == 0) {
return null;
}
in = new ZipFileInputStream(jzentry);
switch (getEntryMethod(jzentry)) {
case STORED:
synchronized (streams) {
streams.put(in, null);
}
return in;
case DEFLATED:
// MORE: Compute good size for inflater stream:
long size = getEntrySize(jzentry) + 2; // Inflater likes a bit of slack
if (size > 65536) size = 8192;
if (size <= 0) size = 4096;
Inflater inf = getInflater();
InputStream is =
new ZipFileInflaterInputStream(in, inf, (int)size);
synchronized (streams) {
streams.put(is, inf);
}
return is;
default:
throw new ZipException("invalid compression method");
}
}
} | java | public InputStream getInputStream(ZipEntry entry) throws IOException {
if (entry == null) {
throw new NullPointerException("entry");
}
long jzentry = 0;
ZipFileInputStream in = null;
synchronized (this) {
ensureOpen();
if (!zc.isUTF8() && (entry.flag & EFS) != 0) {
jzentry = getEntry(jzfile, zc.getBytesUTF8(entry.name), true);
} else {
jzentry = getEntry(jzfile, zc.getBytes(entry.name), true);
}
if (jzentry == 0) {
return null;
}
in = new ZipFileInputStream(jzentry);
switch (getEntryMethod(jzentry)) {
case STORED:
synchronized (streams) {
streams.put(in, null);
}
return in;
case DEFLATED:
// MORE: Compute good size for inflater stream:
long size = getEntrySize(jzentry) + 2; // Inflater likes a bit of slack
if (size > 65536) size = 8192;
if (size <= 0) size = 4096;
Inflater inf = getInflater();
InputStream is =
new ZipFileInflaterInputStream(in, inf, (int)size);
synchronized (streams) {
streams.put(is, inf);
}
return is;
default:
throw new ZipException("invalid compression method");
}
}
} | [
"public",
"InputStream",
"getInputStream",
"(",
"ZipEntry",
"entry",
")",
"throws",
"IOException",
"{",
"if",
"(",
"entry",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"entry\"",
")",
";",
"}",
"long",
"jzentry",
"=",
"0",
";",
"ZipFileInputStream",
"in",
"=",
"null",
";",
"synchronized",
"(",
"this",
")",
"{",
"ensureOpen",
"(",
")",
";",
"if",
"(",
"!",
"zc",
".",
"isUTF8",
"(",
")",
"&&",
"(",
"entry",
".",
"flag",
"&",
"EFS",
")",
"!=",
"0",
")",
"{",
"jzentry",
"=",
"getEntry",
"(",
"jzfile",
",",
"zc",
".",
"getBytesUTF8",
"(",
"entry",
".",
"name",
")",
",",
"true",
")",
";",
"}",
"else",
"{",
"jzentry",
"=",
"getEntry",
"(",
"jzfile",
",",
"zc",
".",
"getBytes",
"(",
"entry",
".",
"name",
")",
",",
"true",
")",
";",
"}",
"if",
"(",
"jzentry",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"in",
"=",
"new",
"ZipFileInputStream",
"(",
"jzentry",
")",
";",
"switch",
"(",
"getEntryMethod",
"(",
"jzentry",
")",
")",
"{",
"case",
"STORED",
":",
"synchronized",
"(",
"streams",
")",
"{",
"streams",
".",
"put",
"(",
"in",
",",
"null",
")",
";",
"}",
"return",
"in",
";",
"case",
"DEFLATED",
":",
"// MORE: Compute good size for inflater stream:",
"long",
"size",
"=",
"getEntrySize",
"(",
"jzentry",
")",
"+",
"2",
";",
"// Inflater likes a bit of slack",
"if",
"(",
"size",
">",
"65536",
")",
"size",
"=",
"8192",
";",
"if",
"(",
"size",
"<=",
"0",
")",
"size",
"=",
"4096",
";",
"Inflater",
"inf",
"=",
"getInflater",
"(",
")",
";",
"InputStream",
"is",
"=",
"new",
"ZipFileInflaterInputStream",
"(",
"in",
",",
"inf",
",",
"(",
"int",
")",
"size",
")",
";",
"synchronized",
"(",
"streams",
")",
"{",
"streams",
".",
"put",
"(",
"is",
",",
"inf",
")",
";",
"}",
"return",
"is",
";",
"default",
":",
"throw",
"new",
"ZipException",
"(",
"\"invalid compression method\"",
")",
";",
"}",
"}",
"}"
]
| Returns an input stream for reading the contents of the specified
zip file entry.
<p> Closing this ZIP file will, in turn, close all input
streams that have been returned by invocations of this method.
@param entry the zip file entry
@return the input stream for reading the contents of the specified
zip file entry.
@throws ZipException if a ZIP format error has occurred
@throws IOException if an I/O error has occurred
@throws IllegalStateException if the zip file has been closed | [
"Returns",
"an",
"input",
"stream",
"for",
"reading",
"the",
"contents",
"of",
"the",
"specified",
"zip",
"file",
"entry",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/ZipFile.java#L350-L390 |
fuinorg/units4j | src/main/java/org/fuin/units4j/dependency/Utils.java | Utils.findForbiddenByName | public static NotDependsOn findForbiddenByName(final List<NotDependsOn> forbidden, final String pkgName) {
"""
Find a dependency in a list by a package name.
@param forbidden
List to search.
@param pkgName
Name of the package to find - Cannot be <code>null</code>.
@return Entry or <code>null</code> if nothing was found.
"""
if (forbidden == null) {
return null;
}
Utils4J.checkNotNull("pkgName", pkgName);
for (int i = 0; i < forbidden.size(); i++) {
final NotDependsOn dep = forbidden.get(i);
if (pkgName.startsWith(dep.getPackageName())) {
if (dep.isIncludeSubPackages()) {
return dep;
} else {
if (pkgName.equals(dep.getPackageName())) {
return dep;
}
}
}
}
return null;
} | java | public static NotDependsOn findForbiddenByName(final List<NotDependsOn> forbidden, final String pkgName) {
if (forbidden == null) {
return null;
}
Utils4J.checkNotNull("pkgName", pkgName);
for (int i = 0; i < forbidden.size(); i++) {
final NotDependsOn dep = forbidden.get(i);
if (pkgName.startsWith(dep.getPackageName())) {
if (dep.isIncludeSubPackages()) {
return dep;
} else {
if (pkgName.equals(dep.getPackageName())) {
return dep;
}
}
}
}
return null;
} | [
"public",
"static",
"NotDependsOn",
"findForbiddenByName",
"(",
"final",
"List",
"<",
"NotDependsOn",
">",
"forbidden",
",",
"final",
"String",
"pkgName",
")",
"{",
"if",
"(",
"forbidden",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Utils4J",
".",
"checkNotNull",
"(",
"\"pkgName\"",
",",
"pkgName",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"forbidden",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"NotDependsOn",
"dep",
"=",
"forbidden",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"pkgName",
".",
"startsWith",
"(",
"dep",
".",
"getPackageName",
"(",
")",
")",
")",
"{",
"if",
"(",
"dep",
".",
"isIncludeSubPackages",
"(",
")",
")",
"{",
"return",
"dep",
";",
"}",
"else",
"{",
"if",
"(",
"pkgName",
".",
"equals",
"(",
"dep",
".",
"getPackageName",
"(",
")",
")",
")",
"{",
"return",
"dep",
";",
"}",
"}",
"}",
"}",
"return",
"null",
";",
"}"
]
| Find a dependency in a list by a package name.
@param forbidden
List to search.
@param pkgName
Name of the package to find - Cannot be <code>null</code>.
@return Entry or <code>null</code> if nothing was found. | [
"Find",
"a",
"dependency",
"in",
"a",
"list",
"by",
"a",
"package",
"name",
"."
]
| train | https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/dependency/Utils.java#L205-L223 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractAttributeValue | static void extractAttributeValue(Elements elementUtils, Element item, String annotationName, AnnotationAttributeType attribute, OnAttributeFoundListener listener) {
"""
Extract from an annotation of a method the attribute value specified.
@param elementUtils the element utils
@param item the item
@param annotationName the annotation name
@param attribute the attribute
@param listener the listener
"""
List<? extends AnnotationMirror> annotationList = elementUtils.getAllAnnotationMirrors(item);
for (AnnotationMirror annotation : annotationList) {
if (annotationName.equals(annotation.getAnnotationType().asElement().toString())) {
// found annotation
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> annotationItem : elementUtils.getElementValuesWithDefaults(annotation).entrySet()) {
if (attribute.isEquals(annotationItem.getKey())) {
listener.onFound(annotationItem.getValue().toString());
return;
}
}
}
}
} | java | static void extractAttributeValue(Elements elementUtils, Element item, String annotationName, AnnotationAttributeType attribute, OnAttributeFoundListener listener) {
List<? extends AnnotationMirror> annotationList = elementUtils.getAllAnnotationMirrors(item);
for (AnnotationMirror annotation : annotationList) {
if (annotationName.equals(annotation.getAnnotationType().asElement().toString())) {
// found annotation
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> annotationItem : elementUtils.getElementValuesWithDefaults(annotation).entrySet()) {
if (attribute.isEquals(annotationItem.getKey())) {
listener.onFound(annotationItem.getValue().toString());
return;
}
}
}
}
} | [
"static",
"void",
"extractAttributeValue",
"(",
"Elements",
"elementUtils",
",",
"Element",
"item",
",",
"String",
"annotationName",
",",
"AnnotationAttributeType",
"attribute",
",",
"OnAttributeFoundListener",
"listener",
")",
"{",
"List",
"<",
"?",
"extends",
"AnnotationMirror",
">",
"annotationList",
"=",
"elementUtils",
".",
"getAllAnnotationMirrors",
"(",
"item",
")",
";",
"for",
"(",
"AnnotationMirror",
"annotation",
":",
"annotationList",
")",
"{",
"if",
"(",
"annotationName",
".",
"equals",
"(",
"annotation",
".",
"getAnnotationType",
"(",
")",
".",
"asElement",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
"{",
"// found annotation",
"for",
"(",
"Entry",
"<",
"?",
"extends",
"ExecutableElement",
",",
"?",
"extends",
"AnnotationValue",
">",
"annotationItem",
":",
"elementUtils",
".",
"getElementValuesWithDefaults",
"(",
"annotation",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"attribute",
".",
"isEquals",
"(",
"annotationItem",
".",
"getKey",
"(",
")",
")",
")",
"{",
"listener",
".",
"onFound",
"(",
"annotationItem",
".",
"getValue",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"return",
";",
"}",
"}",
"}",
"}",
"}"
]
| Extract from an annotation of a method the attribute value specified.
@param elementUtils the element utils
@param item the item
@param annotationName the annotation name
@param attribute the attribute
@param listener the listener | [
"Extract",
"from",
"an",
"annotation",
"of",
"a",
"method",
"the",
"attribute",
"value",
"specified",
"."
]
| train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L353-L366 |
lessthanoptimal/BoofCV | integration/boofcv-swing/src/main/java/boofcv/gui/ListDisplayPanel.java | ListDisplayPanel.addImage | public void addImage( BufferedImage image , String name) {
"""
Displays a new image in the list.
@param image The image being displayed
@param name Name of the image. Shown in the list.
"""
addImage(image, name, ScaleOptions.DOWN);
} | java | public void addImage( BufferedImage image , String name) {
addImage(image, name, ScaleOptions.DOWN);
} | [
"public",
"void",
"addImage",
"(",
"BufferedImage",
"image",
",",
"String",
"name",
")",
"{",
"addImage",
"(",
"image",
",",
"name",
",",
"ScaleOptions",
".",
"DOWN",
")",
";",
"}"
]
| Displays a new image in the list.
@param image The image being displayed
@param name Name of the image. Shown in the list. | [
"Displays",
"a",
"new",
"image",
"in",
"the",
"list",
"."
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-swing/src/main/java/boofcv/gui/ListDisplayPanel.java#L101-L103 |
Jasig/uPortal | uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/BasePersonManager.java | BasePersonManager.createPersonForRequest | protected IPerson createPersonForRequest(HttpServletRequest request) {
"""
Creates a new {@link IPerson} to represent the user based on (1) an OIDC Id token specified
in the Authorization header or (2) the value of the <code>
org.apereo.portal.security.PersonFactory.guest_user_names</code> property in
portal.properties and (optionally) any beans that implement {@link IGuestUsernameSelector}.
This approach supports pluggable, open-ended strategies for multiple guest users who may have
different content.
@since 5.0
"""
/*
* Is there an an identity specified by OIDC Id token?
*/
final Jws<Claims> claims = idTokenFactory.getUserInfo(request);
if (claims != null) {
final String username = claims.getBody().getSubject();
logger.debug("Found OIDC Id token for username='{}'", username);
final IPerson rslt = new PersonImpl();
rslt.setAttribute(IPerson.USERNAME, username);
rslt.setID(userIdentityStore.getPortalUserId(username));
return rslt;
}
/*
* No identity specified; create a 'guest person.'
*/
// First we need to know the guest username
String username = PersonFactory.getGuestUsernames().get(0); // First item is the default
// Pluggable strategy for supporting multiple guest users
for (IGuestUsernameSelector selector : guestUsernameSelectors) {
final String s = selector.selectGuestUsername(request);
if (s != null) {
username = s;
break;
}
}
// Sanity check...
if (!PersonFactory.getGuestUsernames().contains(username)) {
final String msg =
"The specified guest username is not in the configured list: " + username;
throw new IllegalStateException(msg);
}
Integer guestUserId = guestUserIds.get(username);
if (guestUserId == null) {
// Not yet looked up
loadGuestUserId(username, guestUserIds);
guestUserId = guestUserIds.get(username);
}
final IPerson rslt = PersonFactory.createPerson();
rslt.setAttribute(IPerson.USERNAME, username);
rslt.setID(guestUserId);
rslt.setSecurityContext(initialSecurityContextFactory.getInitialContext());
return rslt;
} | java | protected IPerson createPersonForRequest(HttpServletRequest request) {
/*
* Is there an an identity specified by OIDC Id token?
*/
final Jws<Claims> claims = idTokenFactory.getUserInfo(request);
if (claims != null) {
final String username = claims.getBody().getSubject();
logger.debug("Found OIDC Id token for username='{}'", username);
final IPerson rslt = new PersonImpl();
rslt.setAttribute(IPerson.USERNAME, username);
rslt.setID(userIdentityStore.getPortalUserId(username));
return rslt;
}
/*
* No identity specified; create a 'guest person.'
*/
// First we need to know the guest username
String username = PersonFactory.getGuestUsernames().get(0); // First item is the default
// Pluggable strategy for supporting multiple guest users
for (IGuestUsernameSelector selector : guestUsernameSelectors) {
final String s = selector.selectGuestUsername(request);
if (s != null) {
username = s;
break;
}
}
// Sanity check...
if (!PersonFactory.getGuestUsernames().contains(username)) {
final String msg =
"The specified guest username is not in the configured list: " + username;
throw new IllegalStateException(msg);
}
Integer guestUserId = guestUserIds.get(username);
if (guestUserId == null) {
// Not yet looked up
loadGuestUserId(username, guestUserIds);
guestUserId = guestUserIds.get(username);
}
final IPerson rslt = PersonFactory.createPerson();
rslt.setAttribute(IPerson.USERNAME, username);
rslt.setID(guestUserId);
rslt.setSecurityContext(initialSecurityContextFactory.getInitialContext());
return rslt;
} | [
"protected",
"IPerson",
"createPersonForRequest",
"(",
"HttpServletRequest",
"request",
")",
"{",
"/*\n * Is there an an identity specified by OIDC Id token?\n */",
"final",
"Jws",
"<",
"Claims",
">",
"claims",
"=",
"idTokenFactory",
".",
"getUserInfo",
"(",
"request",
")",
";",
"if",
"(",
"claims",
"!=",
"null",
")",
"{",
"final",
"String",
"username",
"=",
"claims",
".",
"getBody",
"(",
")",
".",
"getSubject",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Found OIDC Id token for username='{}'\"",
",",
"username",
")",
";",
"final",
"IPerson",
"rslt",
"=",
"new",
"PersonImpl",
"(",
")",
";",
"rslt",
".",
"setAttribute",
"(",
"IPerson",
".",
"USERNAME",
",",
"username",
")",
";",
"rslt",
".",
"setID",
"(",
"userIdentityStore",
".",
"getPortalUserId",
"(",
"username",
")",
")",
";",
"return",
"rslt",
";",
"}",
"/*\n * No identity specified; create a 'guest person.'\n */",
"// First we need to know the guest username",
"String",
"username",
"=",
"PersonFactory",
".",
"getGuestUsernames",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"// First item is the default",
"// Pluggable strategy for supporting multiple guest users",
"for",
"(",
"IGuestUsernameSelector",
"selector",
":",
"guestUsernameSelectors",
")",
"{",
"final",
"String",
"s",
"=",
"selector",
".",
"selectGuestUsername",
"(",
"request",
")",
";",
"if",
"(",
"s",
"!=",
"null",
")",
"{",
"username",
"=",
"s",
";",
"break",
";",
"}",
"}",
"// Sanity check...",
"if",
"(",
"!",
"PersonFactory",
".",
"getGuestUsernames",
"(",
")",
".",
"contains",
"(",
"username",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"\"The specified guest username is not in the configured list: \"",
"+",
"username",
";",
"throw",
"new",
"IllegalStateException",
"(",
"msg",
")",
";",
"}",
"Integer",
"guestUserId",
"=",
"guestUserIds",
".",
"get",
"(",
"username",
")",
";",
"if",
"(",
"guestUserId",
"==",
"null",
")",
"{",
"// Not yet looked up",
"loadGuestUserId",
"(",
"username",
",",
"guestUserIds",
")",
";",
"guestUserId",
"=",
"guestUserIds",
".",
"get",
"(",
"username",
")",
";",
"}",
"final",
"IPerson",
"rslt",
"=",
"PersonFactory",
".",
"createPerson",
"(",
")",
";",
"rslt",
".",
"setAttribute",
"(",
"IPerson",
".",
"USERNAME",
",",
"username",
")",
";",
"rslt",
".",
"setID",
"(",
"guestUserId",
")",
";",
"rslt",
".",
"setSecurityContext",
"(",
"initialSecurityContextFactory",
".",
"getInitialContext",
"(",
")",
")",
";",
"return",
"rslt",
";",
"}"
]
| Creates a new {@link IPerson} to represent the user based on (1) an OIDC Id token specified
in the Authorization header or (2) the value of the <code>
org.apereo.portal.security.PersonFactory.guest_user_names</code> property in
portal.properties and (optionally) any beans that implement {@link IGuestUsernameSelector}.
This approach supports pluggable, open-ended strategies for multiple guest users who may have
different content.
@since 5.0 | [
"Creates",
"a",
"new",
"{",
"@link",
"IPerson",
"}",
"to",
"represent",
"the",
"user",
"based",
"on",
"(",
"1",
")",
"an",
"OIDC",
"Id",
"token",
"specified",
"in",
"the",
"Authorization",
"header",
"or",
"(",
"2",
")",
"the",
"value",
"of",
"the",
"<code",
">",
"org",
".",
"apereo",
".",
"portal",
".",
"security",
".",
"PersonFactory",
".",
"guest_user_names<",
"/",
"code",
">",
"property",
"in",
"portal",
".",
"properties",
"and",
"(",
"optionally",
")",
"any",
"beans",
"that",
"implement",
"{",
"@link",
"IGuestUsernameSelector",
"}",
".",
"This",
"approach",
"supports",
"pluggable",
"open",
"-",
"ended",
"strategies",
"for",
"multiple",
"guest",
"users",
"who",
"may",
"have",
"different",
"content",
"."
]
| train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/BasePersonManager.java#L119-L171 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/TaskTracker.java | TaskTracker.getMaxActualSlots | int getMaxActualSlots(JobConf conf, int numCpuOnTT, TaskType type) {
"""
Get the actual max number of tasks. This may be different than
get(Max|Reduce)CurrentMapTasks() since that is the number used
for scheduling. This allows the CoronaTaskTracker to return the
real number of resources available.
@param conf Configuration to look for slots
@param numCpuOnTT Number of cpus on TaskTracker
@param type Type of slot
@return Actual number of map tasks, not what the TaskLauncher thinks.
"""
return getMaxSlots(conf, numCpuOnTT, type);
} | java | int getMaxActualSlots(JobConf conf, int numCpuOnTT, TaskType type) {
return getMaxSlots(conf, numCpuOnTT, type);
} | [
"int",
"getMaxActualSlots",
"(",
"JobConf",
"conf",
",",
"int",
"numCpuOnTT",
",",
"TaskType",
"type",
")",
"{",
"return",
"getMaxSlots",
"(",
"conf",
",",
"numCpuOnTT",
",",
"type",
")",
";",
"}"
]
| Get the actual max number of tasks. This may be different than
get(Max|Reduce)CurrentMapTasks() since that is the number used
for scheduling. This allows the CoronaTaskTracker to return the
real number of resources available.
@param conf Configuration to look for slots
@param numCpuOnTT Number of cpus on TaskTracker
@param type Type of slot
@return Actual number of map tasks, not what the TaskLauncher thinks. | [
"Get",
"the",
"actual",
"max",
"number",
"of",
"tasks",
".",
"This",
"may",
"be",
"different",
"than",
"get",
"(",
"Max|Reduce",
")",
"CurrentMapTasks",
"()",
"since",
"that",
"is",
"the",
"number",
"used",
"for",
"scheduling",
".",
"This",
"allows",
"the",
"CoronaTaskTracker",
"to",
"return",
"the",
"real",
"number",
"of",
"resources",
"available",
"."
]
| train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskTracker.java#L4282-L4284 |
CloudSlang/score | engine/orchestrator/score-orchestrator-impl/src/main/java/io/cloudslang/orchestrator/services/CancelExecutionServiceImpl.java | CancelExecutionServiceImpl.cancelPausedRun | private void cancelPausedRun(ExecutionState executionStateToCancel) {
"""
If it doesn't - just cancel it straight away - extract the Run Object, set its context accordingly and put into the queue.
"""
final List<ExecutionState> branches = executionStateService.readByExecutionId(executionStateToCancel.getExecutionId());
// If the parent is paused because one of the branches is paused, OR, it was paused by the user / no-workers-in-group, but has branches that were not finished (and thus, were paused) -
// The parent itself will return to the queue after all the branches are ended (due to this cancellation), and then it'll be canceled as well.
if (branches.size() > 1) { // more than 1 means that it has paused branches (branches is at least 1 - the parent)
for (ExecutionState branch : branches) {
if (!EMPTY_BRANCH.equals(branch.getBranchId())) { // exclude the base execution
returnCanceledRunToQueue(branch);
executionStateService.deleteExecutionState(branch.getExecutionId(), branch.getBranchId());
}
}
executionStateToCancel.setStatus(ExecutionStatus.PENDING_CANCEL); // when the parent will return to queue - should have the correct status
} else {
returnCanceledRunToQueue(executionStateToCancel);
}
} | java | private void cancelPausedRun(ExecutionState executionStateToCancel) {
final List<ExecutionState> branches = executionStateService.readByExecutionId(executionStateToCancel.getExecutionId());
// If the parent is paused because one of the branches is paused, OR, it was paused by the user / no-workers-in-group, but has branches that were not finished (and thus, were paused) -
// The parent itself will return to the queue after all the branches are ended (due to this cancellation), and then it'll be canceled as well.
if (branches.size() > 1) { // more than 1 means that it has paused branches (branches is at least 1 - the parent)
for (ExecutionState branch : branches) {
if (!EMPTY_BRANCH.equals(branch.getBranchId())) { // exclude the base execution
returnCanceledRunToQueue(branch);
executionStateService.deleteExecutionState(branch.getExecutionId(), branch.getBranchId());
}
}
executionStateToCancel.setStatus(ExecutionStatus.PENDING_CANCEL); // when the parent will return to queue - should have the correct status
} else {
returnCanceledRunToQueue(executionStateToCancel);
}
} | [
"private",
"void",
"cancelPausedRun",
"(",
"ExecutionState",
"executionStateToCancel",
")",
"{",
"final",
"List",
"<",
"ExecutionState",
">",
"branches",
"=",
"executionStateService",
".",
"readByExecutionId",
"(",
"executionStateToCancel",
".",
"getExecutionId",
"(",
")",
")",
";",
"// If the parent is paused because one of the branches is paused, OR, it was paused by the user / no-workers-in-group, but has branches that were not finished (and thus, were paused) -",
"// The parent itself will return to the queue after all the branches are ended (due to this cancellation), and then it'll be canceled as well.",
"if",
"(",
"branches",
".",
"size",
"(",
")",
">",
"1",
")",
"{",
"// more than 1 means that it has paused branches (branches is at least 1 - the parent)",
"for",
"(",
"ExecutionState",
"branch",
":",
"branches",
")",
"{",
"if",
"(",
"!",
"EMPTY_BRANCH",
".",
"equals",
"(",
"branch",
".",
"getBranchId",
"(",
")",
")",
")",
"{",
"// exclude the base execution",
"returnCanceledRunToQueue",
"(",
"branch",
")",
";",
"executionStateService",
".",
"deleteExecutionState",
"(",
"branch",
".",
"getExecutionId",
"(",
")",
",",
"branch",
".",
"getBranchId",
"(",
")",
")",
";",
"}",
"}",
"executionStateToCancel",
".",
"setStatus",
"(",
"ExecutionStatus",
".",
"PENDING_CANCEL",
")",
";",
"// when the parent will return to queue - should have the correct status",
"}",
"else",
"{",
"returnCanceledRunToQueue",
"(",
"executionStateToCancel",
")",
";",
"}",
"}"
]
| If it doesn't - just cancel it straight away - extract the Run Object, set its context accordingly and put into the queue. | [
"If",
"it",
"doesn",
"t",
"-",
"just",
"cancel",
"it",
"straight",
"away",
"-",
"extract",
"the",
"Run",
"Object",
"set",
"its",
"context",
"accordingly",
"and",
"put",
"into",
"the",
"queue",
"."
]
| train | https://github.com/CloudSlang/score/blob/796134e917843f4d95a90f7740d69dc5257a1a0e/engine/orchestrator/score-orchestrator-impl/src/main/java/io/cloudslang/orchestrator/services/CancelExecutionServiceImpl.java#L101-L117 |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.spliceIn | private static int spliceIn(ByteBuffer src, ByteBuffer dest) {
"""
Write the contents of src to dest, without messing with src's position.
@param dest (position is advanced)
@return the pos in dest where src is written
"""
int position = dest.position();
int srcPos = src.position();
dest.put(src);
src.position(srcPos);
return position;
} | java | private static int spliceIn(ByteBuffer src, ByteBuffer dest) {
int position = dest.position();
int srcPos = src.position();
dest.put(src);
src.position(srcPos);
return position;
} | [
"private",
"static",
"int",
"spliceIn",
"(",
"ByteBuffer",
"src",
",",
"ByteBuffer",
"dest",
")",
"{",
"int",
"position",
"=",
"dest",
".",
"position",
"(",
")",
";",
"int",
"srcPos",
"=",
"src",
".",
"position",
"(",
")",
";",
"dest",
".",
"put",
"(",
"src",
")",
";",
"src",
".",
"position",
"(",
"srcPos",
")",
";",
"return",
"position",
";",
"}"
]
| Write the contents of src to dest, without messing with src's position.
@param dest (position is advanced)
@return the pos in dest where src is written | [
"Write",
"the",
"contents",
"of",
"src",
"to",
"dest",
"without",
"messing",
"with",
"src",
"s",
"position",
"."
]
| train | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L364-L370 |
mockito/mockito | src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java | InjectingAnnotationEngine.injectMocks | public void injectMocks(final Object testClassInstance) {
"""
Initializes mock/spies dependencies for objects annotated with
@InjectMocks for given testClassInstance.
<p>
See examples in javadoc for {@link MockitoAnnotations} class.
@param testClassInstance
Test class, usually <code>this</code>
"""
Class<?> clazz = testClassInstance.getClass();
Set<Field> mockDependentFields = new HashSet<Field>();
Set<Object> mocks = newMockSafeHashSet();
while (clazz != Object.class) {
new InjectMocksScanner(clazz).addTo(mockDependentFields);
new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks);
onInjection(testClassInstance, clazz, mockDependentFields, mocks);
clazz = clazz.getSuperclass();
}
new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance);
} | java | public void injectMocks(final Object testClassInstance) {
Class<?> clazz = testClassInstance.getClass();
Set<Field> mockDependentFields = new HashSet<Field>();
Set<Object> mocks = newMockSafeHashSet();
while (clazz != Object.class) {
new InjectMocksScanner(clazz).addTo(mockDependentFields);
new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks);
onInjection(testClassInstance, clazz, mockDependentFields, mocks);
clazz = clazz.getSuperclass();
}
new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance);
} | [
"public",
"void",
"injectMocks",
"(",
"final",
"Object",
"testClassInstance",
")",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"testClassInstance",
".",
"getClass",
"(",
")",
";",
"Set",
"<",
"Field",
">",
"mockDependentFields",
"=",
"new",
"HashSet",
"<",
"Field",
">",
"(",
")",
";",
"Set",
"<",
"Object",
">",
"mocks",
"=",
"newMockSafeHashSet",
"(",
")",
";",
"while",
"(",
"clazz",
"!=",
"Object",
".",
"class",
")",
"{",
"new",
"InjectMocksScanner",
"(",
"clazz",
")",
".",
"addTo",
"(",
"mockDependentFields",
")",
";",
"new",
"MockScanner",
"(",
"testClassInstance",
",",
"clazz",
")",
".",
"addPreparedMocks",
"(",
"mocks",
")",
";",
"onInjection",
"(",
"testClassInstance",
",",
"clazz",
",",
"mockDependentFields",
",",
"mocks",
")",
";",
"clazz",
"=",
"clazz",
".",
"getSuperclass",
"(",
")",
";",
"}",
"new",
"DefaultInjectionEngine",
"(",
")",
".",
"injectMocksOnFields",
"(",
"mockDependentFields",
",",
"mocks",
",",
"testClassInstance",
")",
";",
"}"
]
| Initializes mock/spies dependencies for objects annotated with
@InjectMocks for given testClassInstance.
<p>
See examples in javadoc for {@link MockitoAnnotations} class.
@param testClassInstance
Test class, usually <code>this</code> | [
"Initializes",
"mock",
"/",
"spies",
"dependencies",
"for",
"objects",
"annotated",
"with",
"@",
";",
"InjectMocks",
"for",
"given",
"testClassInstance",
".",
"<p",
">",
"See",
"examples",
"in",
"javadoc",
"for",
"{",
"@link",
"MockitoAnnotations",
"}",
"class",
"."
]
| train | https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java#L67-L80 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/ZealotKhala.java | ZealotKhala.doNormal | private ZealotKhala doNormal(String prefix, String field, Object value, String suffix, boolean match) {
"""
执行生成等值查询SQL片段的方法.
@param prefix 前缀
@param field 数据库字段
@param value 值
@param suffix 后缀
@param match 是否匹配
@return ZealotKhala实例的当前实例
"""
if (match) {
SqlInfoBuilder.newInstace(this.source.setPrefix(prefix)).buildNormalSql(field, value, suffix);
this.source.resetPrefix();
}
return this;
} | java | private ZealotKhala doNormal(String prefix, String field, Object value, String suffix, boolean match) {
if (match) {
SqlInfoBuilder.newInstace(this.source.setPrefix(prefix)).buildNormalSql(field, value, suffix);
this.source.resetPrefix();
}
return this;
} | [
"private",
"ZealotKhala",
"doNormal",
"(",
"String",
"prefix",
",",
"String",
"field",
",",
"Object",
"value",
",",
"String",
"suffix",
",",
"boolean",
"match",
")",
"{",
"if",
"(",
"match",
")",
"{",
"SqlInfoBuilder",
".",
"newInstace",
"(",
"this",
".",
"source",
".",
"setPrefix",
"(",
"prefix",
")",
")",
".",
"buildNormalSql",
"(",
"field",
",",
"value",
",",
"suffix",
")",
";",
"this",
".",
"source",
".",
"resetPrefix",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| 执行生成等值查询SQL片段的方法.
@param prefix 前缀
@param field 数据库字段
@param value 值
@param suffix 后缀
@param match 是否匹配
@return ZealotKhala实例的当前实例 | [
"执行生成等值查询SQL片段的方法",
"."
]
| train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L375-L381 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseBoolObjExact | @Nullable
public static Boolean parseBoolObjExact (@Nullable final String sStr, @Nullable final Boolean aDefault) {
"""
Returns a <code>Boolean</code> with a value represented by the specified
string. The <code>Boolean</code> returned represents a <code>true</code>
value if the string argument is not <code>null</code> and is equal,
ignoring case, to the string {@code "true"}, and it will return
<code>false</code> if the string argument is not <code>null</code> and is
equal, ignoring case, to the string {@code "false"}. In all other cases
<code>aDefault</code> is returned.
@param sStr
The string to be parsed. May be <code>null</code>.
@param aDefault
The default value to be returned if the value is neither "true" nor
"false". May be <code>null</code>.
@return the <code>Boolean</code> value represented by the string. Never
<code>null</code>.
"""
if (Boolean.TRUE.toString ().equalsIgnoreCase (sStr))
return Boolean.TRUE;
if (Boolean.FALSE.toString ().equalsIgnoreCase (sStr))
return Boolean.FALSE;
return aDefault;
} | java | @Nullable
public static Boolean parseBoolObjExact (@Nullable final String sStr, @Nullable final Boolean aDefault)
{
if (Boolean.TRUE.toString ().equalsIgnoreCase (sStr))
return Boolean.TRUE;
if (Boolean.FALSE.toString ().equalsIgnoreCase (sStr))
return Boolean.FALSE;
return aDefault;
} | [
"@",
"Nullable",
"public",
"static",
"Boolean",
"parseBoolObjExact",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nullable",
"final",
"Boolean",
"aDefault",
")",
"{",
"if",
"(",
"Boolean",
".",
"TRUE",
".",
"toString",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"sStr",
")",
")",
"return",
"Boolean",
".",
"TRUE",
";",
"if",
"(",
"Boolean",
".",
"FALSE",
".",
"toString",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"sStr",
")",
")",
"return",
"Boolean",
".",
"FALSE",
";",
"return",
"aDefault",
";",
"}"
]
| Returns a <code>Boolean</code> with a value represented by the specified
string. The <code>Boolean</code> returned represents a <code>true</code>
value if the string argument is not <code>null</code> and is equal,
ignoring case, to the string {@code "true"}, and it will return
<code>false</code> if the string argument is not <code>null</code> and is
equal, ignoring case, to the string {@code "false"}. In all other cases
<code>aDefault</code> is returned.
@param sStr
The string to be parsed. May be <code>null</code>.
@param aDefault
The default value to be returned if the value is neither "true" nor
"false". May be <code>null</code>.
@return the <code>Boolean</code> value represented by the string. Never
<code>null</code>. | [
"Returns",
"a",
"<code",
">",
"Boolean<",
"/",
"code",
">",
"with",
"a",
"value",
"represented",
"by",
"the",
"specified",
"string",
".",
"The",
"<code",
">",
"Boolean<",
"/",
"code",
">",
"returned",
"represents",
"a",
"<code",
">",
"true<",
"/",
"code",
">",
"value",
"if",
"the",
"string",
"argument",
"is",
"not",
"<code",
">",
"null<",
"/",
"code",
">",
"and",
"is",
"equal",
"ignoring",
"case",
"to",
"the",
"string",
"{",
"@code",
"true",
"}",
"and",
"it",
"will",
"return",
"<code",
">",
"false<",
"/",
"code",
">",
"if",
"the",
"string",
"argument",
"is",
"not",
"<code",
">",
"null<",
"/",
"code",
">",
"and",
"is",
"equal",
"ignoring",
"case",
"to",
"the",
"string",
"{",
"@code",
"false",
"}",
".",
"In",
"all",
"other",
"cases",
"<code",
">",
"aDefault<",
"/",
"code",
">",
"is",
"returned",
"."
]
| train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L237-L245 |
stephanenicolas/robospice | robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java | SpiceManager.getDataFromCache | public <T> Future<T> getDataFromCache(final Class<T> clazz, final Object cacheKey) throws CacheLoadingException {
"""
Get some data previously saved in cache with key <i>requestCacheKey</i>.
This method doesn't perform any network processing, it just checks if
there are previously saved data. Don't call this method in the main
thread because you could block it. Instead, use the asynchronous version
of this method:
{@link #getFromCache(Class, Object, long, RequestListener)}.
@param clazz
the class of the result to retrieve from cache.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@return a future object that will hold data in cache. Calling get on this
future will block until the data is actually effectively taken
from cache.
@throws CacheLoadingException
Exception thrown when a problem occurs while loading data
from cache.
"""
return executeCommand(new GetDataFromCacheCommand<T>(this, clazz, cacheKey));
} | java | public <T> Future<T> getDataFromCache(final Class<T> clazz, final Object cacheKey) throws CacheLoadingException {
return executeCommand(new GetDataFromCacheCommand<T>(this, clazz, cacheKey));
} | [
"public",
"<",
"T",
">",
"Future",
"<",
"T",
">",
"getDataFromCache",
"(",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"Object",
"cacheKey",
")",
"throws",
"CacheLoadingException",
"{",
"return",
"executeCommand",
"(",
"new",
"GetDataFromCacheCommand",
"<",
"T",
">",
"(",
"this",
",",
"clazz",
",",
"cacheKey",
")",
")",
";",
"}"
]
| Get some data previously saved in cache with key <i>requestCacheKey</i>.
This method doesn't perform any network processing, it just checks if
there are previously saved data. Don't call this method in the main
thread because you could block it. Instead, use the asynchronous version
of this method:
{@link #getFromCache(Class, Object, long, RequestListener)}.
@param clazz
the class of the result to retrieve from cache.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@return a future object that will hold data in cache. Calling get on this
future will block until the data is actually effectively taken
from cache.
@throws CacheLoadingException
Exception thrown when a problem occurs while loading data
from cache. | [
"Get",
"some",
"data",
"previously",
"saved",
"in",
"cache",
"with",
"key",
"<i",
">",
"requestCacheKey<",
"/",
"i",
">",
".",
"This",
"method",
"doesn",
"t",
"perform",
"any",
"network",
"processing",
"it",
"just",
"checks",
"if",
"there",
"are",
"previously",
"saved",
"data",
".",
"Don",
"t",
"call",
"this",
"method",
"in",
"the",
"main",
"thread",
"because",
"you",
"could",
"block",
"it",
".",
"Instead",
"use",
"the",
"asynchronous",
"version",
"of",
"this",
"method",
":",
"{"
]
| train | https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java#L904-L906 |
linkedin/dexmaker | dexmaker/src/main/java/com/android/dx/Code.java | Code.splitCurrentLabel | private void splitCurrentLabel(Label alternateSuccessor, List<Label> catchLabels) {
"""
Closes the current label and starts a new one.
@param catchLabels an immutable list of catch labels
"""
Label newLabel = new Label();
adopt(newLabel);
currentLabel.primarySuccessor = newLabel;
currentLabel.alternateSuccessor = alternateSuccessor;
currentLabel.catchLabels = catchLabels;
currentLabel = newLabel;
currentLabel.marked = true;
} | java | private void splitCurrentLabel(Label alternateSuccessor, List<Label> catchLabels) {
Label newLabel = new Label();
adopt(newLabel);
currentLabel.primarySuccessor = newLabel;
currentLabel.alternateSuccessor = alternateSuccessor;
currentLabel.catchLabels = catchLabels;
currentLabel = newLabel;
currentLabel.marked = true;
} | [
"private",
"void",
"splitCurrentLabel",
"(",
"Label",
"alternateSuccessor",
",",
"List",
"<",
"Label",
">",
"catchLabels",
")",
"{",
"Label",
"newLabel",
"=",
"new",
"Label",
"(",
")",
";",
"adopt",
"(",
"newLabel",
")",
";",
"currentLabel",
".",
"primarySuccessor",
"=",
"newLabel",
";",
"currentLabel",
".",
"alternateSuccessor",
"=",
"alternateSuccessor",
";",
"currentLabel",
".",
"catchLabels",
"=",
"catchLabels",
";",
"currentLabel",
"=",
"newLabel",
";",
"currentLabel",
".",
"marked",
"=",
"true",
";",
"}"
]
| Closes the current label and starts a new one.
@param catchLabels an immutable list of catch labels | [
"Closes",
"the",
"current",
"label",
"and",
"starts",
"a",
"new",
"one",
"."
]
| train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L462-L470 |
liferay/com-liferay-commerce | commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionOptionRelWrapper.java | CPDefinitionOptionRelWrapper.getDescription | @Override
public String getDescription(String languageId, boolean useDefault) {
"""
Returns the localized description of this cp definition option rel in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized description of this cp definition option rel
"""
return _cpDefinitionOptionRel.getDescription(languageId, useDefault);
} | java | @Override
public String getDescription(String languageId, boolean useDefault) {
return _cpDefinitionOptionRel.getDescription(languageId, useDefault);
} | [
"@",
"Override",
"public",
"String",
"getDescription",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_cpDefinitionOptionRel",
".",
"getDescription",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
]
| Returns the localized description of this cp definition option rel in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized description of this cp definition option rel | [
"Returns",
"the",
"localized",
"description",
"of",
"this",
"cp",
"definition",
"option",
"rel",
"in",
"the",
"language",
"optionally",
"using",
"the",
"default",
"language",
"if",
"no",
"localization",
"exists",
"for",
"the",
"requested",
"language",
"."
]
| train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionOptionRelWrapper.java#L340-L343 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/replicator/PusherInternal.java | PusherInternal.uploadJsonRevision | private void uploadJsonRevision(final RevisionInternal rev) {
"""
Fallback to upload a revision if uploadMultipartRevision failed due to the server's rejecting
multipart format.
- (void) uploadJSONRevision: (CBL_Revision*)originalRev in CBLRestPusher.m
"""
// Get the revision's properties:
if (!db.inlineFollowingAttachmentsIn(rev)) {
setError(new CouchbaseLiteException(Status.BAD_ATTACHMENT));
return;
}
final String path = String.format(Locale.ENGLISH, "%s?new_edits=false", encodeDocumentId(rev.getDocID()));
CustomFuture future = sendAsyncRequest("PUT",
path,
rev.getProperties(),
new RemoteRequestCompletion() {
public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
if (e != null) {
setError(e);
} else {
Log.v(TAG, "%s: Sent %s (JSON), response=%s", this, rev, result);
removePending(rev);
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
} | java | private void uploadJsonRevision(final RevisionInternal rev) {
// Get the revision's properties:
if (!db.inlineFollowingAttachmentsIn(rev)) {
setError(new CouchbaseLiteException(Status.BAD_ATTACHMENT));
return;
}
final String path = String.format(Locale.ENGLISH, "%s?new_edits=false", encodeDocumentId(rev.getDocID()));
CustomFuture future = sendAsyncRequest("PUT",
path,
rev.getProperties(),
new RemoteRequestCompletion() {
public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
if (e != null) {
setError(e);
} else {
Log.v(TAG, "%s: Sent %s (JSON), response=%s", this, rev, result);
removePending(rev);
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
} | [
"private",
"void",
"uploadJsonRevision",
"(",
"final",
"RevisionInternal",
"rev",
")",
"{",
"// Get the revision's properties:",
"if",
"(",
"!",
"db",
".",
"inlineFollowingAttachmentsIn",
"(",
"rev",
")",
")",
"{",
"setError",
"(",
"new",
"CouchbaseLiteException",
"(",
"Status",
".",
"BAD_ATTACHMENT",
")",
")",
";",
"return",
";",
"}",
"final",
"String",
"path",
"=",
"String",
".",
"format",
"(",
"Locale",
".",
"ENGLISH",
",",
"\"%s?new_edits=false\"",
",",
"encodeDocumentId",
"(",
"rev",
".",
"getDocID",
"(",
")",
")",
")",
";",
"CustomFuture",
"future",
"=",
"sendAsyncRequest",
"(",
"\"PUT\"",
",",
"path",
",",
"rev",
".",
"getProperties",
"(",
")",
",",
"new",
"RemoteRequestCompletion",
"(",
")",
"{",
"public",
"void",
"onCompletion",
"(",
"RemoteRequest",
"remoteRequest",
",",
"Response",
"httpResponse",
",",
"Object",
"result",
",",
"Throwable",
"e",
")",
"{",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"setError",
"(",
"e",
")",
";",
"}",
"else",
"{",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"%s: Sent %s (JSON), response=%s\"",
",",
"this",
",",
"rev",
",",
"result",
")",
";",
"removePending",
"(",
"rev",
")",
";",
"}",
"}",
"}",
")",
";",
"future",
".",
"setQueue",
"(",
"pendingFutures",
")",
";",
"pendingFutures",
".",
"add",
"(",
"future",
")",
";",
"}"
]
| Fallback to upload a revision if uploadMultipartRevision failed due to the server's rejecting
multipart format.
- (void) uploadJSONRevision: (CBL_Revision*)originalRev in CBLRestPusher.m | [
"Fallback",
"to",
"upload",
"a",
"revision",
"if",
"uploadMultipartRevision",
"failed",
"due",
"to",
"the",
"server",
"s",
"rejecting",
"multipart",
"format",
".",
"-",
"(",
"void",
")",
"uploadJSONRevision",
":",
"(",
"CBL_Revision",
"*",
")",
"originalRev",
"in",
"CBLRestPusher",
".",
"m"
]
| train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PusherInternal.java#L639-L662 |
google/closure-compiler | src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java | DestructuringGlobalNameExtractor.replaceDestructuringAssignment | private static void replaceDestructuringAssignment(Node pattern, Node newLvalue, Node newRvalue) {
"""
Replaces the given assignment or declaration with the new lvalue/rvalue
@param pattern a destructuring pattern in an ASSIGN or VAR/LET/CONST
"""
Node parent = pattern.getParent();
if (parent.isAssign()) {
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
parent.replaceWith(newAssign);
} else if (newLvalue.isName()) {
checkState(parent.isDestructuringLhs());
parent.replaceWith(newLvalue);
newLvalue.addChildToBack(newRvalue);
} else {
pattern.getNext().detach();
pattern.detach();
parent.addChildToBack(newLvalue);
parent.addChildToBack(newRvalue);
}
} | java | private static void replaceDestructuringAssignment(Node pattern, Node newLvalue, Node newRvalue) {
Node parent = pattern.getParent();
if (parent.isAssign()) {
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
parent.replaceWith(newAssign);
} else if (newLvalue.isName()) {
checkState(parent.isDestructuringLhs());
parent.replaceWith(newLvalue);
newLvalue.addChildToBack(newRvalue);
} else {
pattern.getNext().detach();
pattern.detach();
parent.addChildToBack(newLvalue);
parent.addChildToBack(newRvalue);
}
} | [
"private",
"static",
"void",
"replaceDestructuringAssignment",
"(",
"Node",
"pattern",
",",
"Node",
"newLvalue",
",",
"Node",
"newRvalue",
")",
"{",
"Node",
"parent",
"=",
"pattern",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
"isAssign",
"(",
")",
")",
"{",
"Node",
"newAssign",
"=",
"IR",
".",
"assign",
"(",
"newLvalue",
",",
"newRvalue",
")",
".",
"srcref",
"(",
"parent",
")",
";",
"parent",
".",
"replaceWith",
"(",
"newAssign",
")",
";",
"}",
"else",
"if",
"(",
"newLvalue",
".",
"isName",
"(",
")",
")",
"{",
"checkState",
"(",
"parent",
".",
"isDestructuringLhs",
"(",
")",
")",
";",
"parent",
".",
"replaceWith",
"(",
"newLvalue",
")",
";",
"newLvalue",
".",
"addChildToBack",
"(",
"newRvalue",
")",
";",
"}",
"else",
"{",
"pattern",
".",
"getNext",
"(",
")",
".",
"detach",
"(",
")",
";",
"pattern",
".",
"detach",
"(",
")",
";",
"parent",
".",
"addChildToBack",
"(",
"newLvalue",
")",
";",
"parent",
".",
"addChildToBack",
"(",
"newRvalue",
")",
";",
"}",
"}"
]
| Replaces the given assignment or declaration with the new lvalue/rvalue
@param pattern a destructuring pattern in an ASSIGN or VAR/LET/CONST | [
"Replaces",
"the",
"given",
"assignment",
"or",
"declaration",
"with",
"the",
"new",
"lvalue",
"/",
"rvalue"
]
| train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L153-L168 |
kaazing/gateway | management/src/main/java/org/kaazing/gateway/management/context/DefaultManagementContext.java | DefaultManagementContext.addSessionManagementBean | @Override
public SessionManagementBean addSessionManagementBean(ServiceManagementBean serviceManagementBean,
IoSessionEx session) {
"""
Create a SessionManagementBean for a resource address on the local Gateway instance.
<p/>
XXX We need to do something more if we're going to support some idea of storing sessions from another Gateway instance in
the same repository, as we won't generally have ServiceContext or IoSessions to work with (since the other instance will
be in a different process, perhaps on a different machine.)
<p/>
NOTE: we store the service resource address on the management bean because we need it later to do protocol-specific things
like reconstruct JMX session mbean names. NOTE: the managementProcessors are called during the constructor, so the bean
has not yet been loaded into the list of sessionManagement beans.
"""
SessionManagementBean sessionManagementBean =
new SessionManagementBeanImpl(serviceManagementBean, session);
for (ManagementServiceHandler handler : managementServiceHandlers) {
handler.addSessionManagementBean(sessionManagementBean);
}
return sessionManagementBean;
} | java | @Override
public SessionManagementBean addSessionManagementBean(ServiceManagementBean serviceManagementBean,
IoSessionEx session) {
SessionManagementBean sessionManagementBean =
new SessionManagementBeanImpl(serviceManagementBean, session);
for (ManagementServiceHandler handler : managementServiceHandlers) {
handler.addSessionManagementBean(sessionManagementBean);
}
return sessionManagementBean;
} | [
"@",
"Override",
"public",
"SessionManagementBean",
"addSessionManagementBean",
"(",
"ServiceManagementBean",
"serviceManagementBean",
",",
"IoSessionEx",
"session",
")",
"{",
"SessionManagementBean",
"sessionManagementBean",
"=",
"new",
"SessionManagementBeanImpl",
"(",
"serviceManagementBean",
",",
"session",
")",
";",
"for",
"(",
"ManagementServiceHandler",
"handler",
":",
"managementServiceHandlers",
")",
"{",
"handler",
".",
"addSessionManagementBean",
"(",
"sessionManagementBean",
")",
";",
"}",
"return",
"sessionManagementBean",
";",
"}"
]
| Create a SessionManagementBean for a resource address on the local Gateway instance.
<p/>
XXX We need to do something more if we're going to support some idea of storing sessions from another Gateway instance in
the same repository, as we won't generally have ServiceContext or IoSessions to work with (since the other instance will
be in a different process, perhaps on a different machine.)
<p/>
NOTE: we store the service resource address on the management bean because we need it later to do protocol-specific things
like reconstruct JMX session mbean names. NOTE: the managementProcessors are called during the constructor, so the bean
has not yet been loaded into the list of sessionManagement beans. | [
"Create",
"a",
"SessionManagementBean",
"for",
"a",
"resource",
"address",
"on",
"the",
"local",
"Gateway",
"instance",
".",
"<p",
"/",
">",
"XXX",
"We",
"need",
"to",
"do",
"something",
"more",
"if",
"we",
"re",
"going",
"to",
"support",
"some",
"idea",
"of",
"storing",
"sessions",
"from",
"another",
"Gateway",
"instance",
"in",
"the",
"same",
"repository",
"as",
"we",
"won",
"t",
"generally",
"have",
"ServiceContext",
"or",
"IoSessions",
"to",
"work",
"with",
"(",
"since",
"the",
"other",
"instance",
"will",
"be",
"in",
"a",
"different",
"process",
"perhaps",
"on",
"a",
"different",
"machine",
".",
")",
"<p",
"/",
">",
"NOTE",
":",
"we",
"store",
"the",
"service",
"resource",
"address",
"on",
"the",
"management",
"bean",
"because",
"we",
"need",
"it",
"later",
"to",
"do",
"protocol",
"-",
"specific",
"things",
"like",
"reconstruct",
"JMX",
"session",
"mbean",
"names",
".",
"NOTE",
":",
"the",
"managementProcessors",
"are",
"called",
"during",
"the",
"constructor",
"so",
"the",
"bean",
"has",
"not",
"yet",
"been",
"loaded",
"into",
"the",
"list",
"of",
"sessionManagement",
"beans",
"."
]
| train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/management/src/main/java/org/kaazing/gateway/management/context/DefaultManagementContext.java#L554-L565 |
oasp/oasp4j | modules/security/src/main/java/io/oasp/module/security/common/impl/accesscontrol/AccessControlSchemaXmlMapper.java | AccessControlSchemaXmlMapper.writeXsd | public void writeXsd(final OutputStream out) {
"""
Generates the XSD (XML Schema Definition) to the given {@link OutputStream}.
@param out is the {@link OutputStream} to write to.
"""
SchemaOutputResolver sor = new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
StreamResult streamResult = new StreamResult(out);
streamResult.setSystemId(suggestedFileName);
return streamResult;
}
};
try {
this.jaxbContext.generateSchema(sor);
} catch (IOException e) {
throw new IllegalStateException("Failed to generate and write the XSD schema!", e);
}
} | java | public void writeXsd(final OutputStream out) {
SchemaOutputResolver sor = new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
StreamResult streamResult = new StreamResult(out);
streamResult.setSystemId(suggestedFileName);
return streamResult;
}
};
try {
this.jaxbContext.generateSchema(sor);
} catch (IOException e) {
throw new IllegalStateException("Failed to generate and write the XSD schema!", e);
}
} | [
"public",
"void",
"writeXsd",
"(",
"final",
"OutputStream",
"out",
")",
"{",
"SchemaOutputResolver",
"sor",
"=",
"new",
"SchemaOutputResolver",
"(",
")",
"{",
"@",
"Override",
"public",
"Result",
"createOutput",
"(",
"String",
"namespaceUri",
",",
"String",
"suggestedFileName",
")",
"throws",
"IOException",
"{",
"StreamResult",
"streamResult",
"=",
"new",
"StreamResult",
"(",
"out",
")",
";",
"streamResult",
".",
"setSystemId",
"(",
"suggestedFileName",
")",
";",
"return",
"streamResult",
";",
"}",
"}",
";",
"try",
"{",
"this",
".",
"jaxbContext",
".",
"generateSchema",
"(",
"sor",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Failed to generate and write the XSD schema!\"",
",",
"e",
")",
";",
"}",
"}"
]
| Generates the XSD (XML Schema Definition) to the given {@link OutputStream}.
@param out is the {@link OutputStream} to write to. | [
"Generates",
"the",
"XSD",
"(",
"XML",
"Schema",
"Definition",
")",
"to",
"the",
"given",
"{",
"@link",
"OutputStream",
"}",
"."
]
| train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/security/src/main/java/io/oasp/module/security/common/impl/accesscontrol/AccessControlSchemaXmlMapper.java#L100-L118 |
ops4j/org.ops4j.pax.exam2 | containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java | KarafDistributionOption.editConfigurationFileExtend | public static Option editConfigurationFileExtend(String configurationFilePath, String key,
Object value) {
"""
This option allows to extend configurations in each configuration file based on the
karaf.home location. The value extends the current value (e.g. a=b to a=a,b) instead of
replacing it. If there is no current value it is added.
<p>
If you would like to have add or replace functionality please use the
{@link KarafDistributionConfigurationFilePutOption} instead.
@param configurationFilePath
configuration file path
@param key
property key
@param value
property value
@return option
"""
return new KarafDistributionConfigurationFileExtendOption(configurationFilePath, key, value);
} | java | public static Option editConfigurationFileExtend(String configurationFilePath, String key,
Object value) {
return new KarafDistributionConfigurationFileExtendOption(configurationFilePath, key, value);
} | [
"public",
"static",
"Option",
"editConfigurationFileExtend",
"(",
"String",
"configurationFilePath",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"return",
"new",
"KarafDistributionConfigurationFileExtendOption",
"(",
"configurationFilePath",
",",
"key",
",",
"value",
")",
";",
"}"
]
| This option allows to extend configurations in each configuration file based on the
karaf.home location. The value extends the current value (e.g. a=b to a=a,b) instead of
replacing it. If there is no current value it is added.
<p>
If you would like to have add or replace functionality please use the
{@link KarafDistributionConfigurationFilePutOption} instead.
@param configurationFilePath
configuration file path
@param key
property key
@param value
property value
@return option | [
"This",
"option",
"allows",
"to",
"extend",
"configurations",
"in",
"each",
"configuration",
"file",
"based",
"on",
"the",
"karaf",
".",
"home",
"location",
".",
"The",
"value",
"extends",
"the",
"current",
"value",
"(",
"e",
".",
"g",
".",
"a",
"=",
"b",
"to",
"a",
"=",
"a",
"b",
")",
"instead",
"of",
"replacing",
"it",
".",
"If",
"there",
"is",
"no",
"current",
"value",
"it",
"is",
"added",
".",
"<p",
">",
"If",
"you",
"would",
"like",
"to",
"have",
"add",
"or",
"replace",
"functionality",
"please",
"use",
"the",
"{",
"@link",
"KarafDistributionConfigurationFilePutOption",
"}",
"instead",
"."
]
| train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java#L256-L259 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java | SnowflakeAzureClient.buildAzureStorageEndpointURI | private static URI buildAzureStorageEndpointURI(String storageEndPoint, String storageAccount)
throws URISyntaxException {
"""
/*
Builds a URI to a Azure Storage account endpoint
@param storageEndPoint the storage endpoint name
@param storageAccount the storage account name
"""
URI storageEndpoint = new URI(
"https", storageAccount + "." + storageEndPoint + "/",
null, null);
return storageEndpoint;
} | java | private static URI buildAzureStorageEndpointURI(String storageEndPoint, String storageAccount)
throws URISyntaxException
{
URI storageEndpoint = new URI(
"https", storageAccount + "." + storageEndPoint + "/",
null, null);
return storageEndpoint;
} | [
"private",
"static",
"URI",
"buildAzureStorageEndpointURI",
"(",
"String",
"storageEndPoint",
",",
"String",
"storageAccount",
")",
"throws",
"URISyntaxException",
"{",
"URI",
"storageEndpoint",
"=",
"new",
"URI",
"(",
"\"https\"",
",",
"storageAccount",
"+",
"\".\"",
"+",
"storageEndPoint",
"+",
"\"/\"",
",",
"null",
",",
"null",
")",
";",
"return",
"storageEndpoint",
";",
"}"
]
| /*
Builds a URI to a Azure Storage account endpoint
@param storageEndPoint the storage endpoint name
@param storageAccount the storage account name | [
"/",
"*",
"Builds",
"a",
"URI",
"to",
"a",
"Azure",
"Storage",
"account",
"endpoint"
]
| train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java#L771-L779 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDValidation.java | SDValidation.validateBool | protected static void validateBool(String opName, SDVariable v) {
"""
Validate that the operation is being applied on a boolean type SDVariable
@param opName Operation name to print in the exception
@param v Variable to validate datatype for (input to operation)
"""
if (v == null)
return;
if (v.dataType() != DataType.BOOL)
throw new IllegalStateException("Cannot apply operation \"" + opName + "\" to variable \"" + v.getVarName() + "\" with non-boolean point data type " + v.dataType());
} | java | protected static void validateBool(String opName, SDVariable v) {
if (v == null)
return;
if (v.dataType() != DataType.BOOL)
throw new IllegalStateException("Cannot apply operation \"" + opName + "\" to variable \"" + v.getVarName() + "\" with non-boolean point data type " + v.dataType());
} | [
"protected",
"static",
"void",
"validateBool",
"(",
"String",
"opName",
",",
"SDVariable",
"v",
")",
"{",
"if",
"(",
"v",
"==",
"null",
")",
"return",
";",
"if",
"(",
"v",
".",
"dataType",
"(",
")",
"!=",
"DataType",
".",
"BOOL",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot apply operation \\\"\"",
"+",
"opName",
"+",
"\"\\\" to variable \\\"\"",
"+",
"v",
".",
"getVarName",
"(",
")",
"+",
"\"\\\" with non-boolean point data type \"",
"+",
"v",
".",
"dataType",
"(",
")",
")",
";",
"}"
]
| Validate that the operation is being applied on a boolean type SDVariable
@param opName Operation name to print in the exception
@param v Variable to validate datatype for (input to operation) | [
"Validate",
"that",
"the",
"operation",
"is",
"being",
"applied",
"on",
"a",
"boolean",
"type",
"SDVariable"
]
| train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDValidation.java#L118-L123 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/impl/LifecycleManager.java | LifecycleManager.cacheStarting | @Override
public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
"""
Registers the Search interceptor in the cache before it gets started
"""
InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader());
SearchIntegrator searchFactory = null;
boolean isIndexed = cfg.indexing().index().isEnabled();
if (isIndexed) {
setBooleanQueryMaxClauseCount();
cr.registerComponent(new ShardAllocationManagerImpl(), ShardAllocatorManager.class);
searchFactory = createSearchIntegrator(cfg.indexing(), cr, aggregatedClassLoader);
KeyTransformationHandler keyTransformationHandler = new KeyTransformationHandler(aggregatedClassLoader);
cr.registerComponent(keyTransformationHandler, KeyTransformationHandler.class);
createQueryInterceptorIfNeeded(cr.getComponent(BasicComponentRegistry.class), cfg, cache, searchFactory, keyTransformationHandler);
addCacheDependencyIfNeeded(cacheName, cache.getCacheManager(), cfg.indexing());
cr.registerComponent(new QueryBox(), QueryBox.class);
}
registerMatcher(cr, searchFactory, aggregatedClassLoader);
cr.registerComponent(new EmbeddedQueryEngine(cache, isIndexed), EmbeddedQueryEngine.class);
}
} | java | @Override
public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader());
SearchIntegrator searchFactory = null;
boolean isIndexed = cfg.indexing().index().isEnabled();
if (isIndexed) {
setBooleanQueryMaxClauseCount();
cr.registerComponent(new ShardAllocationManagerImpl(), ShardAllocatorManager.class);
searchFactory = createSearchIntegrator(cfg.indexing(), cr, aggregatedClassLoader);
KeyTransformationHandler keyTransformationHandler = new KeyTransformationHandler(aggregatedClassLoader);
cr.registerComponent(keyTransformationHandler, KeyTransformationHandler.class);
createQueryInterceptorIfNeeded(cr.getComponent(BasicComponentRegistry.class), cfg, cache, searchFactory, keyTransformationHandler);
addCacheDependencyIfNeeded(cacheName, cache.getCacheManager(), cfg.indexing());
cr.registerComponent(new QueryBox(), QueryBox.class);
}
registerMatcher(cr, searchFactory, aggregatedClassLoader);
cr.registerComponent(new EmbeddedQueryEngine(cache, isIndexed), EmbeddedQueryEngine.class);
}
} | [
"@",
"Override",
"public",
"void",
"cacheStarting",
"(",
"ComponentRegistry",
"cr",
",",
"Configuration",
"cfg",
",",
"String",
"cacheName",
")",
"{",
"InternalCacheRegistry",
"icr",
"=",
"cr",
".",
"getGlobalComponentRegistry",
"(",
")",
".",
"getComponent",
"(",
"InternalCacheRegistry",
".",
"class",
")",
";",
"if",
"(",
"!",
"icr",
".",
"isInternalCache",
"(",
"cacheName",
")",
"||",
"icr",
".",
"internalCacheHasFlag",
"(",
"cacheName",
",",
"Flag",
".",
"QUERYABLE",
")",
")",
"{",
"AdvancedCache",
"<",
"?",
",",
"?",
">",
"cache",
"=",
"cr",
".",
"getComponent",
"(",
"Cache",
".",
"class",
")",
".",
"getAdvancedCache",
"(",
")",
";",
"ClassLoader",
"aggregatedClassLoader",
"=",
"makeAggregatedClassLoader",
"(",
"cr",
".",
"getGlobalComponentRegistry",
"(",
")",
".",
"getGlobalConfiguration",
"(",
")",
".",
"classLoader",
"(",
")",
")",
";",
"SearchIntegrator",
"searchFactory",
"=",
"null",
";",
"boolean",
"isIndexed",
"=",
"cfg",
".",
"indexing",
"(",
")",
".",
"index",
"(",
")",
".",
"isEnabled",
"(",
")",
";",
"if",
"(",
"isIndexed",
")",
"{",
"setBooleanQueryMaxClauseCount",
"(",
")",
";",
"cr",
".",
"registerComponent",
"(",
"new",
"ShardAllocationManagerImpl",
"(",
")",
",",
"ShardAllocatorManager",
".",
"class",
")",
";",
"searchFactory",
"=",
"createSearchIntegrator",
"(",
"cfg",
".",
"indexing",
"(",
")",
",",
"cr",
",",
"aggregatedClassLoader",
")",
";",
"KeyTransformationHandler",
"keyTransformationHandler",
"=",
"new",
"KeyTransformationHandler",
"(",
"aggregatedClassLoader",
")",
";",
"cr",
".",
"registerComponent",
"(",
"keyTransformationHandler",
",",
"KeyTransformationHandler",
".",
"class",
")",
";",
"createQueryInterceptorIfNeeded",
"(",
"cr",
".",
"getComponent",
"(",
"BasicComponentRegistry",
".",
"class",
")",
",",
"cfg",
",",
"cache",
",",
"searchFactory",
",",
"keyTransformationHandler",
")",
";",
"addCacheDependencyIfNeeded",
"(",
"cacheName",
",",
"cache",
".",
"getCacheManager",
"(",
")",
",",
"cfg",
".",
"indexing",
"(",
")",
")",
";",
"cr",
".",
"registerComponent",
"(",
"new",
"QueryBox",
"(",
")",
",",
"QueryBox",
".",
"class",
")",
";",
"}",
"registerMatcher",
"(",
"cr",
",",
"searchFactory",
",",
"aggregatedClassLoader",
")",
";",
"cr",
".",
"registerComponent",
"(",
"new",
"EmbeddedQueryEngine",
"(",
"cache",
",",
"isIndexed",
")",
",",
"EmbeddedQueryEngine",
".",
"class",
")",
";",
"}",
"}"
]
| Registers the Search interceptor in the cache before it gets started | [
"Registers",
"the",
"Search",
"interceptor",
"in",
"the",
"cache",
"before",
"it",
"gets",
"started"
]
| train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/impl/LifecycleManager.java#L126-L153 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java | GaliosFieldTableOps.polyAdd_S | public void polyAdd_S(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) {
"""
Adds two polynomials together.
<p>Coefficients for smallest powers are first, e.g. 2*x**3 + 8*x**2+1 = [1,0,2,8]</p>
@param polyA (Input) First polynomial
@param polyB (Input) Second polynomial
@param output (Output) Results of addition
"""
output.resize(Math.max(polyA.size,polyB.size));
int M = Math.min(polyA.size, polyB.size);
for (int i = M; i < polyA.size; i++) {
output.data[i] = polyA.data[i];
}
for (int i = M; i < polyB.size; i++) {
output.data[i] = polyB.data[i];
}
for (int i = 0; i < M; i++) {
output.data[i] = (byte)((polyA.data[i]&0xFF) ^ (polyB.data[i]&0xFF));
}
} | java | public void polyAdd_S(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) {
output.resize(Math.max(polyA.size,polyB.size));
int M = Math.min(polyA.size, polyB.size);
for (int i = M; i < polyA.size; i++) {
output.data[i] = polyA.data[i];
}
for (int i = M; i < polyB.size; i++) {
output.data[i] = polyB.data[i];
}
for (int i = 0; i < M; i++) {
output.data[i] = (byte)((polyA.data[i]&0xFF) ^ (polyB.data[i]&0xFF));
}
} | [
"public",
"void",
"polyAdd_S",
"(",
"GrowQueue_I8",
"polyA",
",",
"GrowQueue_I8",
"polyB",
",",
"GrowQueue_I8",
"output",
")",
"{",
"output",
".",
"resize",
"(",
"Math",
".",
"max",
"(",
"polyA",
".",
"size",
",",
"polyB",
".",
"size",
")",
")",
";",
"int",
"M",
"=",
"Math",
".",
"min",
"(",
"polyA",
".",
"size",
",",
"polyB",
".",
"size",
")",
";",
"for",
"(",
"int",
"i",
"=",
"M",
";",
"i",
"<",
"polyA",
".",
"size",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"polyA",
".",
"data",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"M",
";",
"i",
"<",
"polyB",
".",
"size",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"polyB",
".",
"data",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"M",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"polyA",
".",
"data",
"[",
"i",
"]",
"&",
"0xFF",
")",
"^",
"(",
"polyB",
".",
"data",
"[",
"i",
"]",
"&",
"0xFF",
")",
")",
";",
"}",
"}"
]
| Adds two polynomials together.
<p>Coefficients for smallest powers are first, e.g. 2*x**3 + 8*x**2+1 = [1,0,2,8]</p>
@param polyA (Input) First polynomial
@param polyB (Input) Second polynomial
@param output (Output) Results of addition | [
"Adds",
"two",
"polynomials",
"together",
"."
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java#L175-L189 |
TheHortonMachine/hortonmachine | hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java | EpanetWrapper.ENgetpatternvalue | public float ENgetpatternvalue( int index, int period ) throws EpanetException {
"""
Retrieves the multiplier factor for a specific time period in a time pattern.
@param index time pattern index.
@param period period within time pattern.
@return multiplier factor for the period.
@throws EpanetException
"""
float[] value = new float[1];
int errcode = epanet.ENgetpatternvalue(index, period, value);
checkError(errcode);
return value[0];
} | java | public float ENgetpatternvalue( int index, int period ) throws EpanetException {
float[] value = new float[1];
int errcode = epanet.ENgetpatternvalue(index, period, value);
checkError(errcode);
return value[0];
} | [
"public",
"float",
"ENgetpatternvalue",
"(",
"int",
"index",
",",
"int",
"period",
")",
"throws",
"EpanetException",
"{",
"float",
"[",
"]",
"value",
"=",
"new",
"float",
"[",
"1",
"]",
";",
"int",
"errcode",
"=",
"epanet",
".",
"ENgetpatternvalue",
"(",
"index",
",",
"period",
",",
"value",
")",
";",
"checkError",
"(",
"errcode",
")",
";",
"return",
"value",
"[",
"0",
"]",
";",
"}"
]
| Retrieves the multiplier factor for a specific time period in a time pattern.
@param index time pattern index.
@param period period within time pattern.
@return multiplier factor for the period.
@throws EpanetException | [
"Retrieves",
"the",
"multiplier",
"factor",
"for",
"a",
"specific",
"time",
"period",
"in",
"a",
"time",
"pattern",
"."
]
| train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java#L416-L422 |
ltsopensource/light-task-scheduler | lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/WebUtils.java | WebUtils.doPost | public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) throws IOException {
"""
执行HTTP POST请求。
@param url 请求地址
@param params 请求参数
@return 响应字符串
"""
return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
} | java | public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) throws IOException {
return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
} | [
"public",
"static",
"String",
"doPost",
"(",
"String",
"url",
",",
"Map",
"<",
"String",
",",
"String",
">",
"params",
",",
"int",
"connectTimeout",
",",
"int",
"readTimeout",
")",
"throws",
"IOException",
"{",
"return",
"doPost",
"(",
"url",
",",
"params",
",",
"DEFAULT_CHARSET",
",",
"connectTimeout",
",",
"readTimeout",
")",
";",
"}"
]
| 执行HTTP POST请求。
@param url 请求地址
@param params 请求参数
@return 响应字符串 | [
"执行HTTP",
"POST请求。"
]
| train | https://github.com/ltsopensource/light-task-scheduler/blob/64d3aa000ff5022be5e94f511b58f405e5f4c8eb/lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/WebUtils.java#L51-L53 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirLongsSketch.java | ReservoirLongsSketch.estimateSubsetSum | public SampleSubsetSummary estimateSubsetSum(final Predicate<Long> predicate) {
"""
Computes an estimated subset sum from the entire stream for objects matching a given
predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard
deviations.
<p>This is technically a heuristic method, and tries to err on the conservative side.</p>
@param predicate A predicate to use when identifying items.
@return A summary object containing the estimate, upper and lower bounds, and the total
sketch weight.
"""
if (itemsSeen_ == 0) {
return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0);
}
final long numSamples = getNumSamples();
final double samplingRate = numSamples / (double) itemsSeen_;
assert samplingRate >= 0.0;
assert samplingRate <= 1.0;
int predTrueCount = 0;
for (int i = 0; i < numSamples; ++i) {
if (predicate.test(data_[i])) {
++predTrueCount;
}
}
// if in exact mode, we can return an exact answer
if (itemsSeen_ <= reservoirSize_) {
return new SampleSubsetSummary(predTrueCount, predTrueCount, predTrueCount, numSamples);
}
final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, predTrueCount, samplingRate);
final double estimatedTrueFraction = (1.0 * predTrueCount) / numSamples;
final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, predTrueCount, samplingRate);
return new SampleSubsetSummary(
itemsSeen_ * lbTrueFraction,
itemsSeen_ * estimatedTrueFraction,
itemsSeen_ * ubTrueFraction,
itemsSeen_);
} | java | public SampleSubsetSummary estimateSubsetSum(final Predicate<Long> predicate) {
if (itemsSeen_ == 0) {
return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0);
}
final long numSamples = getNumSamples();
final double samplingRate = numSamples / (double) itemsSeen_;
assert samplingRate >= 0.0;
assert samplingRate <= 1.0;
int predTrueCount = 0;
for (int i = 0; i < numSamples; ++i) {
if (predicate.test(data_[i])) {
++predTrueCount;
}
}
// if in exact mode, we can return an exact answer
if (itemsSeen_ <= reservoirSize_) {
return new SampleSubsetSummary(predTrueCount, predTrueCount, predTrueCount, numSamples);
}
final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, predTrueCount, samplingRate);
final double estimatedTrueFraction = (1.0 * predTrueCount) / numSamples;
final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, predTrueCount, samplingRate);
return new SampleSubsetSummary(
itemsSeen_ * lbTrueFraction,
itemsSeen_ * estimatedTrueFraction,
itemsSeen_ * ubTrueFraction,
itemsSeen_);
} | [
"public",
"SampleSubsetSummary",
"estimateSubsetSum",
"(",
"final",
"Predicate",
"<",
"Long",
">",
"predicate",
")",
"{",
"if",
"(",
"itemsSeen_",
"==",
"0",
")",
"{",
"return",
"new",
"SampleSubsetSummary",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
")",
";",
"}",
"final",
"long",
"numSamples",
"=",
"getNumSamples",
"(",
")",
";",
"final",
"double",
"samplingRate",
"=",
"numSamples",
"/",
"(",
"double",
")",
"itemsSeen_",
";",
"assert",
"samplingRate",
">=",
"0.0",
";",
"assert",
"samplingRate",
"<=",
"1.0",
";",
"int",
"predTrueCount",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numSamples",
";",
"++",
"i",
")",
"{",
"if",
"(",
"predicate",
".",
"test",
"(",
"data_",
"[",
"i",
"]",
")",
")",
"{",
"++",
"predTrueCount",
";",
"}",
"}",
"// if in exact mode, we can return an exact answer",
"if",
"(",
"itemsSeen_",
"<=",
"reservoirSize_",
")",
"{",
"return",
"new",
"SampleSubsetSummary",
"(",
"predTrueCount",
",",
"predTrueCount",
",",
"predTrueCount",
",",
"numSamples",
")",
";",
"}",
"final",
"double",
"lbTrueFraction",
"=",
"pseudoHypergeometricLBonP",
"(",
"numSamples",
",",
"predTrueCount",
",",
"samplingRate",
")",
";",
"final",
"double",
"estimatedTrueFraction",
"=",
"(",
"1.0",
"*",
"predTrueCount",
")",
"/",
"numSamples",
";",
"final",
"double",
"ubTrueFraction",
"=",
"pseudoHypergeometricUBonP",
"(",
"numSamples",
",",
"predTrueCount",
",",
"samplingRate",
")",
";",
"return",
"new",
"SampleSubsetSummary",
"(",
"itemsSeen_",
"*",
"lbTrueFraction",
",",
"itemsSeen_",
"*",
"estimatedTrueFraction",
",",
"itemsSeen_",
"*",
"ubTrueFraction",
",",
"itemsSeen_",
")",
";",
"}"
]
| Computes an estimated subset sum from the entire stream for objects matching a given
predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard
deviations.
<p>This is technically a heuristic method, and tries to err on the conservative side.</p>
@param predicate A predicate to use when identifying items.
@return A summary object containing the estimate, upper and lower bounds, and the total
sketch weight. | [
"Computes",
"an",
"estimated",
"subset",
"sum",
"from",
"the",
"entire",
"stream",
"for",
"objects",
"matching",
"a",
"given",
"predicate",
".",
"Provides",
"a",
"lower",
"bound",
"estimate",
"and",
"upper",
"bound",
"using",
"a",
"target",
"of",
"2",
"standard",
"deviations",
"."
]
| train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirLongsSketch.java#L428-L458 |
nulab/backlog4j | src/main/java/com/nulabinc/backlog4j/api/option/UpdatePullRequestParams.java | UpdatePullRequestParams.attachmentIds | public UpdatePullRequestParams attachmentIds(List<Long> attachmentIds) {
"""
Sets the pull request attachment files.
@param attachmentIds the attachment file identifiers
@return UpdatePullRequestParams instance
"""
for (Long attachmentId : attachmentIds) {
parameters.add(new NameValuePair("attachmentId[]", attachmentId.toString()));
}
return this;
} | java | public UpdatePullRequestParams attachmentIds(List<Long> attachmentIds) {
for (Long attachmentId : attachmentIds) {
parameters.add(new NameValuePair("attachmentId[]", attachmentId.toString()));
}
return this;
} | [
"public",
"UpdatePullRequestParams",
"attachmentIds",
"(",
"List",
"<",
"Long",
">",
"attachmentIds",
")",
"{",
"for",
"(",
"Long",
"attachmentId",
":",
"attachmentIds",
")",
"{",
"parameters",
".",
"add",
"(",
"new",
"NameValuePair",
"(",
"\"attachmentId[]\"",
",",
"attachmentId",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| Sets the pull request attachment files.
@param attachmentIds the attachment file identifiers
@return UpdatePullRequestParams instance | [
"Sets",
"the",
"pull",
"request",
"attachment",
"files",
"."
]
| train | https://github.com/nulab/backlog4j/blob/862ae0586ad808b2ec413f665b8dfc0c9a107b4e/src/main/java/com/nulabinc/backlog4j/api/option/UpdatePullRequestParams.java#L130-L135 |
undertow-io/undertow | core/src/main/java/io/undertow/server/handlers/proxy/ProxyHandler.java | ProxyHandler.addRequestHeader | @Deprecated
public ProxyHandler addRequestHeader(final HttpString header, final ExchangeAttribute attribute) {
"""
Adds a request header to the outgoing request. If the header resolves to null or an empty string
it will not be added, however any existing header with the same name will be removed.
@param header The header name
@param attribute The header value attribute.
@return this
"""
requestHeaders.put(header, attribute);
return this;
} | java | @Deprecated
public ProxyHandler addRequestHeader(final HttpString header, final ExchangeAttribute attribute) {
requestHeaders.put(header, attribute);
return this;
} | [
"@",
"Deprecated",
"public",
"ProxyHandler",
"addRequestHeader",
"(",
"final",
"HttpString",
"header",
",",
"final",
"ExchangeAttribute",
"attribute",
")",
"{",
"requestHeaders",
".",
"put",
"(",
"header",
",",
"attribute",
")",
";",
"return",
"this",
";",
"}"
]
| Adds a request header to the outgoing request. If the header resolves to null or an empty string
it will not be added, however any existing header with the same name will be removed.
@param header The header name
@param attribute The header value attribute.
@return this | [
"Adds",
"a",
"request",
"header",
"to",
"the",
"outgoing",
"request",
".",
"If",
"the",
"header",
"resolves",
"to",
"null",
"or",
"an",
"empty",
"string",
"it",
"will",
"not",
"be",
"added",
"however",
"any",
"existing",
"header",
"with",
"the",
"same",
"name",
"will",
"be",
"removed",
"."
]
| train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyHandler.java#L223-L227 |
Netflix/netflix-commons | netflix-statistics/src/main/java/com/netflix/stats/distribution/DataBuffer.java | DataBuffer.getPercentiles | public double[] getPercentiles(double[] percents, double[] percentiles) {
"""
Gets the requested percentile statistics.
@param percents array of percentile values to compute,
which must be in the range {@code [0 .. 100]}
@param percentiles array to fill in with the percentile values;
must be the same length as {@code percents}
@return the {@code percentiles} array
@see <a href="http://en.wikipedia.org/wiki/Percentile">Percentile (Wikipedia)</a>
@see <a href="http://cnx.org/content/m10805/latest/">Percentile</a>
"""
for (int i = 0; i < percents.length; i++) {
percentiles[i] = computePercentile(percents[i]);
}
return percentiles;
} | java | public double[] getPercentiles(double[] percents, double[] percentiles) {
for (int i = 0; i < percents.length; i++) {
percentiles[i] = computePercentile(percents[i]);
}
return percentiles;
} | [
"public",
"double",
"[",
"]",
"getPercentiles",
"(",
"double",
"[",
"]",
"percents",
",",
"double",
"[",
"]",
"percentiles",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"percents",
".",
"length",
";",
"i",
"++",
")",
"{",
"percentiles",
"[",
"i",
"]",
"=",
"computePercentile",
"(",
"percents",
"[",
"i",
"]",
")",
";",
"}",
"return",
"percentiles",
";",
"}"
]
| Gets the requested percentile statistics.
@param percents array of percentile values to compute,
which must be in the range {@code [0 .. 100]}
@param percentiles array to fill in with the percentile values;
must be the same length as {@code percents}
@return the {@code percentiles} array
@see <a href="http://en.wikipedia.org/wiki/Percentile">Percentile (Wikipedia)</a>
@see <a href="http://cnx.org/content/m10805/latest/">Percentile</a> | [
"Gets",
"the",
"requested",
"percentile",
"statistics",
"."
]
| train | https://github.com/Netflix/netflix-commons/blob/7a158af76906d4a9b753e9344ce3e7abeb91dc01/netflix-statistics/src/main/java/com/netflix/stats/distribution/DataBuffer.java#L164-L169 |
apache/incubator-shardingsphere | sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/clause/expression/AliasExpressionParser.java | AliasExpressionParser.parseTableAlias | public Optional<String> parseTableAlias(final SQLStatement sqlStatement, final boolean setTableToken, final String tableName) {
"""
Parse alias for table.
@param sqlStatement SQL statement
@param setTableToken is add table token
@param tableName table name
@return alias for table
"""
if (lexerEngine.skipIfEqual(DefaultKeyword.AS)) {
return parseWithAs(sqlStatement, setTableToken, tableName);
}
if (lexerEngine.equalAny(getDefaultAvailableKeywordsForTableAlias()) || lexerEngine.equalAny(getCustomizedAvailableKeywordsForTableAlias())) {
return parseAlias(sqlStatement, setTableToken, tableName);
}
return Optional.absent();
} | java | public Optional<String> parseTableAlias(final SQLStatement sqlStatement, final boolean setTableToken, final String tableName) {
if (lexerEngine.skipIfEqual(DefaultKeyword.AS)) {
return parseWithAs(sqlStatement, setTableToken, tableName);
}
if (lexerEngine.equalAny(getDefaultAvailableKeywordsForTableAlias()) || lexerEngine.equalAny(getCustomizedAvailableKeywordsForTableAlias())) {
return parseAlias(sqlStatement, setTableToken, tableName);
}
return Optional.absent();
} | [
"public",
"Optional",
"<",
"String",
">",
"parseTableAlias",
"(",
"final",
"SQLStatement",
"sqlStatement",
",",
"final",
"boolean",
"setTableToken",
",",
"final",
"String",
"tableName",
")",
"{",
"if",
"(",
"lexerEngine",
".",
"skipIfEqual",
"(",
"DefaultKeyword",
".",
"AS",
")",
")",
"{",
"return",
"parseWithAs",
"(",
"sqlStatement",
",",
"setTableToken",
",",
"tableName",
")",
";",
"}",
"if",
"(",
"lexerEngine",
".",
"equalAny",
"(",
"getDefaultAvailableKeywordsForTableAlias",
"(",
")",
")",
"||",
"lexerEngine",
".",
"equalAny",
"(",
"getCustomizedAvailableKeywordsForTableAlias",
"(",
")",
")",
")",
"{",
"return",
"parseAlias",
"(",
"sqlStatement",
",",
"setTableToken",
",",
"tableName",
")",
";",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
]
| Parse alias for table.
@param sqlStatement SQL statement
@param setTableToken is add table token
@param tableName table name
@return alias for table | [
"Parse",
"alias",
"for",
"table",
"."
]
| train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/clause/expression/AliasExpressionParser.java#L103-L111 |
line/armeria | core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java | LoggingDecoratorBuilder.headersSanitizer | public T headersSanitizer(Function<? super HttpHeaders, ? extends HttpHeaders> headersSanitizer) {
"""
Sets the {@link Function} to use to sanitize request, response and trailing headers before logging.
It is common to have the {@link Function} that removes sensitive headers, like {@code "Cookie"} and
{@code "Set-Cookie"}, before logging. This method is a shortcut of:
<pre>{@code
builder.requestHeadersSanitizer(headersSanitizer);
builder.requestTrailersSanitizer(headersSanitizer);
builder.responseHeadersSanitizer(headersSanitizer);
builder.responseTrailersSanitizer(headersSanitizer);
}</pre>
@see #requestHeadersSanitizer(Function)
@see #requestTrailersSanitizer(Function)
@see #responseHeadersSanitizer(Function)
@see #responseTrailersSanitizer(Function)
"""
requireNonNull(headersSanitizer, "headersSanitizer");
requestHeadersSanitizer(headersSanitizer);
requestTrailersSanitizer(headersSanitizer);
responseHeadersSanitizer(headersSanitizer);
responseTrailersSanitizer(headersSanitizer);
return self();
} | java | public T headersSanitizer(Function<? super HttpHeaders, ? extends HttpHeaders> headersSanitizer) {
requireNonNull(headersSanitizer, "headersSanitizer");
requestHeadersSanitizer(headersSanitizer);
requestTrailersSanitizer(headersSanitizer);
responseHeadersSanitizer(headersSanitizer);
responseTrailersSanitizer(headersSanitizer);
return self();
} | [
"public",
"T",
"headersSanitizer",
"(",
"Function",
"<",
"?",
"super",
"HttpHeaders",
",",
"?",
"extends",
"HttpHeaders",
">",
"headersSanitizer",
")",
"{",
"requireNonNull",
"(",
"headersSanitizer",
",",
"\"headersSanitizer\"",
")",
";",
"requestHeadersSanitizer",
"(",
"headersSanitizer",
")",
";",
"requestTrailersSanitizer",
"(",
"headersSanitizer",
")",
";",
"responseHeadersSanitizer",
"(",
"headersSanitizer",
")",
";",
"responseTrailersSanitizer",
"(",
"headersSanitizer",
")",
";",
"return",
"self",
"(",
")",
";",
"}"
]
| Sets the {@link Function} to use to sanitize request, response and trailing headers before logging.
It is common to have the {@link Function} that removes sensitive headers, like {@code "Cookie"} and
{@code "Set-Cookie"}, before logging. This method is a shortcut of:
<pre>{@code
builder.requestHeadersSanitizer(headersSanitizer);
builder.requestTrailersSanitizer(headersSanitizer);
builder.responseHeadersSanitizer(headersSanitizer);
builder.responseTrailersSanitizer(headersSanitizer);
}</pre>
@see #requestHeadersSanitizer(Function)
@see #requestTrailersSanitizer(Function)
@see #responseHeadersSanitizer(Function)
@see #responseTrailersSanitizer(Function) | [
"Sets",
"the",
"{",
"@link",
"Function",
"}",
"to",
"use",
"to",
"sanitize",
"request",
"response",
"and",
"trailing",
"headers",
"before",
"logging",
".",
"It",
"is",
"common",
"to",
"have",
"the",
"{",
"@link",
"Function",
"}",
"that",
"removes",
"sensitive",
"headers",
"like",
"{",
"@code",
"Cookie",
"}",
"and",
"{",
"@code",
"Set",
"-",
"Cookie",
"}",
"before",
"logging",
".",
"This",
"method",
"is",
"a",
"shortcut",
"of",
":",
"<pre",
">",
"{",
"@code",
"builder",
".",
"requestHeadersSanitizer",
"(",
"headersSanitizer",
")",
";",
"builder",
".",
"requestTrailersSanitizer",
"(",
"headersSanitizer",
")",
";",
"builder",
".",
"responseHeadersSanitizer",
"(",
"headersSanitizer",
")",
";",
"builder",
".",
"responseTrailersSanitizer",
"(",
"headersSanitizer",
")",
";",
"}",
"<",
"/",
"pre",
">"
]
| train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java#L188-L195 |
Azure/azure-sdk-for-java | mediaservices/data-plane/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java | Asset.unlinkDeliveryPolicy | public static EntityUnlinkOperation unlinkDeliveryPolicy(String assetId,
String adpId) {
"""
unlink an asset delivery policy
@param assetId
the asset id
@param adpId
the asset delivery policy id
@return the entity action operation
"""
return new EntityUnlinkOperation(ENTITY_SET, assetId, "DeliveryPolicies", adpId);
} | java | public static EntityUnlinkOperation unlinkDeliveryPolicy(String assetId,
String adpId) {
return new EntityUnlinkOperation(ENTITY_SET, assetId, "DeliveryPolicies", adpId);
} | [
"public",
"static",
"EntityUnlinkOperation",
"unlinkDeliveryPolicy",
"(",
"String",
"assetId",
",",
"String",
"adpId",
")",
"{",
"return",
"new",
"EntityUnlinkOperation",
"(",
"ENTITY_SET",
",",
"assetId",
",",
"\"DeliveryPolicies\"",
",",
"adpId",
")",
";",
"}"
]
| unlink an asset delivery policy
@param assetId
the asset id
@param adpId
the asset delivery policy id
@return the entity action operation | [
"unlink",
"an",
"asset",
"delivery",
"policy"
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/data-plane/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java#L386-L389 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCircuitPeeringsInner.java | ExpressRouteCircuitPeeringsInner.createOrUpdate | public ExpressRouteCircuitPeeringInner createOrUpdate(String resourceGroupName, String circuitName, String peeringName, ExpressRouteCircuitPeeringInner peeringParameters) {
"""
Creates or updates a peering in the specified express route circuits.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param peeringName The name of the peering.
@param peeringParameters Parameters supplied to the create or update express route circuit peering operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCircuitPeeringInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, peeringParameters).toBlocking().last().body();
} | java | public ExpressRouteCircuitPeeringInner createOrUpdate(String resourceGroupName, String circuitName, String peeringName, ExpressRouteCircuitPeeringInner peeringParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, peeringParameters).toBlocking().last().body();
} | [
"public",
"ExpressRouteCircuitPeeringInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"circuitName",
",",
"String",
"peeringName",
",",
"ExpressRouteCircuitPeeringInner",
"peeringParameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"circuitName",
",",
"peeringName",
",",
"peeringParameters",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Creates or updates a peering in the specified express route circuits.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param peeringName The name of the peering.
@param peeringParameters Parameters supplied to the create or update express route circuit peering operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCircuitPeeringInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"peering",
"in",
"the",
"specified",
"express",
"route",
"circuits",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCircuitPeeringsInner.java#L362-L364 |
hal/core | gui/src/main/java/org/jboss/as/console/client/shared/runtime/StandaloneRestartReload.java | StandaloneRestartReload.checkServerState | public void checkServerState(final AsyncCallback<Boolean> callback, final String standBy, final String success) {
"""
Simply query the process state attribute to get to the required headers
"""
// :read-attribute(name=process-type)
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(NAME).set("server-state");
operation.get(ADDRESS).setEmptyList();
dispatchAsync.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if (response.isFailure()) {
callback.onFailure(new RuntimeException("Failed to poll server state"));
} else {
// TODO: only works when this response changes the reload state
String outcome = response.get(RESULT).asString();
boolean keepRunning = !outcome.equalsIgnoreCase("running");//reloadState.isStaleModel();
if (!keepRunning) {
// clear state
reloadState.reset();
Console.info(Console.MESSAGES.successful(success));
// clear reload state
eventBus.fireEvent(new ReloadEvent());
}
callback.onSuccess(keepRunning);
}
}
@Override
public void onFailure(Throwable caught) {
Console.getMessageCenter().notify(new Message(standBy, caught.getMessage(), Message.Severity.Warning));
}
});
} | java | public void checkServerState(final AsyncCallback<Boolean> callback, final String standBy, final String success) {
// :read-attribute(name=process-type)
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(NAME).set("server-state");
operation.get(ADDRESS).setEmptyList();
dispatchAsync.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if (response.isFailure()) {
callback.onFailure(new RuntimeException("Failed to poll server state"));
} else {
// TODO: only works when this response changes the reload state
String outcome = response.get(RESULT).asString();
boolean keepRunning = !outcome.equalsIgnoreCase("running");//reloadState.isStaleModel();
if (!keepRunning) {
// clear state
reloadState.reset();
Console.info(Console.MESSAGES.successful(success));
// clear reload state
eventBus.fireEvent(new ReloadEvent());
}
callback.onSuccess(keepRunning);
}
}
@Override
public void onFailure(Throwable caught) {
Console.getMessageCenter().notify(new Message(standBy, caught.getMessage(), Message.Severity.Warning));
}
});
} | [
"public",
"void",
"checkServerState",
"(",
"final",
"AsyncCallback",
"<",
"Boolean",
">",
"callback",
",",
"final",
"String",
"standBy",
",",
"final",
"String",
"success",
")",
"{",
"// :read-attribute(name=process-type)",
"final",
"ModelNode",
"operation",
"=",
"new",
"ModelNode",
"(",
")",
";",
"operation",
".",
"get",
"(",
"OP",
")",
".",
"set",
"(",
"READ_ATTRIBUTE_OPERATION",
")",
";",
"operation",
".",
"get",
"(",
"NAME",
")",
".",
"set",
"(",
"\"server-state\"",
")",
";",
"operation",
".",
"get",
"(",
"ADDRESS",
")",
".",
"setEmptyList",
"(",
")",
";",
"dispatchAsync",
".",
"execute",
"(",
"new",
"DMRAction",
"(",
"operation",
")",
",",
"new",
"SimpleCallback",
"<",
"DMRResponse",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"DMRResponse",
"result",
")",
"{",
"ModelNode",
"response",
"=",
"result",
".",
"get",
"(",
")",
";",
"if",
"(",
"response",
".",
"isFailure",
"(",
")",
")",
"{",
"callback",
".",
"onFailure",
"(",
"new",
"RuntimeException",
"(",
"\"Failed to poll server state\"",
")",
")",
";",
"}",
"else",
"{",
"// TODO: only works when this response changes the reload state",
"String",
"outcome",
"=",
"response",
".",
"get",
"(",
"RESULT",
")",
".",
"asString",
"(",
")",
";",
"boolean",
"keepRunning",
"=",
"!",
"outcome",
".",
"equalsIgnoreCase",
"(",
"\"running\"",
")",
";",
"//reloadState.isStaleModel();",
"if",
"(",
"!",
"keepRunning",
")",
"{",
"// clear state",
"reloadState",
".",
"reset",
"(",
")",
";",
"Console",
".",
"info",
"(",
"Console",
".",
"MESSAGES",
".",
"successful",
"(",
"success",
")",
")",
";",
"// clear reload state",
"eventBus",
".",
"fireEvent",
"(",
"new",
"ReloadEvent",
"(",
")",
")",
";",
"}",
"callback",
".",
"onSuccess",
"(",
"keepRunning",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"Throwable",
"caught",
")",
"{",
"Console",
".",
"getMessageCenter",
"(",
")",
".",
"notify",
"(",
"new",
"Message",
"(",
"standBy",
",",
"caught",
".",
"getMessage",
"(",
")",
",",
"Message",
".",
"Severity",
".",
"Warning",
")",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Simply query the process state attribute to get to the required headers | [
"Simply",
"query",
"the",
"process",
"state",
"attribute",
"to",
"get",
"to",
"the",
"required",
"headers"
]
| train | https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/client/shared/runtime/StandaloneRestartReload.java#L118-L160 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/event/EventUtils.java | EventUtils.addEventListener | public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
"""
Adds an event listener to the specified source. This looks for an "add" method corresponding to the event
type (addActionListener, for example).
@param eventSource the event source
@param listenerType the event listener type
@param listener the listener
@param <L> the event listener type
@throws IllegalArgumentException if the object doesn't support the listener type
"""
try {
MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
} catch (final NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
+ " does not have a public add" + listenerType.getSimpleName()
+ " method which takes a parameter of type " + listenerType.getName() + ".");
} catch (final IllegalAccessException e) {
throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
+ " does not have an accessible add" + listenerType.getSimpleName ()
+ " method which takes a parameter of type " + listenerType.getName() + ".");
} catch (final InvocationTargetException e) {
throw new RuntimeException("Unable to add listener.", e.getCause());
}
} | java | public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
try {
MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
} catch (final NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
+ " does not have a public add" + listenerType.getSimpleName()
+ " method which takes a parameter of type " + listenerType.getName() + ".");
} catch (final IllegalAccessException e) {
throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
+ " does not have an accessible add" + listenerType.getSimpleName ()
+ " method which takes a parameter of type " + listenerType.getName() + ".");
} catch (final InvocationTargetException e) {
throw new RuntimeException("Unable to add listener.", e.getCause());
}
} | [
"public",
"static",
"<",
"L",
">",
"void",
"addEventListener",
"(",
"final",
"Object",
"eventSource",
",",
"final",
"Class",
"<",
"L",
">",
"listenerType",
",",
"final",
"L",
"listener",
")",
"{",
"try",
"{",
"MethodUtils",
".",
"invokeMethod",
"(",
"eventSource",
",",
"\"add\"",
"+",
"listenerType",
".",
"getSimpleName",
"(",
")",
",",
"listener",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Class \"",
"+",
"eventSource",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\" does not have a public add\"",
"+",
"listenerType",
".",
"getSimpleName",
"(",
")",
"+",
"\" method which takes a parameter of type \"",
"+",
"listenerType",
".",
"getName",
"(",
")",
"+",
"\".\"",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Class \"",
"+",
"eventSource",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\" does not have an accessible add\"",
"+",
"listenerType",
".",
"getSimpleName",
"(",
")",
"+",
"\" method which takes a parameter of type \"",
"+",
"listenerType",
".",
"getName",
"(",
")",
"+",
"\".\"",
")",
";",
"}",
"catch",
"(",
"final",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to add listener.\"",
",",
"e",
".",
"getCause",
"(",
")",
")",
";",
"}",
"}"
]
| Adds an event listener to the specified source. This looks for an "add" method corresponding to the event
type (addActionListener, for example).
@param eventSource the event source
@param listenerType the event listener type
@param listener the listener
@param <L> the event listener type
@throws IllegalArgumentException if the object doesn't support the listener type | [
"Adds",
"an",
"event",
"listener",
"to",
"the",
"specified",
"source",
".",
"This",
"looks",
"for",
"an",
"add",
"method",
"corresponding",
"to",
"the",
"event",
"type",
"(",
"addActionListener",
"for",
"example",
")",
".",
"@param",
"eventSource",
"the",
"event",
"source",
"@param",
"listenerType",
"the",
"event",
"listener",
"type",
"@param",
"listener",
"the",
"listener",
"@param",
"<L",
">",
"the",
"event",
"listener",
"type"
]
| train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/event/EventUtils.java#L50-L64 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/VariablesInner.java | VariablesInner.get | public VariableInner get(String resourceGroupName, String automationAccountName, String variableName) {
"""
Retrieve the variable identified by variable name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param variableName The name of variable.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VariableInner object if successful.
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, variableName).toBlocking().single().body();
} | java | public VariableInner get(String resourceGroupName, String automationAccountName, String variableName) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, variableName).toBlocking().single().body();
} | [
"public",
"VariableInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"variableName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"variableName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Retrieve the variable identified by variable name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param variableName The name of variable.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VariableInner object if successful. | [
"Retrieve",
"the",
"variable",
"identified",
"by",
"variable",
"name",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/VariablesInner.java#L393-L395 |
leancloud/java-sdk-all | android-sdk/mixpush-android/src/main/java/cn/leancloud/AVHMSPushMessageReceiver.java | AVHMSPushMessageReceiver.onPushMsg | @Override
public void onPushMsg(Context var1, byte[] var2, String var3) {
"""
收到透传消息
消息格式类似于:
{"alert":"", "title":"", "action":"", "silent":true}
SDK 内部会转换成 {"content":\\"{"alert":"", "title":"", "action":"", "silent":true}\\"}
再发送给本地的 Receiver。
所以,开发者如果想自己处理透传消息,则需要从 Receiver#onReceive(Context context, Intent intent) 的 intent 中通过
getStringExtra("content") 获取到实际的数据。
@param var1
@param var2
@param var3
"""
try {
String message = new String(var2, "UTF-8");
AndroidNotificationManager androidNotificationManager = AndroidNotificationManager.getInstance();
androidNotificationManager.processMixPushMessage(message);
} catch (Exception ex) {
LOGGER.e("failed to process PushMessage.", ex);
}
} | java | @Override
public void onPushMsg(Context var1, byte[] var2, String var3) {
try {
String message = new String(var2, "UTF-8");
AndroidNotificationManager androidNotificationManager = AndroidNotificationManager.getInstance();
androidNotificationManager.processMixPushMessage(message);
} catch (Exception ex) {
LOGGER.e("failed to process PushMessage.", ex);
}
} | [
"@",
"Override",
"public",
"void",
"onPushMsg",
"(",
"Context",
"var1",
",",
"byte",
"[",
"]",
"var2",
",",
"String",
"var3",
")",
"{",
"try",
"{",
"String",
"message",
"=",
"new",
"String",
"(",
"var2",
",",
"\"UTF-8\"",
")",
";",
"AndroidNotificationManager",
"androidNotificationManager",
"=",
"AndroidNotificationManager",
".",
"getInstance",
"(",
")",
";",
"androidNotificationManager",
".",
"processMixPushMessage",
"(",
"message",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"LOGGER",
".",
"e",
"(",
"\"failed to process PushMessage.\"",
",",
"ex",
")",
";",
"}",
"}"
]
| 收到透传消息
消息格式类似于:
{"alert":"", "title":"", "action":"", "silent":true}
SDK 内部会转换成 {"content":\\"{"alert":"", "title":"", "action":"", "silent":true}\\"}
再发送给本地的 Receiver。
所以,开发者如果想自己处理透传消息,则需要从 Receiver#onReceive(Context context, Intent intent) 的 intent 中通过
getStringExtra("content") 获取到实际的数据。
@param var1
@param var2
@param var3 | [
"收到透传消息"
]
| train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/mixpush-android/src/main/java/cn/leancloud/AVHMSPushMessageReceiver.java#L81-L90 |
gallandarakhneorg/afc | advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java | BusItinerary.insertBusHaltAfter | public BusItineraryHalt insertBusHaltAfter(BusItineraryHalt afterHalt, String name, BusItineraryHaltType type) {
"""
Insert newHalt after afterHalt in the ordered list of {@link BusItineraryHalt}.
@param afterHalt the halt where insert the new halt
@param name name of the new halt
@param type the type of bus halt
@return the added bus halt, otherwise <code>null</code>
"""
return insertBusHaltAfter(afterHalt, null, name, type);
} | java | public BusItineraryHalt insertBusHaltAfter(BusItineraryHalt afterHalt, String name, BusItineraryHaltType type) {
return insertBusHaltAfter(afterHalt, null, name, type);
} | [
"public",
"BusItineraryHalt",
"insertBusHaltAfter",
"(",
"BusItineraryHalt",
"afterHalt",
",",
"String",
"name",
",",
"BusItineraryHaltType",
"type",
")",
"{",
"return",
"insertBusHaltAfter",
"(",
"afterHalt",
",",
"null",
",",
"name",
",",
"type",
")",
";",
"}"
]
| Insert newHalt after afterHalt in the ordered list of {@link BusItineraryHalt}.
@param afterHalt the halt where insert the new halt
@param name name of the new halt
@param type the type of bus halt
@return the added bus halt, otherwise <code>null</code> | [
"Insert",
"newHalt",
"after",
"afterHalt",
"in",
"the",
"ordered",
"list",
"of",
"{",
"@link",
"BusItineraryHalt",
"}",
"."
]
| train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java#L1175-L1177 |
arxanchain/java-common | src/main/java/com/arxanfintech/common/crypto/core/ECKey.java | ECKey.recoverPubBytesFromSignature | public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) {
"""
<p>
Given the components of a signature and a selector value, recover and return
the public key that generated the signature according to the algorithm in
SEC1v2 section 4.1.6.
</p>
<p>
The recId is an index from 0 to 3 which indicates which of the 4 possible
keys is the correct one. Because the key recovery operation yields multiple
potential keys, the correct key must either be stored alongside the
signature, or you must be willing to try each recId in turn until you find
one that outputs the key you are expecting.
</p>
<p>
If this method returns null it means recovery was not possible and recId
should be iterated.
</p>
<p>
Given the above two points, a correct usage of this method is inside a for
loop from 0 to 3, and if the output is null OR a key that is not the one you
expect, you try again with the next recId.
</p>
@param recId
Which possible key to recover.
@param sig
the R and S components of the signature, wrapped.
@param messageHash
Hash of the data that was signed.
@return 65-byte encoded public key
"""
check(recId >= 0, "recId must be positive");
check(sig.r.signum() >= 0, "r must be positive");
check(sig.s.signum() >= 0, "s must be positive");
check(messageHash != null, "messageHash must not be null");
// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)
// 1.1 Let x = r + jn
BigInteger n = CURVE.getN(); // Curve order.
BigInteger i = BigInteger.valueOf((long) recId / 2);
BigInteger x = sig.r.add(i.multiply(n));
// 1.2. Convert the integer x to an octet string X of length mlen using the
// conversion routine
// specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
// 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve
// point R using the
// conversion routine specified in Section 2.3.4. If this conversion routine
// outputs “invalid”, then
// do another iteration of Step 1.
//
// More concisely, what these points mean is to use X as a compressed public
// key.
ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime.
if (x.compareTo(prime) >= 0) {
// Cannot have point co-ordinates larger than this as everything takes place
// modulo Q.
return null;
}
// Compressed keys require you to know an extra bit of data about the y-coord as
// there are two possibilities.
// So it's encoded in the recId.
ECPoint R = decompressKey(x, (recId & 1) == 1);
// 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers
// responsibility).
if (!R.multiply(n).isInfinity())
return null;
// 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
BigInteger e = new BigInteger(1, messageHash);
// 1.6. For k from 1 to 2 do the following. (loop is outside this function via
// iterating recId)
// 1.6.1. Compute a candidate public key as:
// Q = mi(r) * (sR - eG)
//
// Where mi(x) is the modular multiplicative inverse. We transform this into the
// following:
// Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
// Where -e is the modular additive inverse of e, that is z such that z + e = 0
// (mod n). In the above equation
// ** is point multiplication and + is point addition (the EC group operator).
//
// We can find the additive inverse by subtracting e from zero then taking the
// mod. For example the additive
// inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
BigInteger rInv = sig.r.modInverse(n);
BigInteger srInv = rInv.multiply(sig.s).mod(n);
BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
return q.getEncoded(/* compressed */ false);
} | java | public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) {
check(recId >= 0, "recId must be positive");
check(sig.r.signum() >= 0, "r must be positive");
check(sig.s.signum() >= 0, "s must be positive");
check(messageHash != null, "messageHash must not be null");
// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)
// 1.1 Let x = r + jn
BigInteger n = CURVE.getN(); // Curve order.
BigInteger i = BigInteger.valueOf((long) recId / 2);
BigInteger x = sig.r.add(i.multiply(n));
// 1.2. Convert the integer x to an octet string X of length mlen using the
// conversion routine
// specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
// 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve
// point R using the
// conversion routine specified in Section 2.3.4. If this conversion routine
// outputs “invalid”, then
// do another iteration of Step 1.
//
// More concisely, what these points mean is to use X as a compressed public
// key.
ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime.
if (x.compareTo(prime) >= 0) {
// Cannot have point co-ordinates larger than this as everything takes place
// modulo Q.
return null;
}
// Compressed keys require you to know an extra bit of data about the y-coord as
// there are two possibilities.
// So it's encoded in the recId.
ECPoint R = decompressKey(x, (recId & 1) == 1);
// 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers
// responsibility).
if (!R.multiply(n).isInfinity())
return null;
// 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
BigInteger e = new BigInteger(1, messageHash);
// 1.6. For k from 1 to 2 do the following. (loop is outside this function via
// iterating recId)
// 1.6.1. Compute a candidate public key as:
// Q = mi(r) * (sR - eG)
//
// Where mi(x) is the modular multiplicative inverse. We transform this into the
// following:
// Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
// Where -e is the modular additive inverse of e, that is z such that z + e = 0
// (mod n). In the above equation
// ** is point multiplication and + is point addition (the EC group operator).
//
// We can find the additive inverse by subtracting e from zero then taking the
// mod. For example the additive
// inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
BigInteger rInv = sig.r.modInverse(n);
BigInteger srInv = rInv.multiply(sig.s).mod(n);
BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
return q.getEncoded(/* compressed */ false);
} | [
"public",
"static",
"byte",
"[",
"]",
"recoverPubBytesFromSignature",
"(",
"int",
"recId",
",",
"ECDSASignature",
"sig",
",",
"byte",
"[",
"]",
"messageHash",
")",
"{",
"check",
"(",
"recId",
">=",
"0",
",",
"\"recId must be positive\"",
")",
";",
"check",
"(",
"sig",
".",
"r",
".",
"signum",
"(",
")",
">=",
"0",
",",
"\"r must be positive\"",
")",
";",
"check",
"(",
"sig",
".",
"s",
".",
"signum",
"(",
")",
">=",
"0",
",",
"\"s must be positive\"",
")",
";",
"check",
"(",
"messageHash",
"!=",
"null",
",",
"\"messageHash must not be null\"",
")",
";",
"// 1.0 For j from 0 to h (h == recId here and the loop is outside this function)",
"// 1.1 Let x = r + jn",
"BigInteger",
"n",
"=",
"CURVE",
".",
"getN",
"(",
")",
";",
"// Curve order.",
"BigInteger",
"i",
"=",
"BigInteger",
".",
"valueOf",
"(",
"(",
"long",
")",
"recId",
"/",
"2",
")",
";",
"BigInteger",
"x",
"=",
"sig",
".",
"r",
".",
"add",
"(",
"i",
".",
"multiply",
"(",
"n",
")",
")",
";",
"// 1.2. Convert the integer x to an octet string X of length mlen using the",
"// conversion routine",
"// specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.",
"// 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve",
"// point R using the",
"// conversion routine specified in Section 2.3.4. If this conversion routine",
"// outputs “invalid”, then",
"// do another iteration of Step 1.",
"//",
"// More concisely, what these points mean is to use X as a compressed public",
"// key.",
"ECCurve",
".",
"Fp",
"curve",
"=",
"(",
"ECCurve",
".",
"Fp",
")",
"CURVE",
".",
"getCurve",
"(",
")",
";",
"BigInteger",
"prime",
"=",
"curve",
".",
"getQ",
"(",
")",
";",
"// Bouncy Castle is not consistent about the letter it uses for the prime.",
"if",
"(",
"x",
".",
"compareTo",
"(",
"prime",
")",
">=",
"0",
")",
"{",
"// Cannot have point co-ordinates larger than this as everything takes place",
"// modulo Q.",
"return",
"null",
";",
"}",
"// Compressed keys require you to know an extra bit of data about the y-coord as",
"// there are two possibilities.",
"// So it's encoded in the recId.",
"ECPoint",
"R",
"=",
"decompressKey",
"(",
"x",
",",
"(",
"recId",
"&",
"1",
")",
"==",
"1",
")",
";",
"// 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers",
"// responsibility).",
"if",
"(",
"!",
"R",
".",
"multiply",
"(",
"n",
")",
".",
"isInfinity",
"(",
")",
")",
"return",
"null",
";",
"// 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.",
"BigInteger",
"e",
"=",
"new",
"BigInteger",
"(",
"1",
",",
"messageHash",
")",
";",
"// 1.6. For k from 1 to 2 do the following. (loop is outside this function via",
"// iterating recId)",
"// 1.6.1. Compute a candidate public key as:",
"// Q = mi(r) * (sR - eG)",
"//",
"// Where mi(x) is the modular multiplicative inverse. We transform this into the",
"// following:",
"// Q = (mi(r) * s ** R) + (mi(r) * -e ** G)",
"// Where -e is the modular additive inverse of e, that is z such that z + e = 0",
"// (mod n). In the above equation",
"// ** is point multiplication and + is point addition (the EC group operator).",
"//",
"// We can find the additive inverse by subtracting e from zero then taking the",
"// mod. For example the additive",
"// inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.",
"BigInteger",
"eInv",
"=",
"BigInteger",
".",
"ZERO",
".",
"subtract",
"(",
"e",
")",
".",
"mod",
"(",
"n",
")",
";",
"BigInteger",
"rInv",
"=",
"sig",
".",
"r",
".",
"modInverse",
"(",
"n",
")",
";",
"BigInteger",
"srInv",
"=",
"rInv",
".",
"multiply",
"(",
"sig",
".",
"s",
")",
".",
"mod",
"(",
"n",
")",
";",
"BigInteger",
"eInvrInv",
"=",
"rInv",
".",
"multiply",
"(",
"eInv",
")",
".",
"mod",
"(",
"n",
")",
";",
"ECPoint",
".",
"Fp",
"q",
"=",
"(",
"ECPoint",
".",
"Fp",
")",
"ECAlgorithms",
".",
"sumOfTwoMultiplies",
"(",
"CURVE",
".",
"getG",
"(",
")",
",",
"eInvrInv",
",",
"R",
",",
"srInv",
")",
";",
"return",
"q",
".",
"getEncoded",
"(",
"/* compressed */",
"false",
")",
";",
"}"
]
| <p>
Given the components of a signature and a selector value, recover and return
the public key that generated the signature according to the algorithm in
SEC1v2 section 4.1.6.
</p>
<p>
The recId is an index from 0 to 3 which indicates which of the 4 possible
keys is the correct one. Because the key recovery operation yields multiple
potential keys, the correct key must either be stored alongside the
signature, or you must be willing to try each recId in turn until you find
one that outputs the key you are expecting.
</p>
<p>
If this method returns null it means recovery was not possible and recId
should be iterated.
</p>
<p>
Given the above two points, a correct usage of this method is inside a for
loop from 0 to 3, and if the output is null OR a key that is not the one you
expect, you try again with the next recId.
</p>
@param recId
Which possible key to recover.
@param sig
the R and S components of the signature, wrapped.
@param messageHash
Hash of the data that was signed.
@return 65-byte encoded public key | [
"<p",
">",
"Given",
"the",
"components",
"of",
"a",
"signature",
"and",
"a",
"selector",
"value",
"recover",
"and",
"return",
"the",
"public",
"key",
"that",
"generated",
"the",
"signature",
"according",
"to",
"the",
"algorithm",
"in",
"SEC1v2",
"section",
"4",
".",
"1",
".",
"6",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/crypto/core/ECKey.java#L1135-L1194 |
junit-team/junit4 | src/main/java/org/junit/Assert.java | Assert.assertNotEquals | public static void assertNotEquals(String message, long unexpected, long actual) {
"""
Asserts that two longs are <b>not</b> equals. If they are, an
{@link AssertionError} is thrown with the given message.
@param message the identifying message for the {@link AssertionError} (<code>null</code>
okay)
@param unexpected unexpected value to check
@param actual the value to check against <code>unexpected</code>
"""
if (unexpected == actual) {
failEquals(message, Long.valueOf(actual));
}
} | java | public static void assertNotEquals(String message, long unexpected, long actual) {
if (unexpected == actual) {
failEquals(message, Long.valueOf(actual));
}
} | [
"public",
"static",
"void",
"assertNotEquals",
"(",
"String",
"message",
",",
"long",
"unexpected",
",",
"long",
"actual",
")",
"{",
"if",
"(",
"unexpected",
"==",
"actual",
")",
"{",
"failEquals",
"(",
"message",
",",
"Long",
".",
"valueOf",
"(",
"actual",
")",
")",
";",
"}",
"}"
]
| Asserts that two longs are <b>not</b> equals. If they are, an
{@link AssertionError} is thrown with the given message.
@param message the identifying message for the {@link AssertionError} (<code>null</code>
okay)
@param unexpected unexpected value to check
@param actual the value to check against <code>unexpected</code> | [
"Asserts",
"that",
"two",
"longs",
"are",
"<b",
">",
"not<",
"/",
"b",
">",
"equals",
".",
"If",
"they",
"are",
"an",
"{",
"@link",
"AssertionError",
"}",
"is",
"thrown",
"with",
"the",
"given",
"message",
"."
]
| train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/Assert.java#L199-L203 |
droidpl/android-json-viewer | android-json-viewer/src/main/java/com/github/droidpl/android/jsonviewer/JSONViewerActivity.java | JSONViewerActivity.startActivity | public static void startActivity(@NonNull Context context, @Nullable JSONArray jsonArray) {
"""
Starts an activity with a json array.
@param context The context to start the activity.
@param jsonArray The json array.
"""
Intent intent = new Intent(context, JSONViewerActivity.class);
Bundle bundle = new Bundle();
if (jsonArray != null) {
bundle.putString(JSON_ARRAY_STATE, jsonArray.toString());
}
intent.putExtras(bundle);
context.startActivity(intent);
} | java | public static void startActivity(@NonNull Context context, @Nullable JSONArray jsonArray) {
Intent intent = new Intent(context, JSONViewerActivity.class);
Bundle bundle = new Bundle();
if (jsonArray != null) {
bundle.putString(JSON_ARRAY_STATE, jsonArray.toString());
}
intent.putExtras(bundle);
context.startActivity(intent);
} | [
"public",
"static",
"void",
"startActivity",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"@",
"Nullable",
"JSONArray",
"jsonArray",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"context",
",",
"JSONViewerActivity",
".",
"class",
")",
";",
"Bundle",
"bundle",
"=",
"new",
"Bundle",
"(",
")",
";",
"if",
"(",
"jsonArray",
"!=",
"null",
")",
"{",
"bundle",
".",
"putString",
"(",
"JSON_ARRAY_STATE",
",",
"jsonArray",
".",
"toString",
"(",
")",
")",
";",
"}",
"intent",
".",
"putExtras",
"(",
"bundle",
")",
";",
"context",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
]
| Starts an activity with a json array.
@param context The context to start the activity.
@param jsonArray The json array. | [
"Starts",
"an",
"activity",
"with",
"a",
"json",
"array",
"."
]
| train | https://github.com/droidpl/android-json-viewer/blob/7345a7a0e6636399015a03fad8243a47f5fcdd8f/android-json-viewer/src/main/java/com/github/droidpl/android/jsonviewer/JSONViewerActivity.java#L58-L66 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/base/CommandInterceptor.java | CommandInterceptor.handleDefault | @Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
"""
The default behaviour of the visitXXX methods, which is to ignore the call and pass the call up to the next
interceptor in the chain.
@param ctx invocation context
@param command command to invoke
@return return value
@throws Throwable in the event of problems
"""
return invokeNextInterceptor(ctx, command);
} | java | @Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextInterceptor(ctx, command);
} | [
"@",
"Override",
"protected",
"Object",
"handleDefault",
"(",
"InvocationContext",
"ctx",
",",
"VisitableCommand",
"command",
")",
"throws",
"Throwable",
"{",
"return",
"invokeNextInterceptor",
"(",
"ctx",
",",
"command",
")",
";",
"}"
]
| The default behaviour of the visitXXX methods, which is to ignore the call and pass the call up to the next
interceptor in the chain.
@param ctx invocation context
@param command command to invoke
@return return value
@throws Throwable in the event of problems | [
"The",
"default",
"behaviour",
"of",
"the",
"visitXXX",
"methods",
"which",
"is",
"to",
"ignore",
"the",
"call",
"and",
"pass",
"the",
"call",
"up",
"to",
"the",
"next",
"interceptor",
"in",
"the",
"chain",
"."
]
| train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/base/CommandInterceptor.java#L135-L138 |
michael-rapp/AndroidMaterialValidation | library/src/main/java/de/mrapp/android/validation/Validators.java | Validators.iPv6Address | public static Validator<CharSequence> iPv6Address(@NonNull final Context context) {
"""
Creates and returns a validator, which allows to validate texts to ensure, that they
represent valid IPv6 addresses. Empty texts are also accepted.
@param context
The context, which should be used to retrieve the error message, as an instance of
the class {@link Context}. The context may not be null
@return The validator, which has been created, as an instance of the type {@link Validator}
"""
return new IPv6AddressValidator(context, R.string.default_error_message);
} | java | public static Validator<CharSequence> iPv6Address(@NonNull final Context context) {
return new IPv6AddressValidator(context, R.string.default_error_message);
} | [
"public",
"static",
"Validator",
"<",
"CharSequence",
">",
"iPv6Address",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
")",
"{",
"return",
"new",
"IPv6AddressValidator",
"(",
"context",
",",
"R",
".",
"string",
".",
"default_error_message",
")",
";",
"}"
]
| Creates and returns a validator, which allows to validate texts to ensure, that they
represent valid IPv6 addresses. Empty texts are also accepted.
@param context
The context, which should be used to retrieve the error message, as an instance of
the class {@link Context}. The context may not be null
@return The validator, which has been created, as an instance of the type {@link Validator} | [
"Creates",
"and",
"returns",
"a",
"validator",
"which",
"allows",
"to",
"validate",
"texts",
"to",
"ensure",
"that",
"they",
"represent",
"valid",
"IPv6",
"addresses",
".",
"Empty",
"texts",
"are",
"also",
"accepted",
"."
]
| train | https://github.com/michael-rapp/AndroidMaterialValidation/blob/ac8693baeac7abddf2e38a47da4c1849d4661a8b/library/src/main/java/de/mrapp/android/validation/Validators.java#L968-L970 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/DataFrameBuilder.java | DataFrameBuilder.handleDataFrameComplete | private void handleDataFrameComplete(DataFrame dataFrame) {
"""
Publishes a data frame to the DataFrameLog. The outcome of the publish operation, whether success or failure, is
routed to the appropriate callback handlers given in this constructor. This method is called synchronously by the
DataFrameOutputStream, via the LogItem.serialize() method through the append() method, and as such, it is executed
on the same thread that invoked append().
@param dataFrame The data frame to publish.
@throws NullPointerException If the data frame is null.
@throws IllegalArgumentException If the data frame is not sealed.
"""
Exceptions.checkArgument(dataFrame.isSealed(), "dataFrame", "Cannot publish a non-sealed DataFrame.");
// Write DataFrame to DataFrameLog.
CommitArgs commitArgs = new CommitArgs(this.lastSerializedSequenceNumber, this.lastStartedSequenceNumber, dataFrame.getLength());
try {
this.args.beforeCommit.accept(commitArgs);
this.targetLog.append(dataFrame.getData(), this.args.writeTimeout)
.thenAcceptAsync(logAddress -> {
commitArgs.setLogAddress(logAddress);
this.args.commitSuccess.accept(commitArgs);
}, this.args.executor)
.exceptionally(ex -> handleProcessingException(ex, commitArgs));
} catch (Throwable ex) {
handleProcessingException(ex, commitArgs);
// Even though we invoked the dataFrameCommitFailureCallback() - which was for the DurableLog to handle,
// we still need to fail the current call, which most likely leads to failing the LogItem that triggered this.
throw ex;
}
} | java | private void handleDataFrameComplete(DataFrame dataFrame) {
Exceptions.checkArgument(dataFrame.isSealed(), "dataFrame", "Cannot publish a non-sealed DataFrame.");
// Write DataFrame to DataFrameLog.
CommitArgs commitArgs = new CommitArgs(this.lastSerializedSequenceNumber, this.lastStartedSequenceNumber, dataFrame.getLength());
try {
this.args.beforeCommit.accept(commitArgs);
this.targetLog.append(dataFrame.getData(), this.args.writeTimeout)
.thenAcceptAsync(logAddress -> {
commitArgs.setLogAddress(logAddress);
this.args.commitSuccess.accept(commitArgs);
}, this.args.executor)
.exceptionally(ex -> handleProcessingException(ex, commitArgs));
} catch (Throwable ex) {
handleProcessingException(ex, commitArgs);
// Even though we invoked the dataFrameCommitFailureCallback() - which was for the DurableLog to handle,
// we still need to fail the current call, which most likely leads to failing the LogItem that triggered this.
throw ex;
}
} | [
"private",
"void",
"handleDataFrameComplete",
"(",
"DataFrame",
"dataFrame",
")",
"{",
"Exceptions",
".",
"checkArgument",
"(",
"dataFrame",
".",
"isSealed",
"(",
")",
",",
"\"dataFrame\"",
",",
"\"Cannot publish a non-sealed DataFrame.\"",
")",
";",
"// Write DataFrame to DataFrameLog.",
"CommitArgs",
"commitArgs",
"=",
"new",
"CommitArgs",
"(",
"this",
".",
"lastSerializedSequenceNumber",
",",
"this",
".",
"lastStartedSequenceNumber",
",",
"dataFrame",
".",
"getLength",
"(",
")",
")",
";",
"try",
"{",
"this",
".",
"args",
".",
"beforeCommit",
".",
"accept",
"(",
"commitArgs",
")",
";",
"this",
".",
"targetLog",
".",
"append",
"(",
"dataFrame",
".",
"getData",
"(",
")",
",",
"this",
".",
"args",
".",
"writeTimeout",
")",
".",
"thenAcceptAsync",
"(",
"logAddress",
"->",
"{",
"commitArgs",
".",
"setLogAddress",
"(",
"logAddress",
")",
";",
"this",
".",
"args",
".",
"commitSuccess",
".",
"accept",
"(",
"commitArgs",
")",
";",
"}",
",",
"this",
".",
"args",
".",
"executor",
")",
".",
"exceptionally",
"(",
"ex",
"->",
"handleProcessingException",
"(",
"ex",
",",
"commitArgs",
")",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"handleProcessingException",
"(",
"ex",
",",
"commitArgs",
")",
";",
"// Even though we invoked the dataFrameCommitFailureCallback() - which was for the DurableLog to handle,",
"// we still need to fail the current call, which most likely leads to failing the LogItem that triggered this.",
"throw",
"ex",
";",
"}",
"}"
]
| Publishes a data frame to the DataFrameLog. The outcome of the publish operation, whether success or failure, is
routed to the appropriate callback handlers given in this constructor. This method is called synchronously by the
DataFrameOutputStream, via the LogItem.serialize() method through the append() method, and as such, it is executed
on the same thread that invoked append().
@param dataFrame The data frame to publish.
@throws NullPointerException If the data frame is null.
@throws IllegalArgumentException If the data frame is not sealed. | [
"Publishes",
"a",
"data",
"frame",
"to",
"the",
"DataFrameLog",
".",
"The",
"outcome",
"of",
"the",
"publish",
"operation",
"whether",
"success",
"or",
"failure",
"is",
"routed",
"to",
"the",
"appropriate",
"callback",
"handlers",
"given",
"in",
"this",
"constructor",
".",
"This",
"method",
"is",
"called",
"synchronously",
"by",
"the",
"DataFrameOutputStream",
"via",
"the",
"LogItem",
".",
"serialize",
"()",
"method",
"through",
"the",
"append",
"()",
"method",
"and",
"as",
"such",
"it",
"is",
"executed",
"on",
"the",
"same",
"thread",
"that",
"invoked",
"append",
"()",
"."
]
| train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/DataFrameBuilder.java#L178-L199 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java | ParseUtils.requireAttributes | public static String[] requireAttributes(final XMLExtendedStreamReader reader, final String... attributeNames)
throws XMLStreamException {
"""
Require all the named attributes, returning their values in order.
@param reader the reader
@param attributeNames the attribute names
@return the attribute values in order
@throws javax.xml.stream.XMLStreamException if an error occurs
"""
final int length = attributeNames.length;
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
final String name = attributeNames[i];
final String value = reader.getAttributeValue(null, name);
if (value == null) {
throw missingRequired(reader, Collections.singleton(name));
}
result[i] = value;
}
return result;
} | java | public static String[] requireAttributes(final XMLExtendedStreamReader reader, final String... attributeNames)
throws XMLStreamException {
final int length = attributeNames.length;
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
final String name = attributeNames[i];
final String value = reader.getAttributeValue(null, name);
if (value == null) {
throw missingRequired(reader, Collections.singleton(name));
}
result[i] = value;
}
return result;
} | [
"public",
"static",
"String",
"[",
"]",
"requireAttributes",
"(",
"final",
"XMLExtendedStreamReader",
"reader",
",",
"final",
"String",
"...",
"attributeNames",
")",
"throws",
"XMLStreamException",
"{",
"final",
"int",
"length",
"=",
"attributeNames",
".",
"length",
";",
"final",
"String",
"[",
"]",
"result",
"=",
"new",
"String",
"[",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"final",
"String",
"name",
"=",
"attributeNames",
"[",
"i",
"]",
";",
"final",
"String",
"value",
"=",
"reader",
".",
"getAttributeValue",
"(",
"null",
",",
"name",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"missingRequired",
"(",
"reader",
",",
"Collections",
".",
"singleton",
"(",
"name",
")",
")",
";",
"}",
"result",
"[",
"i",
"]",
"=",
"value",
";",
"}",
"return",
"result",
";",
"}"
]
| Require all the named attributes, returning their values in order.
@param reader the reader
@param attributeNames the attribute names
@return the attribute values in order
@throws javax.xml.stream.XMLStreamException if an error occurs | [
"Require",
"all",
"the",
"named",
"attributes",
"returning",
"their",
"values",
"in",
"order",
"."
]
| train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java#L514-L527 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java | ExternalTableDefinition.newBuilder | public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) {
"""
Creates a builder for an ExternalTableDefinition object.
@param sourceUri a fully-qualified URI that points to your data in Google Cloud Storage. The
URI can contain one '*' wildcard character that must come after the bucket's name. Size
limits related to load jobs apply to external data sources.
@param schema the schema for the external data
@param format the source format of the external data
@return a builder for an ExternalTableDefinition object given source URI, schema and format
@see <a href="https://cloud.google.com/bigquery/loading-data-into-bigquery#quota">Quota</a>
@see <a
href="https://cloud.google.com/bigquery/docs/reference/v2/tables#externalDataConfiguration.sourceFormat">
Source Format</a>
"""
return newBuilder(ImmutableList.of(sourceUri), schema, format);
} | java | public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) {
return newBuilder(ImmutableList.of(sourceUri), schema, format);
} | [
"public",
"static",
"Builder",
"newBuilder",
"(",
"String",
"sourceUri",
",",
"Schema",
"schema",
",",
"FormatOptions",
"format",
")",
"{",
"return",
"newBuilder",
"(",
"ImmutableList",
".",
"of",
"(",
"sourceUri",
")",
",",
"schema",
",",
"format",
")",
";",
"}"
]
| Creates a builder for an ExternalTableDefinition object.
@param sourceUri a fully-qualified URI that points to your data in Google Cloud Storage. The
URI can contain one '*' wildcard character that must come after the bucket's name. Size
limits related to load jobs apply to external data sources.
@param schema the schema for the external data
@param format the source format of the external data
@return a builder for an ExternalTableDefinition object given source URI, schema and format
@see <a href="https://cloud.google.com/bigquery/loading-data-into-bigquery#quota">Quota</a>
@see <a
href="https://cloud.google.com/bigquery/docs/reference/v2/tables#externalDataConfiguration.sourceFormat">
Source Format</a> | [
"Creates",
"a",
"builder",
"for",
"an",
"ExternalTableDefinition",
"object",
"."
]
| train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java#L297-L299 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MeasureFormat.java | MeasureFormat.getInstance | public static MeasureFormat getInstance(ULocale locale, FormatWidth formatWidth, NumberFormat format) {
"""
Create a format from the locale, formatWidth, and format.
@param locale the locale.
@param formatWidth hints how long formatted strings should be.
@param format This is defensively copied.
@return The new MeasureFormat object.
"""
PluralRules rules = PluralRules.forLocale(locale);
NumericFormatters formatters = null;
MeasureFormatData data = localeMeasureFormatData.get(locale);
if (data == null) {
data = loadLocaleData(locale);
localeMeasureFormatData.put(locale, data);
}
if (formatWidth == FormatWidth.NUMERIC) {
formatters = localeToNumericDurationFormatters.get(locale);
if (formatters == null) {
formatters = loadNumericFormatters(locale);
localeToNumericDurationFormatters.put(locale, formatters);
}
}
NumberFormat intFormat = NumberFormat.getInstance(locale);
intFormat.setMaximumFractionDigits(0);
intFormat.setMinimumFractionDigits(0);
intFormat.setRoundingMode(BigDecimal.ROUND_DOWN);
return new MeasureFormat(
locale,
data,
formatWidth,
new ImmutableNumberFormat(format),
rules,
formatters,
new ImmutableNumberFormat(NumberFormat.getInstance(locale, formatWidth.getCurrencyStyle())),
new ImmutableNumberFormat(intFormat));
} | java | public static MeasureFormat getInstance(ULocale locale, FormatWidth formatWidth, NumberFormat format) {
PluralRules rules = PluralRules.forLocale(locale);
NumericFormatters formatters = null;
MeasureFormatData data = localeMeasureFormatData.get(locale);
if (data == null) {
data = loadLocaleData(locale);
localeMeasureFormatData.put(locale, data);
}
if (formatWidth == FormatWidth.NUMERIC) {
formatters = localeToNumericDurationFormatters.get(locale);
if (formatters == null) {
formatters = loadNumericFormatters(locale);
localeToNumericDurationFormatters.put(locale, formatters);
}
}
NumberFormat intFormat = NumberFormat.getInstance(locale);
intFormat.setMaximumFractionDigits(0);
intFormat.setMinimumFractionDigits(0);
intFormat.setRoundingMode(BigDecimal.ROUND_DOWN);
return new MeasureFormat(
locale,
data,
formatWidth,
new ImmutableNumberFormat(format),
rules,
formatters,
new ImmutableNumberFormat(NumberFormat.getInstance(locale, formatWidth.getCurrencyStyle())),
new ImmutableNumberFormat(intFormat));
} | [
"public",
"static",
"MeasureFormat",
"getInstance",
"(",
"ULocale",
"locale",
",",
"FormatWidth",
"formatWidth",
",",
"NumberFormat",
"format",
")",
"{",
"PluralRules",
"rules",
"=",
"PluralRules",
".",
"forLocale",
"(",
"locale",
")",
";",
"NumericFormatters",
"formatters",
"=",
"null",
";",
"MeasureFormatData",
"data",
"=",
"localeMeasureFormatData",
".",
"get",
"(",
"locale",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"{",
"data",
"=",
"loadLocaleData",
"(",
"locale",
")",
";",
"localeMeasureFormatData",
".",
"put",
"(",
"locale",
",",
"data",
")",
";",
"}",
"if",
"(",
"formatWidth",
"==",
"FormatWidth",
".",
"NUMERIC",
")",
"{",
"formatters",
"=",
"localeToNumericDurationFormatters",
".",
"get",
"(",
"locale",
")",
";",
"if",
"(",
"formatters",
"==",
"null",
")",
"{",
"formatters",
"=",
"loadNumericFormatters",
"(",
"locale",
")",
";",
"localeToNumericDurationFormatters",
".",
"put",
"(",
"locale",
",",
"formatters",
")",
";",
"}",
"}",
"NumberFormat",
"intFormat",
"=",
"NumberFormat",
".",
"getInstance",
"(",
"locale",
")",
";",
"intFormat",
".",
"setMaximumFractionDigits",
"(",
"0",
")",
";",
"intFormat",
".",
"setMinimumFractionDigits",
"(",
"0",
")",
";",
"intFormat",
".",
"setRoundingMode",
"(",
"BigDecimal",
".",
"ROUND_DOWN",
")",
";",
"return",
"new",
"MeasureFormat",
"(",
"locale",
",",
"data",
",",
"formatWidth",
",",
"new",
"ImmutableNumberFormat",
"(",
"format",
")",
",",
"rules",
",",
"formatters",
",",
"new",
"ImmutableNumberFormat",
"(",
"NumberFormat",
".",
"getInstance",
"(",
"locale",
",",
"formatWidth",
".",
"getCurrencyStyle",
"(",
")",
")",
")",
",",
"new",
"ImmutableNumberFormat",
"(",
"intFormat",
")",
")",
";",
"}"
]
| Create a format from the locale, formatWidth, and format.
@param locale the locale.
@param formatWidth hints how long formatted strings should be.
@param format This is defensively copied.
@return The new MeasureFormat object. | [
"Create",
"a",
"format",
"from",
"the",
"locale",
"formatWidth",
"and",
"format",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MeasureFormat.java#L235-L263 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBUtils.java | EJBUtils.methodsMatch | static boolean methodsMatch(Method m1, Method m2) {
"""
Returns true for two methods that have the same name and parameters. <p>
Similar to Method.equals(), except declaring class and return type are
NOT considered. <p>
Useful for determining when multiple component or business interfaces
implement the same method... as they will both be mapped to the same
methodId. <p>
@param m1 first of two methods to compare
@param m2 second of two methods to compare
@return true if both methods have the same name and parameters;
otherwise false.
"""
if (m1 == m2)
{
return true;
}
else if (m1.getName().equals(m2.getName()))
{
Class<?>[] parms1 = m1.getParameterTypes();
Class<?>[] parms2 = m2.getParameterTypes();
if (parms1.length == parms2.length)
{
int length = parms1.length;
for (int i = 0; i < length; i++)
{
if (parms1[i] != parms2[i])
return false;
}
return true;
}
}
return false;
} | java | static boolean methodsMatch(Method m1, Method m2)
{
if (m1 == m2)
{
return true;
}
else if (m1.getName().equals(m2.getName()))
{
Class<?>[] parms1 = m1.getParameterTypes();
Class<?>[] parms2 = m2.getParameterTypes();
if (parms1.length == parms2.length)
{
int length = parms1.length;
for (int i = 0; i < length; i++)
{
if (parms1[i] != parms2[i])
return false;
}
return true;
}
}
return false;
} | [
"static",
"boolean",
"methodsMatch",
"(",
"Method",
"m1",
",",
"Method",
"m2",
")",
"{",
"if",
"(",
"m1",
"==",
"m2",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"m1",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"m2",
".",
"getName",
"(",
")",
")",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"parms1",
"=",
"m1",
".",
"getParameterTypes",
"(",
")",
";",
"Class",
"<",
"?",
">",
"[",
"]",
"parms2",
"=",
"m2",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"parms1",
".",
"length",
"==",
"parms2",
".",
"length",
")",
"{",
"int",
"length",
"=",
"parms1",
".",
"length",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"parms1",
"[",
"i",
"]",
"!=",
"parms2",
"[",
"i",
"]",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Returns true for two methods that have the same name and parameters. <p>
Similar to Method.equals(), except declaring class and return type are
NOT considered. <p>
Useful for determining when multiple component or business interfaces
implement the same method... as they will both be mapped to the same
methodId. <p>
@param m1 first of two methods to compare
@param m2 second of two methods to compare
@return true if both methods have the same name and parameters;
otherwise false. | [
"Returns",
"true",
"for",
"two",
"methods",
"that",
"have",
"the",
"same",
"name",
"and",
"parameters",
".",
"<p",
">"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBUtils.java#L118-L140 |
marklogic/java-client-api | marklogic-client-api/src/main/java/com/marklogic/client/example/cookbook/datamovement/BulkLoadFromJdbcRaw.java | BulkLoadFromJdbcRaw.populateSalary | public void populateSalary(ResultSet row, ObjectNode s) throws SQLException {
"""
take data from a JDBC ResultSet (row) and populate an ObjectNode (JSON) object
"""
s.put("employeeId", row.getInt("emp_no"));
s.put("salary", row.getInt("salary"));
Calendar fromDate = Calendar.getInstance();
fromDate.setTime(row.getDate("from_date"));
s.put("fromDate", dateFormat.format(fromDate.getTime()));
Calendar toDate = Calendar.getInstance();
toDate.setTime(row.getDate("to_date"));
s.put("toDate", dateFormat.format(toDate.getTime()));
} | java | public void populateSalary(ResultSet row, ObjectNode s) throws SQLException {
s.put("employeeId", row.getInt("emp_no"));
s.put("salary", row.getInt("salary"));
Calendar fromDate = Calendar.getInstance();
fromDate.setTime(row.getDate("from_date"));
s.put("fromDate", dateFormat.format(fromDate.getTime()));
Calendar toDate = Calendar.getInstance();
toDate.setTime(row.getDate("to_date"));
s.put("toDate", dateFormat.format(toDate.getTime()));
} | [
"public",
"void",
"populateSalary",
"(",
"ResultSet",
"row",
",",
"ObjectNode",
"s",
")",
"throws",
"SQLException",
"{",
"s",
".",
"put",
"(",
"\"employeeId\"",
",",
"row",
".",
"getInt",
"(",
"\"emp_no\"",
")",
")",
";",
"s",
".",
"put",
"(",
"\"salary\"",
",",
"row",
".",
"getInt",
"(",
"\"salary\"",
")",
")",
";",
"Calendar",
"fromDate",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"fromDate",
".",
"setTime",
"(",
"row",
".",
"getDate",
"(",
"\"from_date\"",
")",
")",
";",
"s",
".",
"put",
"(",
"\"fromDate\"",
",",
"dateFormat",
".",
"format",
"(",
"fromDate",
".",
"getTime",
"(",
")",
")",
")",
";",
"Calendar",
"toDate",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"toDate",
".",
"setTime",
"(",
"row",
".",
"getDate",
"(",
"\"to_date\"",
")",
")",
";",
"s",
".",
"put",
"(",
"\"toDate\"",
",",
"dateFormat",
".",
"format",
"(",
"toDate",
".",
"getTime",
"(",
")",
")",
")",
";",
"}"
]
| take data from a JDBC ResultSet (row) and populate an ObjectNode (JSON) object | [
"take",
"data",
"from",
"a",
"JDBC",
"ResultSet",
"(",
"row",
")",
"and",
"populate",
"an",
"ObjectNode",
"(",
"JSON",
")",
"object"
]
| train | https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/example/cookbook/datamovement/BulkLoadFromJdbcRaw.java#L113-L122 |
knowm/Sundial | src/main/java/org/quartz/core/RAMJobStore.java | RAMJobStore.storeJobAndTrigger | @Override
public void storeJobAndTrigger(JobDetail newJob, OperableTrigger newTrigger)
throws JobPersistenceException {
"""
Store the given <code>{@link org.quartz.jobs.JobDetail}</code> and <code>
{@link org.quartz.triggers.Trigger}</code>.
@param newJob The <code>JobDetail</code> to be stored.
@param newTrigger The <code>Trigger</code> to be stored.
@throws ObjectAlreadyExistsException if a <code>Job</code> with the same name/group already
exists.
"""
storeJob(newJob, false);
storeTrigger(newTrigger, false);
} | java | @Override
public void storeJobAndTrigger(JobDetail newJob, OperableTrigger newTrigger)
throws JobPersistenceException {
storeJob(newJob, false);
storeTrigger(newTrigger, false);
} | [
"@",
"Override",
"public",
"void",
"storeJobAndTrigger",
"(",
"JobDetail",
"newJob",
",",
"OperableTrigger",
"newTrigger",
")",
"throws",
"JobPersistenceException",
"{",
"storeJob",
"(",
"newJob",
",",
"false",
")",
";",
"storeTrigger",
"(",
"newTrigger",
",",
"false",
")",
";",
"}"
]
| Store the given <code>{@link org.quartz.jobs.JobDetail}</code> and <code>
{@link org.quartz.triggers.Trigger}</code>.
@param newJob The <code>JobDetail</code> to be stored.
@param newTrigger The <code>Trigger</code> to be stored.
@throws ObjectAlreadyExistsException if a <code>Job</code> with the same name/group already
exists. | [
"Store",
"the",
"given",
"<code",
">",
"{",
"@link",
"org",
".",
"quartz",
".",
"jobs",
".",
"JobDetail",
"}",
"<",
"/",
"code",
">",
"and",
"<code",
">",
"{",
"@link",
"org",
".",
"quartz",
".",
"triggers",
".",
"Trigger",
"}",
"<",
"/",
"code",
">",
"."
]
| train | https://github.com/knowm/Sundial/blob/0d61549fdfb8d6f884a1f2eed7e32ad39e2f4c62/src/main/java/org/quartz/core/RAMJobStore.java#L124-L130 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/model/workflow/Process.java | Process.setAttribute | public void setAttribute(String attrname, String value) {
"""
Set the value of a process attribute.
If the value is null, the attribute is removed.
If the attribute does not exist and the value is not null, the attribute
is created.
@param attrname
@param value
"""
if (attributes == null)
attributes = new ArrayList<Attribute>();
Attribute.setAttribute(attributes, attrname, value);
} | java | public void setAttribute(String attrname, String value) {
if (attributes == null)
attributes = new ArrayList<Attribute>();
Attribute.setAttribute(attributes, attrname, value);
} | [
"public",
"void",
"setAttribute",
"(",
"String",
"attrname",
",",
"String",
"value",
")",
"{",
"if",
"(",
"attributes",
"==",
"null",
")",
"attributes",
"=",
"new",
"ArrayList",
"<",
"Attribute",
">",
"(",
")",
";",
"Attribute",
".",
"setAttribute",
"(",
"attributes",
",",
"attrname",
",",
"value",
")",
";",
"}"
]
| Set the value of a process attribute.
If the value is null, the attribute is removed.
If the attribute does not exist and the value is not null, the attribute
is created.
@param attrname
@param value | [
"Set",
"the",
"value",
"of",
"a",
"process",
"attribute",
".",
"If",
"the",
"value",
"is",
"null",
"the",
"attribute",
"is",
"removed",
".",
"If",
"the",
"attribute",
"does",
"not",
"exist",
"and",
"the",
"value",
"is",
"not",
"null",
"the",
"attribute",
"is",
"created",
"."
]
| train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/workflow/Process.java#L450-L454 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java | RegistriesInner.createAsync | public Observable<RegistryInner> createAsync(String resourceGroupName, String registryName, RegistryCreateParameters registryCreateParameters) {
"""
Creates a container registry with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param registryCreateParameters The parameters for creating a container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createWithServiceResponseAsync(resourceGroupName, registryName, registryCreateParameters).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | java | public Observable<RegistryInner> createAsync(String resourceGroupName, String registryName, RegistryCreateParameters registryCreateParameters) {
return createWithServiceResponseAsync(resourceGroupName, registryName, registryCreateParameters).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RegistryInner",
">",
"createAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"RegistryCreateParameters",
"registryCreateParameters",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
"registryCreateParameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RegistryInner",
">",
",",
"RegistryInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RegistryInner",
"call",
"(",
"ServiceResponse",
"<",
"RegistryInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Creates a container registry with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param registryCreateParameters The parameters for creating a container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"a",
"container",
"registry",
"with",
"the",
"specified",
"parameters",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java#L329-L336 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/GeneratorRegistry.java | GeneratorRegistry.updateRegistries | private void updateRegistries(ResourceGenerator generator) {
"""
Update the registries with the generator given in parameter
@param generator
the generator
"""
resolverRegistry.add(new ResourceGeneratorResolverWrapper(generator, generator.getResolver()));
GeneratorComparator genComparator = new GeneratorComparator();
Collections.sort(resolverRegistry);
if (generator instanceof StreamResourceGenerator) {
binaryResourceGeneratorRegistry.add(generator);
Collections.sort(binaryResourceGeneratorRegistry, genComparator);
}
if (generator instanceof CssResourceGenerator) {
if (((CssResourceGenerator) generator).isHandlingCssImage()) {
cssImageResourceGeneratorRegistry.add(generator);
Collections.sort(cssImageResourceGeneratorRegistry, genComparator);
}
}
if (generator instanceof BundlingProcessLifeCycleListener) {
bundlingProcesslifeCycleListeners.add((BundlingProcessLifeCycleListener) generator);
}
} | java | private void updateRegistries(ResourceGenerator generator) {
resolverRegistry.add(new ResourceGeneratorResolverWrapper(generator, generator.getResolver()));
GeneratorComparator genComparator = new GeneratorComparator();
Collections.sort(resolverRegistry);
if (generator instanceof StreamResourceGenerator) {
binaryResourceGeneratorRegistry.add(generator);
Collections.sort(binaryResourceGeneratorRegistry, genComparator);
}
if (generator instanceof CssResourceGenerator) {
if (((CssResourceGenerator) generator).isHandlingCssImage()) {
cssImageResourceGeneratorRegistry.add(generator);
Collections.sort(cssImageResourceGeneratorRegistry, genComparator);
}
}
if (generator instanceof BundlingProcessLifeCycleListener) {
bundlingProcesslifeCycleListeners.add((BundlingProcessLifeCycleListener) generator);
}
} | [
"private",
"void",
"updateRegistries",
"(",
"ResourceGenerator",
"generator",
")",
"{",
"resolverRegistry",
".",
"add",
"(",
"new",
"ResourceGeneratorResolverWrapper",
"(",
"generator",
",",
"generator",
".",
"getResolver",
"(",
")",
")",
")",
";",
"GeneratorComparator",
"genComparator",
"=",
"new",
"GeneratorComparator",
"(",
")",
";",
"Collections",
".",
"sort",
"(",
"resolverRegistry",
")",
";",
"if",
"(",
"generator",
"instanceof",
"StreamResourceGenerator",
")",
"{",
"binaryResourceGeneratorRegistry",
".",
"add",
"(",
"generator",
")",
";",
"Collections",
".",
"sort",
"(",
"binaryResourceGeneratorRegistry",
",",
"genComparator",
")",
";",
"}",
"if",
"(",
"generator",
"instanceof",
"CssResourceGenerator",
")",
"{",
"if",
"(",
"(",
"(",
"CssResourceGenerator",
")",
"generator",
")",
".",
"isHandlingCssImage",
"(",
")",
")",
"{",
"cssImageResourceGeneratorRegistry",
".",
"add",
"(",
"generator",
")",
";",
"Collections",
".",
"sort",
"(",
"cssImageResourceGeneratorRegistry",
",",
"genComparator",
")",
";",
"}",
"}",
"if",
"(",
"generator",
"instanceof",
"BundlingProcessLifeCycleListener",
")",
"{",
"bundlingProcesslifeCycleListeners",
".",
"add",
"(",
"(",
"BundlingProcessLifeCycleListener",
")",
"generator",
")",
";",
"}",
"}"
]
| Update the registries with the generator given in parameter
@param generator
the generator | [
"Update",
"the",
"registries",
"with",
"the",
"generator",
"given",
"in",
"parameter"
]
| train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/GeneratorRegistry.java#L332-L350 |
astrapi69/mystic-crypt | crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/PrivateKeyReader.java | PrivateKeyReader.readPrivateKey | public static PrivateKey readPrivateKey(final byte[] privateKeyBytes)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
"""
Reads the given byte array with the default RSA algorithm and returns the {@link PrivateKey}
object.
@param privateKeyBytes
the byte array that contains the private key bytes
@return the {@link PrivateKey} object
@throws NoSuchAlgorithmException
is thrown if instantiation of the cypher object fails.
@throws InvalidKeySpecException
is thrown if generation of the SecretKey object fails.
@throws NoSuchProviderException
is thrown if the specified provider is not registered in the security provider
list.
"""
return readPrivateKey(privateKeyBytes, KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
} | java | public static PrivateKey readPrivateKey(final byte[] privateKeyBytes)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException
{
return readPrivateKey(privateKeyBytes, KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
} | [
"public",
"static",
"PrivateKey",
"readPrivateKey",
"(",
"final",
"byte",
"[",
"]",
"privateKeyBytes",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeySpecException",
",",
"NoSuchProviderException",
"{",
"return",
"readPrivateKey",
"(",
"privateKeyBytes",
",",
"KeyPairGeneratorAlgorithm",
".",
"RSA",
".",
"getAlgorithm",
"(",
")",
")",
";",
"}"
]
| Reads the given byte array with the default RSA algorithm and returns the {@link PrivateKey}
object.
@param privateKeyBytes
the byte array that contains the private key bytes
@return the {@link PrivateKey} object
@throws NoSuchAlgorithmException
is thrown if instantiation of the cypher object fails.
@throws InvalidKeySpecException
is thrown if generation of the SecretKey object fails.
@throws NoSuchProviderException
is thrown if the specified provider is not registered in the security provider
list. | [
"Reads",
"the",
"given",
"byte",
"array",
"with",
"the",
"default",
"RSA",
"algorithm",
"and",
"returns",
"the",
"{",
"@link",
"PrivateKey",
"}",
"object",
"."
]
| train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/PrivateKeyReader.java#L203-L207 |
dbracewell/hermes | hermes-wordnet/src/main/java/com/davidbracewell/hermes/wordnet/WordNet.java | WordNet.getHyponyms | public Set<Synset> getHyponyms(@NonNull Synset node) {
"""
Gets the hyponyms of the given synset.
@param node The synset whose hyponyms we want
@return The hyponyms
"""
return getRelatedSynsets(node, WordNetRelation.HYPONYM);
} | java | public Set<Synset> getHyponyms(@NonNull Synset node) {
return getRelatedSynsets(node, WordNetRelation.HYPONYM);
} | [
"public",
"Set",
"<",
"Synset",
">",
"getHyponyms",
"(",
"@",
"NonNull",
"Synset",
"node",
")",
"{",
"return",
"getRelatedSynsets",
"(",
"node",
",",
"WordNetRelation",
".",
"HYPONYM",
")",
";",
"}"
]
| Gets the hyponyms of the given synset.
@param node The synset whose hyponyms we want
@return The hyponyms | [
"Gets",
"the",
"hyponyms",
"of",
"the",
"given",
"synset",
"."
]
| train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-wordnet/src/main/java/com/davidbracewell/hermes/wordnet/WordNet.java#L249-L251 |
WileyLabs/teasy | src/main/java/com/wiley/elements/conditions/TeasyExpectedConditions.java | TeasyExpectedConditions.visibilityOfFirstElements | public static ExpectedCondition<List<WebElement>> visibilityOfFirstElements(final By locator) {
"""
Expected condition to look for elements in frames that will return as soon as elements are found in any frame
@param locator
@return
"""
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(final WebDriver driver) {
return getFirstVisibleWebElements(driver, null, locator);
}
@Override
public String toString() {
return String.format("visibility of element located by %s", locator);
}
};
} | java | public static ExpectedCondition<List<WebElement>> visibilityOfFirstElements(final By locator) {
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(final WebDriver driver) {
return getFirstVisibleWebElements(driver, null, locator);
}
@Override
public String toString() {
return String.format("visibility of element located by %s", locator);
}
};
} | [
"public",
"static",
"ExpectedCondition",
"<",
"List",
"<",
"WebElement",
">",
">",
"visibilityOfFirstElements",
"(",
"final",
"By",
"locator",
")",
"{",
"return",
"new",
"ExpectedCondition",
"<",
"List",
"<",
"WebElement",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"WebElement",
">",
"apply",
"(",
"final",
"WebDriver",
"driver",
")",
"{",
"return",
"getFirstVisibleWebElements",
"(",
"driver",
",",
"null",
",",
"locator",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"visibility of element located by %s\"",
",",
"locator",
")",
";",
"}",
"}",
";",
"}"
]
| Expected condition to look for elements in frames that will return as soon as elements are found in any frame
@param locator
@return | [
"Expected",
"condition",
"to",
"look",
"for",
"elements",
"in",
"frames",
"that",
"will",
"return",
"as",
"soon",
"as",
"elements",
"are",
"found",
"in",
"any",
"frame"
]
| train | https://github.com/WileyLabs/teasy/blob/94489ac8e6a6680b52dfa6cdbc9d8535333bef42/src/main/java/com/wiley/elements/conditions/TeasyExpectedConditions.java#L145-L157 |
rvs-fluid-it/mvn-fluid-cd | mvn-ext-freeze/src/main/java/be/fluid_it/mvn/cd/x/freeze/replace/FreezeHandler.java | FreezeHandler.printSaxException | void printSaxException(String message, SAXException e) {
"""
Utility method to print information about a SAXException.
@param message A message to be included in the error output.
@param e The exception to be printed.
"""
System.err.println();
System.err.println("*** SAX Exception -- " + message);
System.err.println(" SystemId = \"" +
documentLocator.getSystemId() + "\"");
e.printStackTrace(System.err);
} | java | void printSaxException(String message, SAXException e) {
System.err.println();
System.err.println("*** SAX Exception -- " + message);
System.err.println(" SystemId = \"" +
documentLocator.getSystemId() + "\"");
e.printStackTrace(System.err);
} | [
"void",
"printSaxException",
"(",
"String",
"message",
",",
"SAXException",
"e",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"*** SAX Exception -- \"",
"+",
"message",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\" SystemId = \\\"\"",
"+",
"documentLocator",
".",
"getSystemId",
"(",
")",
"+",
"\"\\\"\"",
")",
";",
"e",
".",
"printStackTrace",
"(",
"System",
".",
"err",
")",
";",
"}"
]
| Utility method to print information about a SAXException.
@param message A message to be included in the error output.
@param e The exception to be printed. | [
"Utility",
"method",
"to",
"print",
"information",
"about",
"a",
"SAXException",
"."
]
| train | https://github.com/rvs-fluid-it/mvn-fluid-cd/blob/2aad8ed1cb40f94bd24bad7e6a127956cc277077/mvn-ext-freeze/src/main/java/be/fluid_it/mvn/cd/x/freeze/replace/FreezeHandler.java#L326-L332 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getCertificateIssuerAsync | public Observable<IssuerBundle> getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) {
"""
Lists the specified certificate issuer.
The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. This operation requires the certificates/manageissuers/getissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IssuerBundle object
"""
return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() {
@Override
public IssuerBundle call(ServiceResponse<IssuerBundle> response) {
return response.body();
}
});
} | java | public Observable<IssuerBundle> getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) {
return getCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() {
@Override
public IssuerBundle call(ServiceResponse<IssuerBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IssuerBundle",
">",
"getCertificateIssuerAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"issuerName",
")",
"{",
"return",
"getCertificateIssuerWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"issuerName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"IssuerBundle",
">",
",",
"IssuerBundle",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"IssuerBundle",
"call",
"(",
"ServiceResponse",
"<",
"IssuerBundle",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Lists the specified certificate issuer.
The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. This operation requires the certificates/manageissuers/getissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IssuerBundle object | [
"Lists",
"the",
"specified",
"certificate",
"issuer",
".",
"The",
"GetCertificateIssuer",
"operation",
"returns",
"the",
"specified",
"certificate",
"issuer",
"resources",
"in",
"the",
"specified",
"key",
"vault",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"manageissuers",
"/",
"getissuers",
"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#L6339-L6346 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java | CPSpecificationOptionPersistenceImpl.fetchByUUID_G | @Override
public CPSpecificationOption fetchByUUID_G(String uuid, long groupId) {
"""
Returns the cp specification option where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp specification option, or <code>null</code> if a matching cp specification option could not be found
"""
return fetchByUUID_G(uuid, groupId, true);
} | java | @Override
public CPSpecificationOption fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | [
"@",
"Override",
"public",
"CPSpecificationOption",
"fetchByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"{",
"return",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
",",
"true",
")",
";",
"}"
]
| Returns the cp specification option where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp specification option, or <code>null</code> if a matching cp specification option could not be found | [
"Returns",
"the",
"cp",
"specification",
"option",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
"finder",
"cache",
"."
]
| train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java#L706-L709 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java | Parameters.getNonNegativeDoubleList | public List<Double> getNonNegativeDoubleList(final String param) {
"""
Gets a parameter whose value is a (possibly empty) list of non-negative doubles.
"""
return getList(param, new StringToDouble(),
new IsNonNegative<Double>(), "non-negative double");
} | java | public List<Double> getNonNegativeDoubleList(final String param) {
return getList(param, new StringToDouble(),
new IsNonNegative<Double>(), "non-negative double");
} | [
"public",
"List",
"<",
"Double",
">",
"getNonNegativeDoubleList",
"(",
"final",
"String",
"param",
")",
"{",
"return",
"getList",
"(",
"param",
",",
"new",
"StringToDouble",
"(",
")",
",",
"new",
"IsNonNegative",
"<",
"Double",
">",
"(",
")",
",",
"\"non-negative double\"",
")",
";",
"}"
]
| Gets a parameter whose value is a (possibly empty) list of non-negative doubles. | [
"Gets",
"a",
"parameter",
"whose",
"value",
"is",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"non",
"-",
"negative",
"doubles",
"."
]
| train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L717-L720 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java | EventsListener.hasHandlers | public boolean hasHandlers(int eventBits, String eventName, Function handler) {
"""
Return true if the element is listening for the
given eventBit or eventName and the handler matches.
"""
for (int i = 0, j = elementEvents.length(); i < j; i++) {
BindFunction function = elementEvents.get(i);
if ((function.hasEventType(eventBits) || function.isTypeOf(eventName))
&& (handler == null || function.isEquals(handler))) {
return true;
}
}
return false;
} | java | public boolean hasHandlers(int eventBits, String eventName, Function handler) {
for (int i = 0, j = elementEvents.length(); i < j; i++) {
BindFunction function = elementEvents.get(i);
if ((function.hasEventType(eventBits) || function.isTypeOf(eventName))
&& (handler == null || function.isEquals(handler))) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"hasHandlers",
"(",
"int",
"eventBits",
",",
"String",
"eventName",
",",
"Function",
"handler",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"j",
"=",
"elementEvents",
".",
"length",
"(",
")",
";",
"i",
"<",
"j",
";",
"i",
"++",
")",
"{",
"BindFunction",
"function",
"=",
"elementEvents",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"(",
"function",
".",
"hasEventType",
"(",
"eventBits",
")",
"||",
"function",
".",
"isTypeOf",
"(",
"eventName",
")",
")",
"&&",
"(",
"handler",
"==",
"null",
"||",
"function",
".",
"isEquals",
"(",
"handler",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Return true if the element is listening for the
given eventBit or eventName and the handler matches. | [
"Return",
"true",
"if",
"the",
"element",
"is",
"listening",
"for",
"the",
"given",
"eventBit",
"or",
"eventName",
"and",
"the",
"handler",
"matches",
"."
]
| train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java#L705-L714 |
SourcePond/fileobserver | fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java | DirectoryFactory.newResource | Resource newResource(final Algorithm pAlgorithm, final Path pFile) {
"""
<p><em>INTERNAL API, only ot be used in class hierarchy</em></p>
<p>
Creates a new checksum {@link Resource} with the algorithm and file specified.
@param pAlgorithm Algorithm, must not be {@code null}
@param pFile File on which checksums shall be tracked, must not be {@code null}
@return New resource instance, never {@code null}
"""
return resourcesFactory.create(pAlgorithm, pFile);
} | java | Resource newResource(final Algorithm pAlgorithm, final Path pFile) {
return resourcesFactory.create(pAlgorithm, pFile);
} | [
"Resource",
"newResource",
"(",
"final",
"Algorithm",
"pAlgorithm",
",",
"final",
"Path",
"pFile",
")",
"{",
"return",
"resourcesFactory",
".",
"create",
"(",
"pAlgorithm",
",",
"pFile",
")",
";",
"}"
]
| <p><em>INTERNAL API, only ot be used in class hierarchy</em></p>
<p>
Creates a new checksum {@link Resource} with the algorithm and file specified.
@param pAlgorithm Algorithm, must not be {@code null}
@param pFile File on which checksums shall be tracked, must not be {@code null}
@return New resource instance, never {@code null} | [
"<p",
">",
"<em",
">",
"INTERNAL",
"API",
"only",
"ot",
"be",
"used",
"in",
"class",
"hierarchy<",
"/",
"em",
">",
"<",
"/",
"p",
">",
"<p",
">",
"Creates",
"a",
"new",
"checksum",
"{",
"@link",
"Resource",
"}",
"with",
"the",
"algorithm",
"and",
"file",
"specified",
"."
]
| train | https://github.com/SourcePond/fileobserver/blob/dfb3055ed35759a47f52f6cfdea49879c415fd6b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java#L75-L77 |
vRallev/ECC-25519 | ECC-25519-Java/src/main/java/djb/Curve25519.java | Curve25519.mul_small | private static final long10 mul_small(long10 xy, long10 x, long y) {
"""
/* Multiply a number by a small integer in range -185861411 .. 185861411.
The output is in reduced form, the input x need not be. x and xy may point
to the same buffer.
"""
long t;
t = (x._8*y);
xy._8 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._9*y);
xy._9 = (t & ((1 << 25) - 1));
t = 19 * (t >> 25) + (x._0*y);
xy._0 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._1*y);
xy._1 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._2*y);
xy._2 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._3*y);
xy._3 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._4*y);
xy._4 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._5*y);
xy._5 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._6*y);
xy._6 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._7*y);
xy._7 = (t & ((1 << 25) - 1));
t = (t >> 25) + xy._8;
xy._8 = (t & ((1 << 26) - 1));
xy._9 += (t >> 26);
return xy;
} | java | private static final long10 mul_small(long10 xy, long10 x, long y) {
long t;
t = (x._8*y);
xy._8 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._9*y);
xy._9 = (t & ((1 << 25) - 1));
t = 19 * (t >> 25) + (x._0*y);
xy._0 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._1*y);
xy._1 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._2*y);
xy._2 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._3*y);
xy._3 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._4*y);
xy._4 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._5*y);
xy._5 = (t & ((1 << 25) - 1));
t = (t >> 25) + (x._6*y);
xy._6 = (t & ((1 << 26) - 1));
t = (t >> 26) + (x._7*y);
xy._7 = (t & ((1 << 25) - 1));
t = (t >> 25) + xy._8;
xy._8 = (t & ((1 << 26) - 1));
xy._9 += (t >> 26);
return xy;
} | [
"private",
"static",
"final",
"long10",
"mul_small",
"(",
"long10",
"xy",
",",
"long10",
"x",
",",
"long",
"y",
")",
"{",
"long",
"t",
";",
"t",
"=",
"(",
"x",
".",
"_8",
"*",
"y",
")",
";",
"xy",
".",
"_8",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"26",
")",
"+",
"(",
"x",
".",
"_9",
"*",
"y",
")",
";",
"xy",
".",
"_9",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"25",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"19",
"*",
"(",
"t",
">>",
"25",
")",
"+",
"(",
"x",
".",
"_0",
"*",
"y",
")",
";",
"xy",
".",
"_0",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"26",
")",
"+",
"(",
"x",
".",
"_1",
"*",
"y",
")",
";",
"xy",
".",
"_1",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"25",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"25",
")",
"+",
"(",
"x",
".",
"_2",
"*",
"y",
")",
";",
"xy",
".",
"_2",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"26",
")",
"+",
"(",
"x",
".",
"_3",
"*",
"y",
")",
";",
"xy",
".",
"_3",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"25",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"25",
")",
"+",
"(",
"x",
".",
"_4",
"*",
"y",
")",
";",
"xy",
".",
"_4",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"26",
")",
"+",
"(",
"x",
".",
"_5",
"*",
"y",
")",
";",
"xy",
".",
"_5",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"25",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"25",
")",
"+",
"(",
"x",
".",
"_6",
"*",
"y",
")",
";",
"xy",
".",
"_6",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"26",
")",
"+",
"(",
"x",
".",
"_7",
"*",
"y",
")",
";",
"xy",
".",
"_7",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"25",
")",
"-",
"1",
")",
")",
";",
"t",
"=",
"(",
"t",
">>",
"25",
")",
"+",
"xy",
".",
"_8",
";",
"xy",
".",
"_8",
"=",
"(",
"t",
"&",
"(",
"(",
"1",
"<<",
"26",
")",
"-",
"1",
")",
")",
";",
"xy",
".",
"_9",
"+=",
"(",
"t",
">>",
"26",
")",
";",
"return",
"xy",
";",
"}"
]
| /* Multiply a number by a small integer in range -185861411 .. 185861411.
The output is in reduced form, the input x need not be. x and xy may point
to the same buffer. | [
"/",
"*",
"Multiply",
"a",
"number",
"by",
"a",
"small",
"integer",
"in",
"range",
"-",
"185861411",
"..",
"185861411",
".",
"The",
"output",
"is",
"in",
"reduced",
"form",
"the",
"input",
"x",
"need",
"not",
"be",
".",
"x",
"and",
"xy",
"may",
"point",
"to",
"the",
"same",
"buffer",
"."
]
| train | https://github.com/vRallev/ECC-25519/blob/5c4297933aabfa4fbe7675e36d6d923ffd22e2cb/ECC-25519-Java/src/main/java/djb/Curve25519.java#L523-L549 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java | TransformerHandlerImpl.resolveEntity | public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
"""
Filter an external entity resolution.
@param publicId The entity's public identifier, or null.
@param systemId The entity's system identifier.
@return A new InputSource or null for the default.
@throws IOException
@throws SAXException The client may throw
an exception during processing.
@throws java.io.IOException The client may throw an
I/O-related exception while obtaining the
new InputSource.
@see org.xml.sax.EntityResolver#resolveEntity
"""
if (m_entityResolver != null)
{
return m_entityResolver.resolveEntity(publicId, systemId);
}
else
{
return null;
}
} | java | public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException
{
if (m_entityResolver != null)
{
return m_entityResolver.resolveEntity(publicId, systemId);
}
else
{
return null;
}
} | [
"public",
"InputSource",
"resolveEntity",
"(",
"String",
"publicId",
",",
"String",
"systemId",
")",
"throws",
"SAXException",
",",
"IOException",
"{",
"if",
"(",
"m_entityResolver",
"!=",
"null",
")",
"{",
"return",
"m_entityResolver",
".",
"resolveEntity",
"(",
"publicId",
",",
"systemId",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| Filter an external entity resolution.
@param publicId The entity's public identifier, or null.
@param systemId The entity's system identifier.
@return A new InputSource or null for the default.
@throws IOException
@throws SAXException The client may throw
an exception during processing.
@throws java.io.IOException The client may throw an
I/O-related exception while obtaining the
new InputSource.
@see org.xml.sax.EntityResolver#resolveEntity | [
"Filter",
"an",
"external",
"entity",
"resolution",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java#L248-L260 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/ZonedDateTime.java | ZonedDateTime.create | private static ZonedDateTime create(long epochSecond, int nanoOfSecond, ZoneId zone) {
"""
Obtains an instance of {@code ZonedDateTime} using seconds from the
epoch of 1970-01-01T00:00:00Z.
@param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z
@param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999
@param zone the time-zone, not null
@return the zoned date-time, not null
@throws DateTimeException if the result exceeds the supported range
"""
ZoneRules rules = zone.getRules();
Instant instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond); // TODO: rules should be queryable by epochSeconds
ZoneOffset offset = rules.getOffset(instant);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
return new ZonedDateTime(ldt, offset, zone);
} | java | private static ZonedDateTime create(long epochSecond, int nanoOfSecond, ZoneId zone) {
ZoneRules rules = zone.getRules();
Instant instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond); // TODO: rules should be queryable by epochSeconds
ZoneOffset offset = rules.getOffset(instant);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
return new ZonedDateTime(ldt, offset, zone);
} | [
"private",
"static",
"ZonedDateTime",
"create",
"(",
"long",
"epochSecond",
",",
"int",
"nanoOfSecond",
",",
"ZoneId",
"zone",
")",
"{",
"ZoneRules",
"rules",
"=",
"zone",
".",
"getRules",
"(",
")",
";",
"Instant",
"instant",
"=",
"Instant",
".",
"ofEpochSecond",
"(",
"epochSecond",
",",
"nanoOfSecond",
")",
";",
"// TODO: rules should be queryable by epochSeconds",
"ZoneOffset",
"offset",
"=",
"rules",
".",
"getOffset",
"(",
"instant",
")",
";",
"LocalDateTime",
"ldt",
"=",
"LocalDateTime",
".",
"ofEpochSecond",
"(",
"epochSecond",
",",
"nanoOfSecond",
",",
"offset",
")",
";",
"return",
"new",
"ZonedDateTime",
"(",
"ldt",
",",
"offset",
",",
"zone",
")",
";",
"}"
]
| Obtains an instance of {@code ZonedDateTime} using seconds from the
epoch of 1970-01-01T00:00:00Z.
@param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z
@param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999
@param zone the time-zone, not null
@return the zoned date-time, not null
@throws DateTimeException if the result exceeds the supported range | [
"Obtains",
"an",
"instance",
"of",
"{",
"@code",
"ZonedDateTime",
"}",
"using",
"seconds",
"from",
"the",
"epoch",
"of",
"1970",
"-",
"01",
"-",
"01T00",
":",
"00",
":",
"00Z",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/ZonedDateTime.java#L446-L452 |
pressgang-ccms/PressGangCCMSContentSpec | src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java | EntityUtilities.getTopicRevisionsById | public static RevisionList getTopicRevisionsById(final TopicProvider topicProvider, final Integer csId) {
"""
/*
Gets a list of Revision's from the CSProcessor database for a specific content spec
"""
final List<Revision> results = new ArrayList<Revision>();
CollectionWrapper<TopicWrapper> topicRevisions = topicProvider.getTopic(csId).getRevisions();
// Create the unique array from the revisions
if (topicRevisions != null && topicRevisions.getItems() != null) {
final List<TopicWrapper> topicRevs = topicRevisions.getItems();
for (final TopicWrapper topicRev : topicRevs) {
Revision revision = new Revision();
revision.setRevision(topicRev.getRevision());
revision.setDate(topicRev.getLastModified());
results.add(revision);
}
Collections.sort(results, new EnversRevisionSort());
return new RevisionList(csId, "Topic", results);
} else {
return null;
}
} | java | public static RevisionList getTopicRevisionsById(final TopicProvider topicProvider, final Integer csId) {
final List<Revision> results = new ArrayList<Revision>();
CollectionWrapper<TopicWrapper> topicRevisions = topicProvider.getTopic(csId).getRevisions();
// Create the unique array from the revisions
if (topicRevisions != null && topicRevisions.getItems() != null) {
final List<TopicWrapper> topicRevs = topicRevisions.getItems();
for (final TopicWrapper topicRev : topicRevs) {
Revision revision = new Revision();
revision.setRevision(topicRev.getRevision());
revision.setDate(topicRev.getLastModified());
results.add(revision);
}
Collections.sort(results, new EnversRevisionSort());
return new RevisionList(csId, "Topic", results);
} else {
return null;
}
} | [
"public",
"static",
"RevisionList",
"getTopicRevisionsById",
"(",
"final",
"TopicProvider",
"topicProvider",
",",
"final",
"Integer",
"csId",
")",
"{",
"final",
"List",
"<",
"Revision",
">",
"results",
"=",
"new",
"ArrayList",
"<",
"Revision",
">",
"(",
")",
";",
"CollectionWrapper",
"<",
"TopicWrapper",
">",
"topicRevisions",
"=",
"topicProvider",
".",
"getTopic",
"(",
"csId",
")",
".",
"getRevisions",
"(",
")",
";",
"// Create the unique array from the revisions",
"if",
"(",
"topicRevisions",
"!=",
"null",
"&&",
"topicRevisions",
".",
"getItems",
"(",
")",
"!=",
"null",
")",
"{",
"final",
"List",
"<",
"TopicWrapper",
">",
"topicRevs",
"=",
"topicRevisions",
".",
"getItems",
"(",
")",
";",
"for",
"(",
"final",
"TopicWrapper",
"topicRev",
":",
"topicRevs",
")",
"{",
"Revision",
"revision",
"=",
"new",
"Revision",
"(",
")",
";",
"revision",
".",
"setRevision",
"(",
"topicRev",
".",
"getRevision",
"(",
")",
")",
";",
"revision",
".",
"setDate",
"(",
"topicRev",
".",
"getLastModified",
"(",
")",
")",
";",
"results",
".",
"add",
"(",
"revision",
")",
";",
"}",
"Collections",
".",
"sort",
"(",
"results",
",",
"new",
"EnversRevisionSort",
"(",
")",
")",
";",
"return",
"new",
"RevisionList",
"(",
"csId",
",",
"\"Topic\"",
",",
"results",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| /*
Gets a list of Revision's from the CSProcessor database for a specific content spec | [
"/",
"*",
"Gets",
"a",
"list",
"of",
"Revision",
"s",
"from",
"the",
"CSProcessor",
"database",
"for",
"a",
"specific",
"content",
"spec"
]
| train | https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java#L319-L339 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/common/logging/LogUtils.java | LogUtils.getLogger | public static Logger getLogger(Class<?> cls,
String resourcename,
String loggerName) {
"""
Get a Logger with an associated resource bundle.
@param cls the Class to contain the Logger (to find resources)
@param resourcename the resource name
@param loggerName the full name for the logger
@return an appropriate Logger
"""
return createLogger(cls, resourcename, loggerName);
} | java | public static Logger getLogger(Class<?> cls,
String resourcename,
String loggerName) {
return createLogger(cls, resourcename, loggerName);
} | [
"public",
"static",
"Logger",
"getLogger",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"String",
"resourcename",
",",
"String",
"loggerName",
")",
"{",
"return",
"createLogger",
"(",
"cls",
",",
"resourcename",
",",
"loggerName",
")",
";",
"}"
]
| Get a Logger with an associated resource bundle.
@param cls the Class to contain the Logger (to find resources)
@param resourcename the resource name
@param loggerName the full name for the logger
@return an appropriate Logger | [
"Get",
"a",
"Logger",
"with",
"an",
"associated",
"resource",
"bundle",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/common/logging/LogUtils.java#L189-L193 |
apache/spark | common/unsafe/src/main/java/org/apache/spark/unsafe/bitset/BitSetMethods.java | BitSetMethods.isSet | public static boolean isSet(Object baseObject, long baseOffset, int index) {
"""
Returns {@code true} if the bit is set at the specified index.
"""
assert index >= 0 : "index (" + index + ") should >= 0";
final long mask = 1L << (index & 0x3f); // mod 64 and shift
final long wordOffset = baseOffset + (index >> 6) * WORD_SIZE;
final long word = Platform.getLong(baseObject, wordOffset);
return (word & mask) != 0;
} | java | public static boolean isSet(Object baseObject, long baseOffset, int index) {
assert index >= 0 : "index (" + index + ") should >= 0";
final long mask = 1L << (index & 0x3f); // mod 64 and shift
final long wordOffset = baseOffset + (index >> 6) * WORD_SIZE;
final long word = Platform.getLong(baseObject, wordOffset);
return (word & mask) != 0;
} | [
"public",
"static",
"boolean",
"isSet",
"(",
"Object",
"baseObject",
",",
"long",
"baseOffset",
",",
"int",
"index",
")",
"{",
"assert",
"index",
">=",
"0",
":",
"\"index (\"",
"+",
"index",
"+",
"\") should >= 0\"",
";",
"final",
"long",
"mask",
"=",
"1L",
"<<",
"(",
"index",
"&",
"0x3f",
")",
";",
"// mod 64 and shift",
"final",
"long",
"wordOffset",
"=",
"baseOffset",
"+",
"(",
"index",
">>",
"6",
")",
"*",
"WORD_SIZE",
";",
"final",
"long",
"word",
"=",
"Platform",
".",
"getLong",
"(",
"baseObject",
",",
"wordOffset",
")",
";",
"return",
"(",
"word",
"&",
"mask",
")",
"!=",
"0",
";",
"}"
]
| Returns {@code true} if the bit is set at the specified index. | [
"Returns",
"{"
]
| train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/unsafe/src/main/java/org/apache/spark/unsafe/bitset/BitSetMethods.java#L62-L68 |
samskivert/samskivert | src/main/java/com/samskivert/swing/Controller.java | Controller.configureAction | public static void configureAction (AbstractButton button, String action) {
"""
Configures the supplied button with the {@link #DISPATCHER} action
listener and the specified action command (which, if it is a method name
will be looked up dynamically on the matching controller).
"""
button.setActionCommand(action);
button.addActionListener(DISPATCHER);
} | java | public static void configureAction (AbstractButton button, String action)
{
button.setActionCommand(action);
button.addActionListener(DISPATCHER);
} | [
"public",
"static",
"void",
"configureAction",
"(",
"AbstractButton",
"button",
",",
"String",
"action",
")",
"{",
"button",
".",
"setActionCommand",
"(",
"action",
")",
";",
"button",
".",
"addActionListener",
"(",
"DISPATCHER",
")",
";",
"}"
]
| Configures the supplied button with the {@link #DISPATCHER} action
listener and the specified action command (which, if it is a method name
will be looked up dynamically on the matching controller). | [
"Configures",
"the",
"supplied",
"button",
"with",
"the",
"{"
]
| train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/Controller.java#L147-L151 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/InitialReportWorker.java | InitialReportWorker.processReport | static void processReport(FSNamesystem namesystem, Collection<Block> toRetry,
BlockListAsLongs newReport, DatanodeDescriptor node,
ExecutorService initialBlockReportExecutor) throws IOException {
"""
Processes a single initial block reports, by spawning multiple threads to
handle insertion to the blocks map. Each thread stores the inserted blocks
in a local list, and at the end, the list are concatenated for a single
datanode descriptor.
"""
// spawn one thread for blocksPerShardBR blocks
int numShards = Math
.min(
namesystem.parallelProcessingThreads,
((newReport.getNumberOfBlocks()
+ namesystem.parallelBRblocksPerShard - 1) / namesystem.parallelBRblocksPerShard));
List<Future<List<Block>>> workers = new ArrayList<Future<List<Block>>>(
numShards);
// submit tasks for execution
for (int i = 0; i < numShards; i++) {
workers.add(initialBlockReportExecutor.submit(new InitialReportWorker(
newReport, i, numShards, node, namesystem.getNameNode()
.shouldRetryAbsentBlocks(), namesystem)));
}
// get results and add to retry list if need
try {
for (Future<List<Block>> worker : workers) {
if (namesystem.getNameNode().shouldRetryAbsentBlocks()) {
toRetry.addAll(worker.get());
} else {
worker.get();
}
}
} catch (ExecutionException e) {
LOG.warn("Parallel report failed", e);
throw new IOException(e);
} catch (InterruptedException e) {
throw new IOException("Interruption", e);
}
} | java | static void processReport(FSNamesystem namesystem, Collection<Block> toRetry,
BlockListAsLongs newReport, DatanodeDescriptor node,
ExecutorService initialBlockReportExecutor) throws IOException {
// spawn one thread for blocksPerShardBR blocks
int numShards = Math
.min(
namesystem.parallelProcessingThreads,
((newReport.getNumberOfBlocks()
+ namesystem.parallelBRblocksPerShard - 1) / namesystem.parallelBRblocksPerShard));
List<Future<List<Block>>> workers = new ArrayList<Future<List<Block>>>(
numShards);
// submit tasks for execution
for (int i = 0; i < numShards; i++) {
workers.add(initialBlockReportExecutor.submit(new InitialReportWorker(
newReport, i, numShards, node, namesystem.getNameNode()
.shouldRetryAbsentBlocks(), namesystem)));
}
// get results and add to retry list if need
try {
for (Future<List<Block>> worker : workers) {
if (namesystem.getNameNode().shouldRetryAbsentBlocks()) {
toRetry.addAll(worker.get());
} else {
worker.get();
}
}
} catch (ExecutionException e) {
LOG.warn("Parallel report failed", e);
throw new IOException(e);
} catch (InterruptedException e) {
throw new IOException("Interruption", e);
}
} | [
"static",
"void",
"processReport",
"(",
"FSNamesystem",
"namesystem",
",",
"Collection",
"<",
"Block",
">",
"toRetry",
",",
"BlockListAsLongs",
"newReport",
",",
"DatanodeDescriptor",
"node",
",",
"ExecutorService",
"initialBlockReportExecutor",
")",
"throws",
"IOException",
"{",
"// spawn one thread for blocksPerShardBR blocks",
"int",
"numShards",
"=",
"Math",
".",
"min",
"(",
"namesystem",
".",
"parallelProcessingThreads",
",",
"(",
"(",
"newReport",
".",
"getNumberOfBlocks",
"(",
")",
"+",
"namesystem",
".",
"parallelBRblocksPerShard",
"-",
"1",
")",
"/",
"namesystem",
".",
"parallelBRblocksPerShard",
")",
")",
";",
"List",
"<",
"Future",
"<",
"List",
"<",
"Block",
">",
">",
">",
"workers",
"=",
"new",
"ArrayList",
"<",
"Future",
"<",
"List",
"<",
"Block",
">",
">",
">",
"(",
"numShards",
")",
";",
"// submit tasks for execution",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numShards",
";",
"i",
"++",
")",
"{",
"workers",
".",
"add",
"(",
"initialBlockReportExecutor",
".",
"submit",
"(",
"new",
"InitialReportWorker",
"(",
"newReport",
",",
"i",
",",
"numShards",
",",
"node",
",",
"namesystem",
".",
"getNameNode",
"(",
")",
".",
"shouldRetryAbsentBlocks",
"(",
")",
",",
"namesystem",
")",
")",
")",
";",
"}",
"// get results and add to retry list if need",
"try",
"{",
"for",
"(",
"Future",
"<",
"List",
"<",
"Block",
">",
">",
"worker",
":",
"workers",
")",
"{",
"if",
"(",
"namesystem",
".",
"getNameNode",
"(",
")",
".",
"shouldRetryAbsentBlocks",
"(",
")",
")",
"{",
"toRetry",
".",
"addAll",
"(",
"worker",
".",
"get",
"(",
")",
")",
";",
"}",
"else",
"{",
"worker",
".",
"get",
"(",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Parallel report failed\"",
",",
"e",
")",
";",
"throw",
"new",
"IOException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Interruption\"",
",",
"e",
")",
";",
"}",
"}"
]
| Processes a single initial block reports, by spawning multiple threads to
handle insertion to the blocks map. Each thread stores the inserted blocks
in a local list, and at the end, the list are concatenated for a single
datanode descriptor. | [
"Processes",
"a",
"single",
"initial",
"block",
"reports",
"by",
"spawning",
"multiple",
"threads",
"to",
"handle",
"insertion",
"to",
"the",
"blocks",
"map",
".",
"Each",
"thread",
"stores",
"the",
"inserted",
"blocks",
"in",
"a",
"local",
"list",
"and",
"at",
"the",
"end",
"the",
"list",
"are",
"concatenated",
"for",
"a",
"single",
"datanode",
"descriptor",
"."
]
| train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/InitialReportWorker.java#L207-L241 |
apache/predictionio-sdk-java | client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java | EventClient.unsetUser | public String unsetUser(String uid, List<String> properties, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
"""
Unsets properties of a user. The list must not be empty.
@param uid ID of the user
@param properties a list of all the properties to unset
@param eventTime timestamp of the event
@return ID of this event
"""
return createEvent(unsetUserAsFuture(uid, properties, eventTime));
} | java | public String unsetUser(String uid, List<String> properties, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
return createEvent(unsetUserAsFuture(uid, properties, eventTime));
} | [
"public",
"String",
"unsetUser",
"(",
"String",
"uid",
",",
"List",
"<",
"String",
">",
"properties",
",",
"DateTime",
"eventTime",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"IOException",
"{",
"return",
"createEvent",
"(",
"unsetUserAsFuture",
"(",
"uid",
",",
"properties",
",",
"eventTime",
")",
")",
";",
"}"
]
| Unsets properties of a user. The list must not be empty.
@param uid ID of the user
@param properties a list of all the properties to unset
@param eventTime timestamp of the event
@return ID of this event | [
"Unsets",
"properties",
"of",
"a",
"user",
".",
"The",
"list",
"must",
"not",
"be",
"empty",
"."
]
| train | https://github.com/apache/predictionio-sdk-java/blob/16052c96b136340c175c3f9c2692e720850df219/client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java#L381-L384 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/sender/http2/Http2ConnectionManager.java | Http2ConnectionManager.addHttp2ClientChannel | public void addHttp2ClientChannel(EventLoop eventLoop, HttpRoute httpRoute, Http2ClientChannel http2ClientChannel) {
"""
Add a given {@link Http2ClientChannel} to the relevant pool.
@param eventLoop netty event loop
@param httpRoute http route
@param http2ClientChannel newly created http/2 client channel
"""
if (!eventLoops.contains(eventLoop)) {
eventLoops.add(eventLoop);
}
final EventLoopPool eventLoopPool = getOrCreateEventLoopPool(eventLoop);
String key = generateKey(httpRoute);
final EventLoopPool.PerRouteConnectionPool perRouteConnectionPool = getOrCreatePerRoutePool(eventLoopPool, key);
perRouteConnectionPool.addChannel(http2ClientChannel);
// Configure a listener to remove connection from pool when it is closed
http2ClientChannel.getChannel().closeFuture().
addListener(future -> {
EventLoopPool.PerRouteConnectionPool pool = eventLoopPool.fetchPerRoutePool(key);
if (pool != null) {
pool.removeChannel(http2ClientChannel);
http2ClientChannel.getDataEventListeners().
forEach(Http2DataEventListener::destroy);
}
}
);
} | java | public void addHttp2ClientChannel(EventLoop eventLoop, HttpRoute httpRoute, Http2ClientChannel http2ClientChannel) {
if (!eventLoops.contains(eventLoop)) {
eventLoops.add(eventLoop);
}
final EventLoopPool eventLoopPool = getOrCreateEventLoopPool(eventLoop);
String key = generateKey(httpRoute);
final EventLoopPool.PerRouteConnectionPool perRouteConnectionPool = getOrCreatePerRoutePool(eventLoopPool, key);
perRouteConnectionPool.addChannel(http2ClientChannel);
// Configure a listener to remove connection from pool when it is closed
http2ClientChannel.getChannel().closeFuture().
addListener(future -> {
EventLoopPool.PerRouteConnectionPool pool = eventLoopPool.fetchPerRoutePool(key);
if (pool != null) {
pool.removeChannel(http2ClientChannel);
http2ClientChannel.getDataEventListeners().
forEach(Http2DataEventListener::destroy);
}
}
);
} | [
"public",
"void",
"addHttp2ClientChannel",
"(",
"EventLoop",
"eventLoop",
",",
"HttpRoute",
"httpRoute",
",",
"Http2ClientChannel",
"http2ClientChannel",
")",
"{",
"if",
"(",
"!",
"eventLoops",
".",
"contains",
"(",
"eventLoop",
")",
")",
"{",
"eventLoops",
".",
"add",
"(",
"eventLoop",
")",
";",
"}",
"final",
"EventLoopPool",
"eventLoopPool",
"=",
"getOrCreateEventLoopPool",
"(",
"eventLoop",
")",
";",
"String",
"key",
"=",
"generateKey",
"(",
"httpRoute",
")",
";",
"final",
"EventLoopPool",
".",
"PerRouteConnectionPool",
"perRouteConnectionPool",
"=",
"getOrCreatePerRoutePool",
"(",
"eventLoopPool",
",",
"key",
")",
";",
"perRouteConnectionPool",
".",
"addChannel",
"(",
"http2ClientChannel",
")",
";",
"// Configure a listener to remove connection from pool when it is closed",
"http2ClientChannel",
".",
"getChannel",
"(",
")",
".",
"closeFuture",
"(",
")",
".",
"addListener",
"(",
"future",
"->",
"{",
"EventLoopPool",
".",
"PerRouteConnectionPool",
"pool",
"=",
"eventLoopPool",
".",
"fetchPerRoutePool",
"(",
"key",
")",
";",
"if",
"(",
"pool",
"!=",
"null",
")",
"{",
"pool",
".",
"removeChannel",
"(",
"http2ClientChannel",
")",
";",
"http2ClientChannel",
".",
"getDataEventListeners",
"(",
")",
".",
"forEach",
"(",
"Http2DataEventListener",
"::",
"destroy",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Add a given {@link Http2ClientChannel} to the relevant pool.
@param eventLoop netty event loop
@param httpRoute http route
@param http2ClientChannel newly created http/2 client channel | [
"Add",
"a",
"given",
"{",
"@link",
"Http2ClientChannel",
"}",
"to",
"the",
"relevant",
"pool",
"."
]
| train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/sender/http2/Http2ConnectionManager.java#L50-L70 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java | ImageDrawing.drawTo | public static void drawTo(Bitmap src, Bitmap dest, int color) {
"""
Drawing bitmap over dest bitmap with clearing last one before drawing
@param src source bitmap
@param dest destination bitmap
@param color clear color
"""
clearBitmap(src, color);
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(src, 0, 0, null);
canvas.setBitmap(null);
} | java | public static void drawTo(Bitmap src, Bitmap dest, int color) {
clearBitmap(src, color);
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(src, 0, 0, null);
canvas.setBitmap(null);
} | [
"public",
"static",
"void",
"drawTo",
"(",
"Bitmap",
"src",
",",
"Bitmap",
"dest",
",",
"int",
"color",
")",
"{",
"clearBitmap",
"(",
"src",
",",
"color",
")",
";",
"Canvas",
"canvas",
"=",
"new",
"Canvas",
"(",
"dest",
")",
";",
"canvas",
".",
"drawBitmap",
"(",
"src",
",",
"0",
",",
"0",
",",
"null",
")",
";",
"canvas",
".",
"setBitmap",
"(",
"null",
")",
";",
"}"
]
| Drawing bitmap over dest bitmap with clearing last one before drawing
@param src source bitmap
@param dest destination bitmap
@param color clear color | [
"Drawing",
"bitmap",
"over",
"dest",
"bitmap",
"with",
"clearing",
"last",
"one",
"before",
"drawing"
]
| train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java#L54-L59 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/SCW.java | SCW.setEta | public void setEta(double eta) {
"""
SCW uses a probabilistic version of the margin and attempts to make a
correction so that the confidence with correct label would be of a
certain threshold, which is set by eta. So the threshold must be in
[0.5, 1.0]. Values in the range [0.8, 0.9] often work well on a wide
range of problems
@param eta the confidence to correct to
"""
if(Double.isNaN(eta) || eta < 0.5 || eta > 1.0)
throw new IllegalArgumentException("eta must be in [0.5, 1] not " + eta);
this.eta = eta;
this.phi = Normal.invcdf(eta, 0, 1);
this.phiSqrd = phi*phi;
this.zeta = 1 + phiSqrd;
this.psi = 1 + phiSqrd/2;
} | java | public void setEta(double eta)
{
if(Double.isNaN(eta) || eta < 0.5 || eta > 1.0)
throw new IllegalArgumentException("eta must be in [0.5, 1] not " + eta);
this.eta = eta;
this.phi = Normal.invcdf(eta, 0, 1);
this.phiSqrd = phi*phi;
this.zeta = 1 + phiSqrd;
this.psi = 1 + phiSqrd/2;
} | [
"public",
"void",
"setEta",
"(",
"double",
"eta",
")",
"{",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"eta",
")",
"||",
"eta",
"<",
"0.5",
"||",
"eta",
">",
"1.0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"eta must be in [0.5, 1] not \"",
"+",
"eta",
")",
";",
"this",
".",
"eta",
"=",
"eta",
";",
"this",
".",
"phi",
"=",
"Normal",
".",
"invcdf",
"(",
"eta",
",",
"0",
",",
"1",
")",
";",
"this",
".",
"phiSqrd",
"=",
"phi",
"*",
"phi",
";",
"this",
".",
"zeta",
"=",
"1",
"+",
"phiSqrd",
";",
"this",
".",
"psi",
"=",
"1",
"+",
"phiSqrd",
"/",
"2",
";",
"}"
]
| SCW uses a probabilistic version of the margin and attempts to make a
correction so that the confidence with correct label would be of a
certain threshold, which is set by eta. So the threshold must be in
[0.5, 1.0]. Values in the range [0.8, 0.9] often work well on a wide
range of problems
@param eta the confidence to correct to | [
"SCW",
"uses",
"a",
"probabilistic",
"version",
"of",
"the",
"margin",
"and",
"attempts",
"to",
"make",
"a",
"correction",
"so",
"that",
"the",
"confidence",
"with",
"correct",
"label",
"would",
"be",
"of",
"a",
"certain",
"threshold",
"which",
"is",
"set",
"by",
"eta",
".",
"So",
"the",
"threshold",
"must",
"be",
"in",
"[",
"0",
".",
"5",
"1",
".",
"0",
"]",
".",
"Values",
"in",
"the",
"range",
"[",
"0",
".",
"8",
"0",
".",
"9",
"]",
"often",
"work",
"well",
"on",
"a",
"wide",
"range",
"of",
"problems"
]
| train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/SCW.java#L169-L178 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java | InternalService.isTyping | public void isTyping(@NonNull final String conversationId, @Nullable Callback<ComapiResult<Void>> callback) {
"""
Send 'user is typing' message for specified conversation.
@param conversationId ID of a conversation.
@param callback Callback to deliver result.
"""
adapter.adapt(isTyping(conversationId, true), callback);
} | java | public void isTyping(@NonNull final String conversationId, @Nullable Callback<ComapiResult<Void>> callback) {
adapter.adapt(isTyping(conversationId, true), callback);
} | [
"public",
"void",
"isTyping",
"(",
"@",
"NonNull",
"final",
"String",
"conversationId",
",",
"@",
"Nullable",
"Callback",
"<",
"ComapiResult",
"<",
"Void",
">",
">",
"callback",
")",
"{",
"adapter",
".",
"adapt",
"(",
"isTyping",
"(",
"conversationId",
",",
"true",
")",
",",
"callback",
")",
";",
"}"
]
| Send 'user is typing' message for specified conversation.
@param conversationId ID of a conversation.
@param callback Callback to deliver result. | [
"Send",
"user",
"is",
"typing",
"message",
"for",
"specified",
"conversation",
"."
]
| train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L929-L931 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java | SparkUtils.readStringFromFile | public static String readStringFromFile(String path, SparkContext sc) throws IOException {
"""
Read a UTF-8 format String from HDFS (or local)
@param path Path to write the string
@param sc Spark context
"""
FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration());
try (BufferedInputStream bis = new BufferedInputStream(fileSystem.open(new Path(path)))) {
byte[] asBytes = IOUtils.toByteArray(bis);
return new String(asBytes, "UTF-8");
}
} | java | public static String readStringFromFile(String path, SparkContext sc) throws IOException {
FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration());
try (BufferedInputStream bis = new BufferedInputStream(fileSystem.open(new Path(path)))) {
byte[] asBytes = IOUtils.toByteArray(bis);
return new String(asBytes, "UTF-8");
}
} | [
"public",
"static",
"String",
"readStringFromFile",
"(",
"String",
"path",
",",
"SparkContext",
"sc",
")",
"throws",
"IOException",
"{",
"FileSystem",
"fileSystem",
"=",
"FileSystem",
".",
"get",
"(",
"sc",
".",
"hadoopConfiguration",
"(",
")",
")",
";",
"try",
"(",
"BufferedInputStream",
"bis",
"=",
"new",
"BufferedInputStream",
"(",
"fileSystem",
".",
"open",
"(",
"new",
"Path",
"(",
"path",
")",
")",
")",
")",
"{",
"byte",
"[",
"]",
"asBytes",
"=",
"IOUtils",
".",
"toByteArray",
"(",
"bis",
")",
";",
"return",
"new",
"String",
"(",
"asBytes",
",",
"\"UTF-8\"",
")",
";",
"}",
"}"
]
| Read a UTF-8 format String from HDFS (or local)
@param path Path to write the string
@param sc Spark context | [
"Read",
"a",
"UTF",
"-",
"8",
"format",
"String",
"from",
"HDFS",
"(",
"or",
"local",
")"
]
| train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L180-L186 |
rimerosolutions/ant-git-tasks | src/main/java/com/rimerosolutions/ant/git/AbstractGitRepoAwareTask.java | AbstractGitRepoAwareTask.translateFilePathUsingPrefix | protected String translateFilePathUsingPrefix(String file, String prefix) throws IOException {
"""
return either a "." if file and prefix have the same value,
or the right part of file - length of prefix plus one removed
@param file file on which a git operation needs to be done
@param prefix folder of the git sandbox
@return path relative to git sandbox folder
@throws IOException the method uses File#getCanonicalPath which can throw IOException
"""
if (file.equals(prefix)) {
return ".";
}
String result = new File(file).getCanonicalPath().substring(prefix.length() + 1);
if (File.separatorChar != '/') {
result = result.replace(File.separatorChar, '/');
}
return result;
} | java | protected String translateFilePathUsingPrefix(String file, String prefix) throws IOException {
if (file.equals(prefix)) {
return ".";
}
String result = new File(file).getCanonicalPath().substring(prefix.length() + 1);
if (File.separatorChar != '/') {
result = result.replace(File.separatorChar, '/');
}
return result;
} | [
"protected",
"String",
"translateFilePathUsingPrefix",
"(",
"String",
"file",
",",
"String",
"prefix",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
".",
"equals",
"(",
"prefix",
")",
")",
"{",
"return",
"\".\"",
";",
"}",
"String",
"result",
"=",
"new",
"File",
"(",
"file",
")",
".",
"getCanonicalPath",
"(",
")",
".",
"substring",
"(",
"prefix",
".",
"length",
"(",
")",
"+",
"1",
")",
";",
"if",
"(",
"File",
".",
"separatorChar",
"!=",
"'",
"'",
")",
"{",
"result",
"=",
"result",
".",
"replace",
"(",
"File",
".",
"separatorChar",
",",
"'",
"'",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| return either a "." if file and prefix have the same value,
or the right part of file - length of prefix plus one removed
@param file file on which a git operation needs to be done
@param prefix folder of the git sandbox
@return path relative to git sandbox folder
@throws IOException the method uses File#getCanonicalPath which can throw IOException | [
"return",
"either",
"a",
".",
"if",
"file",
"and",
"prefix",
"have",
"the",
"same",
"value",
"or",
"the",
"right",
"part",
"of",
"file",
"-",
"length",
"of",
"prefix",
"plus",
"one",
"removed"
]
| train | https://github.com/rimerosolutions/ant-git-tasks/blob/bfb32fe68afe6b9dcfd0a5194497d748ef3e8a6f/src/main/java/com/rimerosolutions/ant/git/AbstractGitRepoAwareTask.java#L99-L108 |
cryptomator/webdav-nio-adapter | src/main/java/org/cryptomator/frontend/webdav/mount/ProcessUtil.java | ProcessUtil.startAndWaitFor | public static Process startAndWaitFor(ProcessBuilder processBuilder, long timeout, TimeUnit unit) throws CommandFailedException, CommandTimeoutException {
"""
Starts a new process and invokes {@link #waitFor(Process, long, TimeUnit)}.
@param processBuilder The process builder used to start the new process
@param timeout Maximum time to wait
@param unit Time unit of <code>timeout</code>
@return The finished process.
@throws CommandFailedException If an I/O error occurs when starting the process.
@throws CommandTimeoutException Thrown in case of a timeout
"""
try {
Process proc = processBuilder.start();
waitFor(proc, timeout, unit);
return proc;
} catch (IOException e) {
throw new CommandFailedException(e);
}
} | java | public static Process startAndWaitFor(ProcessBuilder processBuilder, long timeout, TimeUnit unit) throws CommandFailedException, CommandTimeoutException {
try {
Process proc = processBuilder.start();
waitFor(proc, timeout, unit);
return proc;
} catch (IOException e) {
throw new CommandFailedException(e);
}
} | [
"public",
"static",
"Process",
"startAndWaitFor",
"(",
"ProcessBuilder",
"processBuilder",
",",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"CommandFailedException",
",",
"CommandTimeoutException",
"{",
"try",
"{",
"Process",
"proc",
"=",
"processBuilder",
".",
"start",
"(",
")",
";",
"waitFor",
"(",
"proc",
",",
"timeout",
",",
"unit",
")",
";",
"return",
"proc",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"CommandFailedException",
"(",
"e",
")",
";",
"}",
"}"
]
| Starts a new process and invokes {@link #waitFor(Process, long, TimeUnit)}.
@param processBuilder The process builder used to start the new process
@param timeout Maximum time to wait
@param unit Time unit of <code>timeout</code>
@return The finished process.
@throws CommandFailedException If an I/O error occurs when starting the process.
@throws CommandTimeoutException Thrown in case of a timeout | [
"Starts",
"a",
"new",
"process",
"and",
"invokes",
"{",
"@link",
"#waitFor",
"(",
"Process",
"long",
"TimeUnit",
")",
"}",
"."
]
| train | https://github.com/cryptomator/webdav-nio-adapter/blob/55b0d7dccea9a4ede0a30a95583d8f04c8a86d18/src/main/java/org/cryptomator/frontend/webdav/mount/ProcessUtil.java#L45-L53 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java | DataGridStateFactory.getDataGridURLBuilder | public final DataGridURLBuilder getDataGridURLBuilder(String name, DataGridConfig config) {
"""
<p>
Lookup a {@link DataGridURLBuilder} object given a data grid identifier and a specific
{@link DataGridConfig} object.
</p>
@param name the name of the data grid
@param config the {@link DataGridConfig} object to use when creating the
grid's {@link DataGridURLBuilder} object.
@return the URL builder for a data grid's state object
"""
if(config == null)
throw new IllegalArgumentException(Bundle.getErrorString("DataGridStateFactory_nullDataGridConfig"));
DataGridStateCodec codec = lookupCodec(name, config);
DataGridURLBuilder builder = codec.getDataGridURLBuilder();
return builder;
} | java | public final DataGridURLBuilder getDataGridURLBuilder(String name, DataGridConfig config) {
if(config == null)
throw new IllegalArgumentException(Bundle.getErrorString("DataGridStateFactory_nullDataGridConfig"));
DataGridStateCodec codec = lookupCodec(name, config);
DataGridURLBuilder builder = codec.getDataGridURLBuilder();
return builder;
} | [
"public",
"final",
"DataGridURLBuilder",
"getDataGridURLBuilder",
"(",
"String",
"name",
",",
"DataGridConfig",
"config",
")",
"{",
"if",
"(",
"config",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"Bundle",
".",
"getErrorString",
"(",
"\"DataGridStateFactory_nullDataGridConfig\"",
")",
")",
";",
"DataGridStateCodec",
"codec",
"=",
"lookupCodec",
"(",
"name",
",",
"config",
")",
";",
"DataGridURLBuilder",
"builder",
"=",
"codec",
".",
"getDataGridURLBuilder",
"(",
")",
";",
"return",
"builder",
";",
"}"
]
| <p>
Lookup a {@link DataGridURLBuilder} object given a data grid identifier and a specific
{@link DataGridConfig} object.
</p>
@param name the name of the data grid
@param config the {@link DataGridConfig} object to use when creating the
grid's {@link DataGridURLBuilder} object.
@return the URL builder for a data grid's state object | [
"<p",
">",
"Lookup",
"a",
"{",
"@link",
"DataGridURLBuilder",
"}",
"object",
"given",
"a",
"data",
"grid",
"identifier",
"and",
"a",
"specific",
"{",
"@link",
"DataGridConfig",
"}",
"object",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/DataGridStateFactory.java#L153-L160 |
alexcojocaru/elasticsearch-maven-plugin | src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java | Monitor.isClusterRunning | public static boolean isClusterRunning(String clusterName, int instanceCount, int httpPort) {
"""
Verify that the cluster name and the number of nodes in the cluster,
as reported by the ES node, is as expected.
@param clusterName the ES cluster name
@param instanceCount the number of ES nodes in the cluster
@param httpPort the HTTP port to connect to ES
@return true if the cluster is running, false otherwise
"""
Log log = Mockito.mock(Log.class);
try (ElasticsearchClient client = new ElasticsearchClient.Builder()
.withLog(log)
.withHostname("localhost")
.withPort(httpPort)
.withSocketTimeout(5000)
.build())
{
return isClusterRunning(clusterName, instanceCount, client);
}
} | java | public static boolean isClusterRunning(String clusterName, int instanceCount, int httpPort)
{
Log log = Mockito.mock(Log.class);
try (ElasticsearchClient client = new ElasticsearchClient.Builder()
.withLog(log)
.withHostname("localhost")
.withPort(httpPort)
.withSocketTimeout(5000)
.build())
{
return isClusterRunning(clusterName, instanceCount, client);
}
} | [
"public",
"static",
"boolean",
"isClusterRunning",
"(",
"String",
"clusterName",
",",
"int",
"instanceCount",
",",
"int",
"httpPort",
")",
"{",
"Log",
"log",
"=",
"Mockito",
".",
"mock",
"(",
"Log",
".",
"class",
")",
";",
"try",
"(",
"ElasticsearchClient",
"client",
"=",
"new",
"ElasticsearchClient",
".",
"Builder",
"(",
")",
".",
"withLog",
"(",
"log",
")",
".",
"withHostname",
"(",
"\"localhost\"",
")",
".",
"withPort",
"(",
"httpPort",
")",
".",
"withSocketTimeout",
"(",
"5000",
")",
".",
"build",
"(",
")",
")",
"{",
"return",
"isClusterRunning",
"(",
"clusterName",
",",
"instanceCount",
",",
"client",
")",
";",
"}",
"}"
]
| Verify that the cluster name and the number of nodes in the cluster,
as reported by the ES node, is as expected.
@param clusterName the ES cluster name
@param instanceCount the number of ES nodes in the cluster
@param httpPort the HTTP port to connect to ES
@return true if the cluster is running, false otherwise | [
"Verify",
"that",
"the",
"cluster",
"name",
"and",
"the",
"number",
"of",
"nodes",
"in",
"the",
"cluster",
"as",
"reported",
"by",
"the",
"ES",
"node",
"is",
"as",
"expected",
"."
]
| train | https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java#L176-L189 |
javers/javers | javers-core/src/main/java/org/javers/core/metamodel/clazz/ClientsClassDefinitionBuilder.java | ClientsClassDefinitionBuilder.withIgnoredProperties | public T withIgnoredProperties(List<String> ignoredProperties) {
"""
List of class properties to be ignored by JaVers.
<br/><br/>
Properties can be also ignored with the {@link DiffIgnore} annotation.
<br/><br/>
You can either specify includedProperties or ignoredProperties, not both.
@see DiffIgnore
@throws IllegalArgumentException If includedProperties was already set.
"""
Validate.argumentIsNotNull(ignoredProperties);
if (includedProperties.size() > 0) {
throw new JaversException(JaversExceptionCode.IGNORED_AND_INCLUDED_PROPERTIES_MIX, clazz.getSimpleName());
}
this.ignoredProperties = ignoredProperties;
return (T) this;
} | java | public T withIgnoredProperties(List<String> ignoredProperties) {
Validate.argumentIsNotNull(ignoredProperties);
if (includedProperties.size() > 0) {
throw new JaversException(JaversExceptionCode.IGNORED_AND_INCLUDED_PROPERTIES_MIX, clazz.getSimpleName());
}
this.ignoredProperties = ignoredProperties;
return (T) this;
} | [
"public",
"T",
"withIgnoredProperties",
"(",
"List",
"<",
"String",
">",
"ignoredProperties",
")",
"{",
"Validate",
".",
"argumentIsNotNull",
"(",
"ignoredProperties",
")",
";",
"if",
"(",
"includedProperties",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"throw",
"new",
"JaversException",
"(",
"JaversExceptionCode",
".",
"IGNORED_AND_INCLUDED_PROPERTIES_MIX",
",",
"clazz",
".",
"getSimpleName",
"(",
")",
")",
";",
"}",
"this",
".",
"ignoredProperties",
"=",
"ignoredProperties",
";",
"return",
"(",
"T",
")",
"this",
";",
"}"
]
| List of class properties to be ignored by JaVers.
<br/><br/>
Properties can be also ignored with the {@link DiffIgnore} annotation.
<br/><br/>
You can either specify includedProperties or ignoredProperties, not both.
@see DiffIgnore
@throws IllegalArgumentException If includedProperties was already set. | [
"List",
"of",
"class",
"properties",
"to",
"be",
"ignored",
"by",
"JaVers",
".",
"<br",
"/",
">",
"<br",
"/",
">"
]
| train | https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/core/metamodel/clazz/ClientsClassDefinitionBuilder.java#L49-L56 |
threerings/nenya | core/src/main/java/com/threerings/util/KeyTranslatorImpl.java | KeyTranslatorImpl.addReleaseCommand | public void addReleaseCommand (int keyCode, String command) {
"""
Adds a mapping from a key release to an action command string. Overwrites any existing
mapping that may already have been registered.
"""
KeyRecord krec = getKeyRecord(keyCode);
krec.releaseCommand = command;
} | java | public void addReleaseCommand (int keyCode, String command)
{
KeyRecord krec = getKeyRecord(keyCode);
krec.releaseCommand = command;
} | [
"public",
"void",
"addReleaseCommand",
"(",
"int",
"keyCode",
",",
"String",
"command",
")",
"{",
"KeyRecord",
"krec",
"=",
"getKeyRecord",
"(",
"keyCode",
")",
";",
"krec",
".",
"releaseCommand",
"=",
"command",
";",
"}"
]
| Adds a mapping from a key release to an action command string. Overwrites any existing
mapping that may already have been registered. | [
"Adds",
"a",
"mapping",
"from",
"a",
"key",
"release",
"to",
"an",
"action",
"command",
"string",
".",
"Overwrites",
"any",
"existing",
"mapping",
"that",
"may",
"already",
"have",
"been",
"registered",
"."
]
| train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/util/KeyTranslatorImpl.java#L82-L86 |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java | KnowledgeSwitchYardScanner.toResourcesModel | protected ResourcesModel toResourcesModel(Resource[] resourceAnnotations, KnowledgeNamespace knowledgeNamespace) {
"""
Converts resource annotations to resources model.
@param resourceAnnotations resourceAnnotations
@param knowledgeNamespace knowledgeNamespace
@return model
"""
if (resourceAnnotations == null || resourceAnnotations.length == 0) {
return null;
}
ResourcesModel resourcesModel = new V1ResourcesModel(knowledgeNamespace.uri());
for (Resource resourceAnnotation : resourceAnnotations) {
ResourceModel resourceModel = new V1ResourceModel(knowledgeNamespace.uri());
String location = resourceAnnotation.location();
if (!UNDEFINED.equals(location)) {
resourceModel.setLocation(location);
}
String type = resourceAnnotation.type();
if (!UNDEFINED.equals(type)) {
resourceModel.setType(ResourceType.valueOf(type));
}
ResourceDetailModel resourceDetailModel = toResourceDetailModel(resourceAnnotation.detail(), knowledgeNamespace);
if (resourceDetailModel != null) {
resourceModel.setDetail(resourceDetailModel);
}
resourcesModel.addResource(resourceModel);
}
return resourcesModel;
} | java | protected ResourcesModel toResourcesModel(Resource[] resourceAnnotations, KnowledgeNamespace knowledgeNamespace) {
if (resourceAnnotations == null || resourceAnnotations.length == 0) {
return null;
}
ResourcesModel resourcesModel = new V1ResourcesModel(knowledgeNamespace.uri());
for (Resource resourceAnnotation : resourceAnnotations) {
ResourceModel resourceModel = new V1ResourceModel(knowledgeNamespace.uri());
String location = resourceAnnotation.location();
if (!UNDEFINED.equals(location)) {
resourceModel.setLocation(location);
}
String type = resourceAnnotation.type();
if (!UNDEFINED.equals(type)) {
resourceModel.setType(ResourceType.valueOf(type));
}
ResourceDetailModel resourceDetailModel = toResourceDetailModel(resourceAnnotation.detail(), knowledgeNamespace);
if (resourceDetailModel != null) {
resourceModel.setDetail(resourceDetailModel);
}
resourcesModel.addResource(resourceModel);
}
return resourcesModel;
} | [
"protected",
"ResourcesModel",
"toResourcesModel",
"(",
"Resource",
"[",
"]",
"resourceAnnotations",
",",
"KnowledgeNamespace",
"knowledgeNamespace",
")",
"{",
"if",
"(",
"resourceAnnotations",
"==",
"null",
"||",
"resourceAnnotations",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"ResourcesModel",
"resourcesModel",
"=",
"new",
"V1ResourcesModel",
"(",
"knowledgeNamespace",
".",
"uri",
"(",
")",
")",
";",
"for",
"(",
"Resource",
"resourceAnnotation",
":",
"resourceAnnotations",
")",
"{",
"ResourceModel",
"resourceModel",
"=",
"new",
"V1ResourceModel",
"(",
"knowledgeNamespace",
".",
"uri",
"(",
")",
")",
";",
"String",
"location",
"=",
"resourceAnnotation",
".",
"location",
"(",
")",
";",
"if",
"(",
"!",
"UNDEFINED",
".",
"equals",
"(",
"location",
")",
")",
"{",
"resourceModel",
".",
"setLocation",
"(",
"location",
")",
";",
"}",
"String",
"type",
"=",
"resourceAnnotation",
".",
"type",
"(",
")",
";",
"if",
"(",
"!",
"UNDEFINED",
".",
"equals",
"(",
"type",
")",
")",
"{",
"resourceModel",
".",
"setType",
"(",
"ResourceType",
".",
"valueOf",
"(",
"type",
")",
")",
";",
"}",
"ResourceDetailModel",
"resourceDetailModel",
"=",
"toResourceDetailModel",
"(",
"resourceAnnotation",
".",
"detail",
"(",
")",
",",
"knowledgeNamespace",
")",
";",
"if",
"(",
"resourceDetailModel",
"!=",
"null",
")",
"{",
"resourceModel",
".",
"setDetail",
"(",
"resourceDetailModel",
")",
";",
"}",
"resourcesModel",
".",
"addResource",
"(",
"resourceModel",
")",
";",
"}",
"return",
"resourcesModel",
";",
"}"
]
| Converts resource annotations to resources model.
@param resourceAnnotations resourceAnnotations
@param knowledgeNamespace knowledgeNamespace
@return model | [
"Converts",
"resource",
"annotations",
"to",
"resources",
"model",
"."
]
| train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java#L370-L392 |
czyzby/gdx-lml | lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java | LmlApplicationListener.addClassAlias | protected void addClassAlias(final String alias, final Class<? extends AbstractLmlView> viewClass) {
"""
This method is automatically invoked with {@link AbstractLmlView#getViewId()} (if it returns a non-empty value)
on each view initiated with {@link #initiateView(AbstractLmlView)}. This method can be invoked manually for lazy
views loading: they will be accessible through the chosen alias in LML templates even when their instance is not
created yet.
<p>
If you initiate all views eagerly (in the correct order in which they reference one another), they are likely to
already registered by the time {@link LmlParser} parses their templates. However, calling this method for each of
your expected views in {@link #create()} is considered a good practice if you use {@code setView} LML method to
switch between screens.
@param alias name of the view in LML templates. It will be used by {@code setView} LML method to choose the
appropriate view class.
@param viewClass will be mapped to the selected alias.
"""
aliases.put(alias, viewClass);
} | java | protected void addClassAlias(final String alias, final Class<? extends AbstractLmlView> viewClass) {
aliases.put(alias, viewClass);
} | [
"protected",
"void",
"addClassAlias",
"(",
"final",
"String",
"alias",
",",
"final",
"Class",
"<",
"?",
"extends",
"AbstractLmlView",
">",
"viewClass",
")",
"{",
"aliases",
".",
"put",
"(",
"alias",
",",
"viewClass",
")",
";",
"}"
]
| This method is automatically invoked with {@link AbstractLmlView#getViewId()} (if it returns a non-empty value)
on each view initiated with {@link #initiateView(AbstractLmlView)}. This method can be invoked manually for lazy
views loading: they will be accessible through the chosen alias in LML templates even when their instance is not
created yet.
<p>
If you initiate all views eagerly (in the correct order in which they reference one another), they are likely to
already registered by the time {@link LmlParser} parses their templates. However, calling this method for each of
your expected views in {@link #create()} is considered a good practice if you use {@code setView} LML method to
switch between screens.
@param alias name of the view in LML templates. It will be used by {@code setView} LML method to choose the
appropriate view class.
@param viewClass will be mapped to the selected alias. | [
"This",
"method",
"is",
"automatically",
"invoked",
"with",
"{",
"@link",
"AbstractLmlView#getViewId",
"()",
"}",
"(",
"if",
"it",
"returns",
"a",
"non",
"-",
"empty",
"value",
")",
"on",
"each",
"view",
"initiated",
"with",
"{",
"@link",
"#initiateView",
"(",
"AbstractLmlView",
")",
"}",
".",
"This",
"method",
"can",
"be",
"invoked",
"manually",
"for",
"lazy",
"views",
"loading",
":",
"they",
"will",
"be",
"accessible",
"through",
"the",
"chosen",
"alias",
"in",
"LML",
"templates",
"even",
"when",
"their",
"instance",
"is",
"not",
"created",
"yet",
"."
]
| train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java#L85-L87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.