repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/ThemeUtil.java | ThemeUtil.getBoolean | public static boolean getBoolean(@NonNull final Context context, @AttrRes final int resourceId,
final boolean defaultValue) {
"""
Obtains the boolean value, which corresponds to a specific resource id, from a context's
theme.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param resourceId
The resource id of the attribute, which should be obtained, as an {@link Integer}
value. The resource id must corresponds to a valid theme attribute
@param defaultValue
The default value, which should be returned, if the given resource id is invalid, as
a {@link Boolean} value
@return The boolean value, which has been obtained, as an {@link Boolean} value or false, if
the given resource id is invalid
"""
return getBoolean(context, -1, resourceId, defaultValue);
} | java | public static boolean getBoolean(@NonNull final Context context, @AttrRes final int resourceId,
final boolean defaultValue) {
return getBoolean(context, -1, resourceId, defaultValue);
} | [
"public",
"static",
"boolean",
"getBoolean",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"AttrRes",
"final",
"int",
"resourceId",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"return",
"getBoolean",
"(",
"context",
",",
"-",
"1",
",",
"resourceId",
",",
"defaultValue",
")",
";",
"}"
] | Obtains the boolean value, which corresponds to a specific resource id, from a context's
theme.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param resourceId
The resource id of the attribute, which should be obtained, as an {@link Integer}
value. The resource id must corresponds to a valid theme attribute
@param defaultValue
The default value, which should be returned, if the given resource id is invalid, as
a {@link Boolean} value
@return The boolean value, which has been obtained, as an {@link Boolean} value or false, if
the given resource id is invalid | [
"Obtains",
"the",
"boolean",
"value",
"which",
"corresponds",
"to",
"a",
"specific",
"resource",
"id",
"from",
"a",
"context",
"s",
"theme",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/ThemeUtil.java#L701-L704 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DcosSpec.java | DcosSpec.convertJSONSchemaToJSON | @Given("^I convert jsonSchema '(.+?)' to json and save it in variable '(.+?)'")
public void convertJSONSchemaToJSON(String jsonSchema, String envVar) throws Exception {
"""
Convert jsonSchema to json
@param jsonSchema jsonSchema to be converted to json
@param envVar environment variable where to store json
@throws Exception exception *
"""
String json = commonspec.parseJSONSchema(new JSONObject(jsonSchema)).toString();
ThreadProperty.set(envVar, json);
} | java | @Given("^I convert jsonSchema '(.+?)' to json and save it in variable '(.+?)'")
public void convertJSONSchemaToJSON(String jsonSchema, String envVar) throws Exception {
String json = commonspec.parseJSONSchema(new JSONObject(jsonSchema)).toString();
ThreadProperty.set(envVar, json);
} | [
"@",
"Given",
"(",
"\"^I convert jsonSchema '(.+?)' to json and save it in variable '(.+?)'\"",
")",
"public",
"void",
"convertJSONSchemaToJSON",
"(",
"String",
"jsonSchema",
",",
"String",
"envVar",
")",
"throws",
"Exception",
"{",
"String",
"json",
"=",
"commonspec",
".",
"parseJSONSchema",
"(",
"new",
"JSONObject",
"(",
"jsonSchema",
")",
")",
".",
"toString",
"(",
")",
";",
"ThreadProperty",
".",
"set",
"(",
"envVar",
",",
"json",
")",
";",
"}"
] | Convert jsonSchema to json
@param jsonSchema jsonSchema to be converted to json
@param envVar environment variable where to store json
@throws Exception exception * | [
"Convert",
"jsonSchema",
"to",
"json"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L307-L311 |
structurizr/java | structurizr-core/src/com/structurizr/view/ViewSet.java | ViewSet.createDynamicView | public DynamicView createDynamicView(String key, String description) {
"""
Creates a dynamic view.
@param key the key for the view (must be unique)
@param description a description of the view
@return a DynamicView object
@throws IllegalArgumentException if the key is not unique
"""
assertThatTheViewKeyIsSpecifiedAndUnique(key);
DynamicView view = new DynamicView(model, key, description);
view.setViewSet(this);
dynamicViews.add(view);
return view;
} | java | public DynamicView createDynamicView(String key, String description) {
assertThatTheViewKeyIsSpecifiedAndUnique(key);
DynamicView view = new DynamicView(model, key, description);
view.setViewSet(this);
dynamicViews.add(view);
return view;
} | [
"public",
"DynamicView",
"createDynamicView",
"(",
"String",
"key",
",",
"String",
"description",
")",
"{",
"assertThatTheViewKeyIsSpecifiedAndUnique",
"(",
"key",
")",
";",
"DynamicView",
"view",
"=",
"new",
"DynamicView",
"(",
"model",
",",
"key",
",",
"description",
")",
";",
"view",
".",
"setViewSet",
"(",
"this",
")",
";",
"dynamicViews",
".",
"add",
"(",
"view",
")",
";",
"return",
"view",
";",
"}"
] | Creates a dynamic view.
@param key the key for the view (must be unique)
@param description a description of the view
@return a DynamicView object
@throws IllegalArgumentException if the key is not unique | [
"Creates",
"a",
"dynamic",
"view",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/view/ViewSet.java#L127-L134 |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/ErrorDetectingWrapper.java | ErrorDetectingWrapper.throwPageMigratedException | private void throwPageMigratedException(String msg, int code, int subcode, String userTitle, String userMsg) {
"""
Builds the proper exception and throws it.
@throws PageMigratedException always
"""
// This SUCKS ASS. Messages look like:
// (#21) Page ID 114267748588304 was migrated to page ID 111013272313096. Please update your API calls to the new ID
Matcher matcher = ID_PATTERN.matcher(msg);
long oldId = this.extractNextId(matcher, msg);
long newId = this.extractNextId(matcher, msg);
throw new PageMigratedException(msg, code, subcode, userTitle, userMsg, oldId, newId);
} | java | private void throwPageMigratedException(String msg, int code, int subcode, String userTitle, String userMsg) {
// This SUCKS ASS. Messages look like:
// (#21) Page ID 114267748588304 was migrated to page ID 111013272313096. Please update your API calls to the new ID
Matcher matcher = ID_PATTERN.matcher(msg);
long oldId = this.extractNextId(matcher, msg);
long newId = this.extractNextId(matcher, msg);
throw new PageMigratedException(msg, code, subcode, userTitle, userMsg, oldId, newId);
} | [
"private",
"void",
"throwPageMigratedException",
"(",
"String",
"msg",
",",
"int",
"code",
",",
"int",
"subcode",
",",
"String",
"userTitle",
",",
"String",
"userMsg",
")",
"{",
"// This SUCKS ASS. Messages look like:\r",
"// (#21) Page ID 114267748588304 was migrated to page ID 111013272313096. Please update your API calls to the new ID\r",
"Matcher",
"matcher",
"=",
"ID_PATTERN",
".",
"matcher",
"(",
"msg",
")",
";",
"long",
"oldId",
"=",
"this",
".",
"extractNextId",
"(",
"matcher",
",",
"msg",
")",
";",
"long",
"newId",
"=",
"this",
".",
"extractNextId",
"(",
"matcher",
",",
"msg",
")",
";",
"throw",
"new",
"PageMigratedException",
"(",
"msg",
",",
"code",
",",
"subcode",
",",
"userTitle",
",",
"userMsg",
",",
"oldId",
",",
"newId",
")",
";",
"}"
] | Builds the proper exception and throws it.
@throws PageMigratedException always | [
"Builds",
"the",
"proper",
"exception",
"and",
"throws",
"it",
"."
] | train | https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/impl/ErrorDetectingWrapper.java#L138-L148 |
nextreports/nextreports-server | src/ro/nextreports/server/util/StringUtil.java | StringUtil.getLastCharacters | public static String getLastCharacters(String s, int last) {
"""
Get last characters from a string : if fewer characters, the string will start with ...
@param s string
@param last last characters
@return a string with last characters
"""
int index = s.length() - last + 1;
if (index < 0) {
index = 0;
}
String result = "";
if (index > 0) {
result = " ... ";
}
result = result + s.substring(index);
return result;
} | java | public static String getLastCharacters(String s, int last) {
int index = s.length() - last + 1;
if (index < 0) {
index = 0;
}
String result = "";
if (index > 0) {
result = " ... ";
}
result = result + s.substring(index);
return result;
} | [
"public",
"static",
"String",
"getLastCharacters",
"(",
"String",
"s",
",",
"int",
"last",
")",
"{",
"int",
"index",
"=",
"s",
".",
"length",
"(",
")",
"-",
"last",
"+",
"1",
";",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"index",
"=",
"0",
";",
"}",
"String",
"result",
"=",
"\"\"",
";",
"if",
"(",
"index",
">",
"0",
")",
"{",
"result",
"=",
"\" ... \"",
";",
"}",
"result",
"=",
"result",
"+",
"s",
".",
"substring",
"(",
"index",
")",
";",
"return",
"result",
";",
"}"
] | Get last characters from a string : if fewer characters, the string will start with ...
@param s string
@param last last characters
@return a string with last characters | [
"Get",
"last",
"characters",
"from",
"a",
"string",
":",
"if",
"fewer",
"characters",
"the",
"string",
"will",
"start",
"with",
"..."
] | train | https://github.com/nextreports/nextreports-server/blob/cfce12f5c6d52cb6a739388d50142c6e2e07c55e/src/ro/nextreports/server/util/StringUtil.java#L72-L83 |
moleculer-java/moleculer-java | src/main/java/services/moleculer/ServiceBroker.java | ServiceBroker.createService | public ServiceBroker createService(String name, Service service) {
"""
Installs a new service with the specified name (eg. "user" service) and
notifies other nodes about the actions/listeners of this new service.
@param name
custom service name (eg. "user", "logger", "configurator",
etc.)
@param service
the new service instance
@return this ServiceBroker instance (from "method chaining")
"""
if (serviceRegistry == null) {
// Start service later
services.put(name, service);
} else {
// Register and start service now
eventbus.addListeners(name, service);
serviceRegistry.addActions(name, service);
}
return this;
} | java | public ServiceBroker createService(String name, Service service) {
if (serviceRegistry == null) {
// Start service later
services.put(name, service);
} else {
// Register and start service now
eventbus.addListeners(name, service);
serviceRegistry.addActions(name, service);
}
return this;
} | [
"public",
"ServiceBroker",
"createService",
"(",
"String",
"name",
",",
"Service",
"service",
")",
"{",
"if",
"(",
"serviceRegistry",
"==",
"null",
")",
"{",
"// Start service later",
"services",
".",
"put",
"(",
"name",
",",
"service",
")",
";",
"}",
"else",
"{",
"// Register and start service now",
"eventbus",
".",
"addListeners",
"(",
"name",
",",
"service",
")",
";",
"serviceRegistry",
".",
"addActions",
"(",
"name",
",",
"service",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Installs a new service with the specified name (eg. "user" service) and
notifies other nodes about the actions/listeners of this new service.
@param name
custom service name (eg. "user", "logger", "configurator",
etc.)
@param service
the new service instance
@return this ServiceBroker instance (from "method chaining") | [
"Installs",
"a",
"new",
"service",
"with",
"the",
"specified",
"name",
"(",
"eg",
".",
"user",
"service",
")",
"and",
"notifies",
"other",
"nodes",
"about",
"the",
"actions",
"/",
"listeners",
"of",
"this",
"new",
"service",
"."
] | train | https://github.com/moleculer-java/moleculer-java/blob/27575c44b9ecacc17c4456ceacf5d1851abf1cc4/src/main/java/services/moleculer/ServiceBroker.java#L612-L624 |
joniles/mpxj | src/main/java/net/sf/mpxj/sample/MppDump.java | MppDump.asciidump | private static long asciidump(InputStream is, PrintWriter pw) throws Exception {
"""
This method dumps the entire contents of a file to an output
print writer as ascii data.
@param is Input Stream
@param pw Output PrintWriter
@return number of bytes read
@throws Exception Thrown on file read errors
"""
byte[] buffer = new byte[BUFFER_SIZE];
long byteCount = 0;
char c;
int loop;
int count;
StringBuilder sb = new StringBuilder();
while (true)
{
count = is.read(buffer);
if (count == -1)
{
break;
}
byteCount += count;
sb.setLength(0);
for (loop = 0; loop < count; loop++)
{
c = (char) buffer[loop];
if (c > 200 || c < 27)
{
c = ' ';
}
sb.append(c);
}
pw.print(sb.toString());
}
return (byteCount);
} | java | private static long asciidump(InputStream is, PrintWriter pw) throws Exception
{
byte[] buffer = new byte[BUFFER_SIZE];
long byteCount = 0;
char c;
int loop;
int count;
StringBuilder sb = new StringBuilder();
while (true)
{
count = is.read(buffer);
if (count == -1)
{
break;
}
byteCount += count;
sb.setLength(0);
for (loop = 0; loop < count; loop++)
{
c = (char) buffer[loop];
if (c > 200 || c < 27)
{
c = ' ';
}
sb.append(c);
}
pw.print(sb.toString());
}
return (byteCount);
} | [
"private",
"static",
"long",
"asciidump",
"(",
"InputStream",
"is",
",",
"PrintWriter",
"pw",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"BUFFER_SIZE",
"]",
";",
"long",
"byteCount",
"=",
"0",
";",
"char",
"c",
";",
"int",
"loop",
";",
"int",
"count",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"count",
"=",
"is",
".",
"read",
"(",
"buffer",
")",
";",
"if",
"(",
"count",
"==",
"-",
"1",
")",
"{",
"break",
";",
"}",
"byteCount",
"+=",
"count",
";",
"sb",
".",
"setLength",
"(",
"0",
")",
";",
"for",
"(",
"loop",
"=",
"0",
";",
"loop",
"<",
"count",
";",
"loop",
"++",
")",
"{",
"c",
"=",
"(",
"char",
")",
"buffer",
"[",
"loop",
"]",
";",
"if",
"(",
"c",
">",
"200",
"||",
"c",
"<",
"27",
")",
"{",
"c",
"=",
"'",
"'",
";",
"}",
"sb",
".",
"append",
"(",
"c",
")",
";",
"}",
"pw",
".",
"print",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"(",
"byteCount",
")",
";",
"}"
] | This method dumps the entire contents of a file to an output
print writer as ascii data.
@param is Input Stream
@param pw Output PrintWriter
@return number of bytes read
@throws Exception Thrown on file read errors | [
"This",
"method",
"dumps",
"the",
"entire",
"contents",
"of",
"a",
"file",
"to",
"an",
"output",
"print",
"writer",
"as",
"ascii",
"data",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sample/MppDump.java#L233-L269 |
wigforss/Ka-Commons-Reflection | src/main/java/org/kasource/commons/reflection/util/MethodUtils.java | MethodUtils.findAnnotatedMethods | public static Map<Class<? extends Annotation>, Set<Method>> findAnnotatedMethods(Class<?> clazz, MethodFilter methodFilter, Collection<Class<? extends Annotation>> annotations) {
"""
Returns a map of methods annotated with an annotation from the annotations parameter.
@param methodFilter Filter for methods, may be null to include all annotated methods.
@param annotations Method annotations to find methods for
@return Methods that is annotated with the supplied annotation set.
"""
Map<Class<? extends Annotation>, Set<Method>> annotatedMethods = new HashMap<Class<? extends Annotation>, Set<Method>>();
for (Class<? extends Annotation> annotation : annotations) {
MethodFilter annotationFilter = new MethodFilterBuilder().annotated(annotation).build();
if(methodFilter != null) {
annotationFilter = new MethodFilterList(annotationFilter, methodFilter);
}
Set<Method> methods = getMethods(clazz, annotationFilter);
annotatedMethods.put(annotation, methods);
}
return annotatedMethods;
} | java | public static Map<Class<? extends Annotation>, Set<Method>> findAnnotatedMethods(Class<?> clazz, MethodFilter methodFilter, Collection<Class<? extends Annotation>> annotations) {
Map<Class<? extends Annotation>, Set<Method>> annotatedMethods = new HashMap<Class<? extends Annotation>, Set<Method>>();
for (Class<? extends Annotation> annotation : annotations) {
MethodFilter annotationFilter = new MethodFilterBuilder().annotated(annotation).build();
if(methodFilter != null) {
annotationFilter = new MethodFilterList(annotationFilter, methodFilter);
}
Set<Method> methods = getMethods(clazz, annotationFilter);
annotatedMethods.put(annotation, methods);
}
return annotatedMethods;
} | [
"public",
"static",
"Map",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Set",
"<",
"Method",
">",
">",
"findAnnotatedMethods",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"MethodFilter",
"methodFilter",
",",
"Collection",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
">",
"annotations",
")",
"{",
"Map",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Set",
"<",
"Method",
">",
">",
"annotatedMethods",
"=",
"new",
"HashMap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Set",
"<",
"Method",
">",
">",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
":",
"annotations",
")",
"{",
"MethodFilter",
"annotationFilter",
"=",
"new",
"MethodFilterBuilder",
"(",
")",
".",
"annotated",
"(",
"annotation",
")",
".",
"build",
"(",
")",
";",
"if",
"(",
"methodFilter",
"!=",
"null",
")",
"{",
"annotationFilter",
"=",
"new",
"MethodFilterList",
"(",
"annotationFilter",
",",
"methodFilter",
")",
";",
"}",
"Set",
"<",
"Method",
">",
"methods",
"=",
"getMethods",
"(",
"clazz",
",",
"annotationFilter",
")",
";",
"annotatedMethods",
".",
"put",
"(",
"annotation",
",",
"methods",
")",
";",
"}",
"return",
"annotatedMethods",
";",
"}"
] | Returns a map of methods annotated with an annotation from the annotations parameter.
@param methodFilter Filter for methods, may be null to include all annotated methods.
@param annotations Method annotations to find methods for
@return Methods that is annotated with the supplied annotation set. | [
"Returns",
"a",
"map",
"of",
"methods",
"annotated",
"with",
"an",
"annotation",
"from",
"the",
"annotations",
"parameter",
"."
] | train | https://github.com/wigforss/Ka-Commons-Reflection/blob/a80f7a164cd800089e4f4dd948ca6f0e7badcf33/src/main/java/org/kasource/commons/reflection/util/MethodUtils.java#L146-L159 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcSessionFactory.java | CmsUgcSessionFactory.createSession | public CmsUgcSession createSession(CmsObject cms, HttpServletRequest request, String sitePath)
throws CmsUgcException {
"""
Creates a new editing session.<p>
@param cms the cms context
@param request the request
@param sitePath the configuration site path
@return the form session
@throws CmsUgcException if creating the session fails
"""
CmsUgcConfigurationReader reader = new CmsUgcConfigurationReader(cms);
CmsUgcConfiguration config = null;
try {
CmsFile configFile = cms.readFile(sitePath);
config = reader.readConfiguration(configFile);
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errConfiguration, e.getLocalizedMessage());
}
return createSession(cms, request, config);
} | java | public CmsUgcSession createSession(CmsObject cms, HttpServletRequest request, String sitePath)
throws CmsUgcException {
CmsUgcConfigurationReader reader = new CmsUgcConfigurationReader(cms);
CmsUgcConfiguration config = null;
try {
CmsFile configFile = cms.readFile(sitePath);
config = reader.readConfiguration(configFile);
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errConfiguration, e.getLocalizedMessage());
}
return createSession(cms, request, config);
} | [
"public",
"CmsUgcSession",
"createSession",
"(",
"CmsObject",
"cms",
",",
"HttpServletRequest",
"request",
",",
"String",
"sitePath",
")",
"throws",
"CmsUgcException",
"{",
"CmsUgcConfigurationReader",
"reader",
"=",
"new",
"CmsUgcConfigurationReader",
"(",
"cms",
")",
";",
"CmsUgcConfiguration",
"config",
"=",
"null",
";",
"try",
"{",
"CmsFile",
"configFile",
"=",
"cms",
".",
"readFile",
"(",
"sitePath",
")",
";",
"config",
"=",
"reader",
".",
"readConfiguration",
"(",
"configFile",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getLocalizedMessage",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"CmsUgcException",
"(",
"e",
",",
"CmsUgcConstants",
".",
"ErrorCode",
".",
"errConfiguration",
",",
"e",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"}",
"return",
"createSession",
"(",
"cms",
",",
"request",
",",
"config",
")",
";",
"}"
] | Creates a new editing session.<p>
@param cms the cms context
@param request the request
@param sitePath the configuration site path
@return the form session
@throws CmsUgcException if creating the session fails | [
"Creates",
"a",
"new",
"editing",
"session",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSessionFactory.java#L123-L136 |
OpenLiberty/open-liberty | dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONSAXHandler.java | JSONSAXHandler.startElement | public void startElement(String namespaceURI, String localName, String qName, Attributes attrs)
throws SAXException {
"""
This function parses an IFix top level element and all its children.
"""
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "startElement(String,String,String,org.xml.sax.Attributes)");
Properties props = new Properties();
int attrLength = attrs.getLength();
for (int i = 0; i < attrLength; i++)
{
props.put(attrs.getQName(i), attrs.getValue(i));
}
JSONObject obj = new JSONObject(localName, props);
if (this.head == null)
{
this.head = obj;
this.current = head;
}
else
{
if (current != null)
{
this.previousObjects.push(current);
this.current.addJSONObject(obj);
}
this.current = obj;
}
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "startElement(String,String,String,org.xml.sax.Attributes)");
} | java | public void startElement(String namespaceURI, String localName, String qName, Attributes attrs)
throws SAXException
{
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "startElement(String,String,String,org.xml.sax.Attributes)");
Properties props = new Properties();
int attrLength = attrs.getLength();
for (int i = 0; i < attrLength; i++)
{
props.put(attrs.getQName(i), attrs.getValue(i));
}
JSONObject obj = new JSONObject(localName, props);
if (this.head == null)
{
this.head = obj;
this.current = head;
}
else
{
if (current != null)
{
this.previousObjects.push(current);
this.current.addJSONObject(obj);
}
this.current = obj;
}
if (logger.isLoggable(Level.FINER)) logger.exiting(className, "startElement(String,String,String,org.xml.sax.Attributes)");
} | [
"public",
"void",
"startElement",
"(",
"String",
"namespaceURI",
",",
"String",
"localName",
",",
"String",
"qName",
",",
"Attributes",
"attrs",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINER",
")",
")",
"logger",
".",
"exiting",
"(",
"className",
",",
"\"startElement(String,String,String,org.xml.sax.Attributes)\"",
")",
";",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"int",
"attrLength",
"=",
"attrs",
".",
"getLength",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attrLength",
";",
"i",
"++",
")",
"{",
"props",
".",
"put",
"(",
"attrs",
".",
"getQName",
"(",
"i",
")",
",",
"attrs",
".",
"getValue",
"(",
"i",
")",
")",
";",
"}",
"JSONObject",
"obj",
"=",
"new",
"JSONObject",
"(",
"localName",
",",
"props",
")",
";",
"if",
"(",
"this",
".",
"head",
"==",
"null",
")",
"{",
"this",
".",
"head",
"=",
"obj",
";",
"this",
".",
"current",
"=",
"head",
";",
"}",
"else",
"{",
"if",
"(",
"current",
"!=",
"null",
")",
"{",
"this",
".",
"previousObjects",
".",
"push",
"(",
"current",
")",
";",
"this",
".",
"current",
".",
"addJSONObject",
"(",
"obj",
")",
";",
"}",
"this",
".",
"current",
"=",
"obj",
";",
"}",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINER",
")",
")",
"logger",
".",
"exiting",
"(",
"className",
",",
"\"startElement(String,String,String,org.xml.sax.Attributes)\"",
")",
";",
"}"
] | This function parses an IFix top level element and all its children. | [
"This",
"function",
"parses",
"an",
"IFix",
"top",
"level",
"element",
"and",
"all",
"its",
"children",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONSAXHandler.java#L100-L129 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.callMethod | public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) {
"""
Calls a method on a remote object.
@param objRef The remote object reference.
@param method The name of the method.
@param args Method arguments.
@return The return value of the method.
"""
ObjectNode req = makeRequest("invoke", objRef);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | java | public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) {
ObjectNode req = makeRequest("invoke", objRef);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | [
"public",
"JsonNode",
"callMethod",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"String",
"method",
",",
"final",
"ArrayNode",
"args",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"invoke\"",
",",
"objRef",
")",
";",
"req",
".",
"put",
"(",
"\"method\"",
",",
"method",
")",
";",
"req",
".",
"set",
"(",
"\"args\"",
",",
"args",
")",
";",
"JsonNode",
"resp",
"=",
"this",
".",
"runtime",
".",
"requestResponse",
"(",
"req",
")",
";",
"return",
"resp",
".",
"get",
"(",
"\"result\"",
")",
";",
"}"
] | Calls a method on a remote object.
@param objRef The remote object reference.
@param method The name of the method.
@param args Method arguments.
@return The return value of the method. | [
"Calls",
"a",
"method",
"on",
"a",
"remote",
"object",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L180-L187 |
openengsb/openengsb | components/weaver/service/src/main/java/org/openengsb/core/weaver/service/internal/model/JavassistUtils.java | JavassistUtils.hasAnnotation | public static boolean hasAnnotation(CtField field, String annotationName) {
"""
Returns true if the given field has an annotation set with the given name, returns false otherwise.
"""
FieldInfo info = field.getFieldInfo();
AnnotationsAttribute ainfo = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.invisibleTag);
AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.visibleTag);
return checkAnnotation(ainfo, ainfo2, annotationName);
} | java | public static boolean hasAnnotation(CtField field, String annotationName) {
FieldInfo info = field.getFieldInfo();
AnnotationsAttribute ainfo = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.invisibleTag);
AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.visibleTag);
return checkAnnotation(ainfo, ainfo2, annotationName);
} | [
"public",
"static",
"boolean",
"hasAnnotation",
"(",
"CtField",
"field",
",",
"String",
"annotationName",
")",
"{",
"FieldInfo",
"info",
"=",
"field",
".",
"getFieldInfo",
"(",
")",
";",
"AnnotationsAttribute",
"ainfo",
"=",
"(",
"AnnotationsAttribute",
")",
"info",
".",
"getAttribute",
"(",
"AnnotationsAttribute",
".",
"invisibleTag",
")",
";",
"AnnotationsAttribute",
"ainfo2",
"=",
"(",
"AnnotationsAttribute",
")",
"info",
".",
"getAttribute",
"(",
"AnnotationsAttribute",
".",
"visibleTag",
")",
";",
"return",
"checkAnnotation",
"(",
"ainfo",
",",
"ainfo2",
",",
"annotationName",
")",
";",
"}"
] | Returns true if the given field has an annotation set with the given name, returns false otherwise. | [
"Returns",
"true",
"if",
"the",
"given",
"field",
"has",
"an",
"annotation",
"set",
"with",
"the",
"given",
"name",
"returns",
"false",
"otherwise",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/weaver/service/src/main/java/org/openengsb/core/weaver/service/internal/model/JavassistUtils.java#L49-L56 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/MapTask.java | MapTask.updateJobWithSplit | private void updateJobWithSplit(final JobConf job, InputSplit inputSplit) {
"""
Update the job with details about the file split
@param job the job configuration to update
@param inputSplit the file split
"""
if (inputSplit instanceof FileSplit) {
FileSplit fileSplit = (FileSplit) inputSplit;
job.set("map.input.file", fileSplit.getPath().toString());
job.setLong("map.input.start", fileSplit.getStart());
job.setLong("map.input.length", fileSplit.getLength());
}
LOG.info("split: " + inputSplit.toString());
} | java | private void updateJobWithSplit(final JobConf job, InputSplit inputSplit) {
if (inputSplit instanceof FileSplit) {
FileSplit fileSplit = (FileSplit) inputSplit;
job.set("map.input.file", fileSplit.getPath().toString());
job.setLong("map.input.start", fileSplit.getStart());
job.setLong("map.input.length", fileSplit.getLength());
}
LOG.info("split: " + inputSplit.toString());
} | [
"private",
"void",
"updateJobWithSplit",
"(",
"final",
"JobConf",
"job",
",",
"InputSplit",
"inputSplit",
")",
"{",
"if",
"(",
"inputSplit",
"instanceof",
"FileSplit",
")",
"{",
"FileSplit",
"fileSplit",
"=",
"(",
"FileSplit",
")",
"inputSplit",
";",
"job",
".",
"set",
"(",
"\"map.input.file\"",
",",
"fileSplit",
".",
"getPath",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"job",
".",
"setLong",
"(",
"\"map.input.start\"",
",",
"fileSplit",
".",
"getStart",
"(",
")",
")",
";",
"job",
".",
"setLong",
"(",
"\"map.input.length\"",
",",
"fileSplit",
".",
"getLength",
"(",
")",
")",
";",
"}",
"LOG",
".",
"info",
"(",
"\"split: \"",
"+",
"inputSplit",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Update the job with details about the file split
@param job the job configuration to update
@param inputSplit the file split | [
"Update",
"the",
"job",
"with",
"details",
"about",
"the",
"file",
"split"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/MapTask.java#L383-L391 |
BioPAX/Paxtools | paxtools-core/src/main/java/org/biopax/paxtools/controller/AbstractPropertyEditor.java | AbstractPropertyEditor.checkRestrictions | protected void checkRestrictions(R value, D bean) {
"""
Checks if the <em>bean</em> and the <em>value</em> are consistent with the cardinality rules of
the model. This method is important for validations.
@param value Value that is related to the object
@param bean Object that is related to the value
"""
Integer max = this.maxCardinalities.get(value.getClass());
if (max != null)
{
if (max == 0)
{
throw new IllegalBioPAXArgumentException("Cardinality 0 restriction violated");
} else
{
assert multipleCardinality;
Set values = this.getValueFromBean(bean);
if (values.size() >= max)
{
throw new IllegalBioPAXArgumentException("Cardinality " + max + " restriction violated");
}
}
}
} | java | protected void checkRestrictions(R value, D bean)
{
Integer max = this.maxCardinalities.get(value.getClass());
if (max != null)
{
if (max == 0)
{
throw new IllegalBioPAXArgumentException("Cardinality 0 restriction violated");
} else
{
assert multipleCardinality;
Set values = this.getValueFromBean(bean);
if (values.size() >= max)
{
throw new IllegalBioPAXArgumentException("Cardinality " + max + " restriction violated");
}
}
}
} | [
"protected",
"void",
"checkRestrictions",
"(",
"R",
"value",
",",
"D",
"bean",
")",
"{",
"Integer",
"max",
"=",
"this",
".",
"maxCardinalities",
".",
"get",
"(",
"value",
".",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"max",
"!=",
"null",
")",
"{",
"if",
"(",
"max",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalBioPAXArgumentException",
"(",
"\"Cardinality 0 restriction violated\"",
")",
";",
"}",
"else",
"{",
"assert",
"multipleCardinality",
";",
"Set",
"values",
"=",
"this",
".",
"getValueFromBean",
"(",
"bean",
")",
";",
"if",
"(",
"values",
".",
"size",
"(",
")",
">=",
"max",
")",
"{",
"throw",
"new",
"IllegalBioPAXArgumentException",
"(",
"\"Cardinality \"",
"+",
"max",
"+",
"\" restriction violated\"",
")",
";",
"}",
"}",
"}",
"}"
] | Checks if the <em>bean</em> and the <em>value</em> are consistent with the cardinality rules of
the model. This method is important for validations.
@param value Value that is related to the object
@param bean Object that is related to the value | [
"Checks",
"if",
"the",
"<em",
">",
"bean<",
"/",
"em",
">",
"and",
"the",
"<em",
">",
"value<",
"/",
"em",
">",
"are",
"consistent",
"with",
"the",
"cardinality",
"rules",
"of",
"the",
"model",
".",
"This",
"method",
"is",
"important",
"for",
"validations",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-core/src/main/java/org/biopax/paxtools/controller/AbstractPropertyEditor.java#L479-L497 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/expressions/Expressions.java | Expressions.isEqual | public static IsEqual isEqual(ComparableExpression<Number> left, Number constant) {
"""
Creates an IsEqual expression from the given expression and constant.
@param left The left expression.
@param constant The constant to compare to.
@return A new IsEqual binary expression.
"""
return new IsEqual(left, constant(constant));
} | java | public static IsEqual isEqual(ComparableExpression<Number> left, Number constant) {
return new IsEqual(left, constant(constant));
} | [
"public",
"static",
"IsEqual",
"isEqual",
"(",
"ComparableExpression",
"<",
"Number",
">",
"left",
",",
"Number",
"constant",
")",
"{",
"return",
"new",
"IsEqual",
"(",
"left",
",",
"constant",
"(",
"constant",
")",
")",
";",
"}"
] | Creates an IsEqual expression from the given expression and constant.
@param left The left expression.
@param constant The constant to compare to.
@return A new IsEqual binary expression. | [
"Creates",
"an",
"IsEqual",
"expression",
"from",
"the",
"given",
"expression",
"and",
"constant",
"."
] | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/expressions/Expressions.java#L148-L150 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-js/src/main/java/im/actor/core/js/modules/JsFilesModule.java | JsFilesModule.getFileUrl | public String getFileUrl(long id, long accessHash) {
"""
Getting URL for file if available
@param id file's id
@param accessHash file's accessHash
@return url for a file or null if not yet available
"""
CachedFileUrl cachedFileUrl = keyValueStorage.getValue(id);
if (cachedFileUrl != null) {
long urlTime = cachedFileUrl.getTimeout();
long currentTime = im.actor.runtime.Runtime.getCurrentSyncedTime();
if (urlTime <= currentTime) {
Log.w("JsFilesModule", "URL #" + id + " timeout (urlTime: " + urlTime + ", current:" + currentTime + ")");
keyValueStorage.removeItem(id);
} else {
return cachedFileUrl.getUrl();
}
}
if (!requestedFiles.contains(id)) {
requestedFiles.add(id);
urlLoader.send(new FileRequest(id, accessHash));
}
return null;
} | java | public String getFileUrl(long id, long accessHash) {
CachedFileUrl cachedFileUrl = keyValueStorage.getValue(id);
if (cachedFileUrl != null) {
long urlTime = cachedFileUrl.getTimeout();
long currentTime = im.actor.runtime.Runtime.getCurrentSyncedTime();
if (urlTime <= currentTime) {
Log.w("JsFilesModule", "URL #" + id + " timeout (urlTime: " + urlTime + ", current:" + currentTime + ")");
keyValueStorage.removeItem(id);
} else {
return cachedFileUrl.getUrl();
}
}
if (!requestedFiles.contains(id)) {
requestedFiles.add(id);
urlLoader.send(new FileRequest(id, accessHash));
}
return null;
} | [
"public",
"String",
"getFileUrl",
"(",
"long",
"id",
",",
"long",
"accessHash",
")",
"{",
"CachedFileUrl",
"cachedFileUrl",
"=",
"keyValueStorage",
".",
"getValue",
"(",
"id",
")",
";",
"if",
"(",
"cachedFileUrl",
"!=",
"null",
")",
"{",
"long",
"urlTime",
"=",
"cachedFileUrl",
".",
"getTimeout",
"(",
")",
";",
"long",
"currentTime",
"=",
"im",
".",
"actor",
".",
"runtime",
".",
"Runtime",
".",
"getCurrentSyncedTime",
"(",
")",
";",
"if",
"(",
"urlTime",
"<=",
"currentTime",
")",
"{",
"Log",
".",
"w",
"(",
"\"JsFilesModule\"",
",",
"\"URL #\"",
"+",
"id",
"+",
"\" timeout (urlTime: \"",
"+",
"urlTime",
"+",
"\", current:\"",
"+",
"currentTime",
"+",
"\")\"",
")",
";",
"keyValueStorage",
".",
"removeItem",
"(",
"id",
")",
";",
"}",
"else",
"{",
"return",
"cachedFileUrl",
".",
"getUrl",
"(",
")",
";",
"}",
"}",
"if",
"(",
"!",
"requestedFiles",
".",
"contains",
"(",
"id",
")",
")",
"{",
"requestedFiles",
".",
"add",
"(",
"id",
")",
";",
"urlLoader",
".",
"send",
"(",
"new",
"FileRequest",
"(",
"id",
",",
"accessHash",
")",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Getting URL for file if available
@param id file's id
@param accessHash file's accessHash
@return url for a file or null if not yet available | [
"Getting",
"URL",
"for",
"file",
"if",
"available"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-js/src/main/java/im/actor/core/js/modules/JsFilesModule.java#L93-L112 |
amsa-code/risky | ais/src/main/java/au/gov/amsa/ais/AisExtractor.java | AisExtractor.getValue | public synchronized int getValue(int from, int to) {
"""
Returns an unsigned integer value using the bits from character position
start to position stop in the decoded message.
@param from
@param to
@return
"""
try {
// is synchronized so that values of bitSet and calculated can be
// lazily
// calculated and safely published (thread safe).
SixBit.convertSixBitToBits(message, padBits, bitSet, calculated, from, to);
return (int) SixBit.getValue(from, to, bitSet);
} catch (SixBitException | ArrayIndexOutOfBoundsException e) {
throw new AisParseException(e);
}
} | java | public synchronized int getValue(int from, int to) {
try {
// is synchronized so that values of bitSet and calculated can be
// lazily
// calculated and safely published (thread safe).
SixBit.convertSixBitToBits(message, padBits, bitSet, calculated, from, to);
return (int) SixBit.getValue(from, to, bitSet);
} catch (SixBitException | ArrayIndexOutOfBoundsException e) {
throw new AisParseException(e);
}
} | [
"public",
"synchronized",
"int",
"getValue",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"try",
"{",
"// is synchronized so that values of bitSet and calculated can be",
"// lazily",
"// calculated and safely published (thread safe).",
"SixBit",
".",
"convertSixBitToBits",
"(",
"message",
",",
"padBits",
",",
"bitSet",
",",
"calculated",
",",
"from",
",",
"to",
")",
";",
"return",
"(",
"int",
")",
"SixBit",
".",
"getValue",
"(",
"from",
",",
"to",
",",
"bitSet",
")",
";",
"}",
"catch",
"(",
"SixBitException",
"|",
"ArrayIndexOutOfBoundsException",
"e",
")",
"{",
"throw",
"new",
"AisParseException",
"(",
"e",
")",
";",
"}",
"}"
] | Returns an unsigned integer value using the bits from character position
start to position stop in the decoded message.
@param from
@param to
@return | [
"Returns",
"an",
"unsigned",
"integer",
"value",
"using",
"the",
"bits",
"from",
"character",
"position",
"start",
"to",
"position",
"stop",
"in",
"the",
"decoded",
"message",
"."
] | train | https://github.com/amsa-code/risky/blob/13649942aeddfdb9210eec072c605bc5d7a6daf3/ais/src/main/java/au/gov/amsa/ais/AisExtractor.java#L62-L72 |
VoltDB/voltdb | src/frontend/org/voltdb/InProcessVoltDBServer.java | InProcessVoltDBServer.loadRow | public void loadRow(String tableName, Object... row) throws Exception {
"""
Helper method for loading a row into a table.
Must be called after {@link #start()} and after {@link #runDDLFromPath(String)} or {@link #runDDLFromString(String)}.
@param tableName The case-insensitive name of the target table.
@param row An array of schema-compatible values comprising the row to load.
@throws Exception if the server is unable to complete a transaction of if the input doesn't match table schema.
"""
if (loaderClient == null) {
loaderClient = getClient();
}
String procName = tableName.trim().toUpperCase() + ".insert";
loaderClient.callProcedure(procName, row);
} | java | public void loadRow(String tableName, Object... row) throws Exception {
if (loaderClient == null) {
loaderClient = getClient();
}
String procName = tableName.trim().toUpperCase() + ".insert";
loaderClient.callProcedure(procName, row);
} | [
"public",
"void",
"loadRow",
"(",
"String",
"tableName",
",",
"Object",
"...",
"row",
")",
"throws",
"Exception",
"{",
"if",
"(",
"loaderClient",
"==",
"null",
")",
"{",
"loaderClient",
"=",
"getClient",
"(",
")",
";",
"}",
"String",
"procName",
"=",
"tableName",
".",
"trim",
"(",
")",
".",
"toUpperCase",
"(",
")",
"+",
"\".insert\"",
";",
"loaderClient",
".",
"callProcedure",
"(",
"procName",
",",
"row",
")",
";",
"}"
] | Helper method for loading a row into a table.
Must be called after {@link #start()} and after {@link #runDDLFromPath(String)} or {@link #runDDLFromString(String)}.
@param tableName The case-insensitive name of the target table.
@param row An array of schema-compatible values comprising the row to load.
@throws Exception if the server is unable to complete a transaction of if the input doesn't match table schema. | [
"Helper",
"method",
"for",
"loading",
"a",
"row",
"into",
"a",
"table",
".",
"Must",
"be",
"called",
"after",
"{"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/InProcessVoltDBServer.java#L199-L205 |
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.checkDebug | private Environment checkDebug(Stmt.Debug stmt, Environment environment, EnclosingScope scope) {
"""
Type check an assume statement. This requires checking that the expression
being printed is well-formed and has string type.
@param stmt
Statement to type check
@param environment
Determines the type of all variables immediately going into this
block
@return
"""
// FIXME: want to refine integer type here
Type std_ascii = new Type.Array(Type.Int);
SemanticType type = checkExpression(stmt.getOperand(), environment);
checkIsSubtype(std_ascii, type, environment, stmt.getOperand());
return environment;
} | java | private Environment checkDebug(Stmt.Debug stmt, Environment environment, EnclosingScope scope) {
// FIXME: want to refine integer type here
Type std_ascii = new Type.Array(Type.Int);
SemanticType type = checkExpression(stmt.getOperand(), environment);
checkIsSubtype(std_ascii, type, environment, stmt.getOperand());
return environment;
} | [
"private",
"Environment",
"checkDebug",
"(",
"Stmt",
".",
"Debug",
"stmt",
",",
"Environment",
"environment",
",",
"EnclosingScope",
"scope",
")",
"{",
"// FIXME: want to refine integer type here",
"Type",
"std_ascii",
"=",
"new",
"Type",
".",
"Array",
"(",
"Type",
".",
"Int",
")",
";",
"SemanticType",
"type",
"=",
"checkExpression",
"(",
"stmt",
".",
"getOperand",
"(",
")",
",",
"environment",
")",
";",
"checkIsSubtype",
"(",
"std_ascii",
",",
"type",
",",
"environment",
",",
"stmt",
".",
"getOperand",
"(",
")",
")",
";",
"return",
"environment",
";",
"}"
] | Type check an assume statement. This requires checking that the expression
being printed is well-formed and has string type.
@param stmt
Statement to type check
@param environment
Determines the type of all variables immediately going into this
block
@return | [
"Type",
"check",
"an",
"assume",
"statement",
".",
"This",
"requires",
"checking",
"that",
"the",
"expression",
"being",
"printed",
"is",
"well",
"-",
"formed",
"and",
"has",
"string",
"type",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L497-L503 |
zxing/zxing | android/src/com/google/zxing/client/android/result/ResultHandler.java | ResultHandler.openProductSearch | final void openProductSearch(String upc) {
"""
Uses the mobile-specific version of Product Search, which is formatted for small screens.
"""
Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity) +
"/m/products?q=" + upc + "&source=zxing");
launchIntent(new Intent(Intent.ACTION_VIEW, uri));
} | java | final void openProductSearch(String upc) {
Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity) +
"/m/products?q=" + upc + "&source=zxing");
launchIntent(new Intent(Intent.ACTION_VIEW, uri));
} | [
"final",
"void",
"openProductSearch",
"(",
"String",
"upc",
")",
"{",
"Uri",
"uri",
"=",
"Uri",
".",
"parse",
"(",
"\"http://www.google.\"",
"+",
"LocaleManager",
".",
"getProductSearchCountryTLD",
"(",
"activity",
")",
"+",
"\"/m/products?q=\"",
"+",
"upc",
"+",
"\"&source=zxing\"",
")",
";",
"launchIntent",
"(",
"new",
"Intent",
"(",
"Intent",
".",
"ACTION_VIEW",
",",
"uri",
")",
")",
";",
"}"
] | Uses the mobile-specific version of Product Search, which is formatted for small screens. | [
"Uses",
"the",
"mobile",
"-",
"specific",
"version",
"of",
"Product",
"Search",
"which",
"is",
"formatted",
"for",
"small",
"screens",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/android/src/com/google/zxing/client/android/result/ResultHandler.java#L415-L419 |
baratine/baratine | framework/src/main/java/com/caucho/v5/util/QDate.java | QDate.monthToDayOfYear | private long monthToDayOfYear(long month, boolean isLeapYear) {
"""
Calculates the day of the year for the beginning of the month.
"""
long day = 0;
for (int i = 0; i < month && i < 12; i++) {
day += DAYS_IN_MONTH[i];
if (i == 1 && isLeapYear)
day++;
}
return day;
} | java | private long monthToDayOfYear(long month, boolean isLeapYear)
{
long day = 0;
for (int i = 0; i < month && i < 12; i++) {
day += DAYS_IN_MONTH[i];
if (i == 1 && isLeapYear)
day++;
}
return day;
} | [
"private",
"long",
"monthToDayOfYear",
"(",
"long",
"month",
",",
"boolean",
"isLeapYear",
")",
"{",
"long",
"day",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"month",
"&&",
"i",
"<",
"12",
";",
"i",
"++",
")",
"{",
"day",
"+=",
"DAYS_IN_MONTH",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"==",
"1",
"&&",
"isLeapYear",
")",
"day",
"++",
";",
"}",
"return",
"day",
";",
"}"
] | Calculates the day of the year for the beginning of the month. | [
"Calculates",
"the",
"day",
"of",
"the",
"year",
"for",
"the",
"beginning",
"of",
"the",
"month",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/util/QDate.java#L1580-L1591 |
facebookarchive/hadoop-20 | src/contrib/benchmark/src/java/org/apache/hadoop/hdfs/DataGenerator.java | DataGenerator.genFiles | private void genFiles() throws IOException {
"""
Read file structure file under the input directory. Create each file
under the specified root. The file names are relative to the root.
"""
//
// BufferedReader in = new BufferedReader(new FileReader(new File(inDir,
// StructureGenerator.FILE_STRUCTURE_FILE_NAME)));
// String line;
// while ((line = in.readLine()) != null) {
// String[] tokens = line.split(" ");
// if (tokens.length != 2) {
// throw new IOException("Expect at most 2 tokens per line: "
// + line);
// }
// String fileName = root + tokens[0];
// long fileSize = (long) (BLOCK_SIZE * Double.parseDouble(tokens[1]));
// genFile(new Path(fileName), fileSize);
// }
config = new Configuration(getConf());
config.setInt("dfs.replication", 3);
config.set("dfs.rootdir", root.toString());
JobConf job = new JobConf(config, DataGenerator.class);
job.setJobName("data-genarator");
FileOutputFormat.setOutputPath(job, new Path("data-generator-result"));
// create the input for the map-reduce job
Path inputPath = new Path(ROOT + "load_input");
fs.mkdirs(inputPath);
fs.copyFromLocalFile(new Path(inDir + "/"
+ StructureGenerator.FILE_STRUCTURE_FILE_NAME), inputPath);
FileInputFormat.setInputPaths(job, new Path(ROOT + "load_input"));
job.setInputFormat(TextInputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(CreateFiles.class);
job.setNumMapTasks(nFiles/10);
job.setNumReduceTasks(0);
JobClient.runJob(job);
} | java | private void genFiles() throws IOException {
//
// BufferedReader in = new BufferedReader(new FileReader(new File(inDir,
// StructureGenerator.FILE_STRUCTURE_FILE_NAME)));
// String line;
// while ((line = in.readLine()) != null) {
// String[] tokens = line.split(" ");
// if (tokens.length != 2) {
// throw new IOException("Expect at most 2 tokens per line: "
// + line);
// }
// String fileName = root + tokens[0];
// long fileSize = (long) (BLOCK_SIZE * Double.parseDouble(tokens[1]));
// genFile(new Path(fileName), fileSize);
// }
config = new Configuration(getConf());
config.setInt("dfs.replication", 3);
config.set("dfs.rootdir", root.toString());
JobConf job = new JobConf(config, DataGenerator.class);
job.setJobName("data-genarator");
FileOutputFormat.setOutputPath(job, new Path("data-generator-result"));
// create the input for the map-reduce job
Path inputPath = new Path(ROOT + "load_input");
fs.mkdirs(inputPath);
fs.copyFromLocalFile(new Path(inDir + "/"
+ StructureGenerator.FILE_STRUCTURE_FILE_NAME), inputPath);
FileInputFormat.setInputPaths(job, new Path(ROOT + "load_input"));
job.setInputFormat(TextInputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(CreateFiles.class);
job.setNumMapTasks(nFiles/10);
job.setNumReduceTasks(0);
JobClient.runJob(job);
} | [
"private",
"void",
"genFiles",
"(",
")",
"throws",
"IOException",
"{",
"//",
"// BufferedReader in = new BufferedReader(new FileReader(new File(inDir,",
"// StructureGenerator.FILE_STRUCTURE_FILE_NAME)));",
"// String line;",
"// while ((line = in.readLine()) != null) {",
"// String[] tokens = line.split(\" \");",
"// if (tokens.length != 2) {",
"// throw new IOException(\"Expect at most 2 tokens per line: \"",
"// + line);",
"// }",
"// String fileName = root + tokens[0];",
"// long fileSize = (long) (BLOCK_SIZE * Double.parseDouble(tokens[1]));",
"// genFile(new Path(fileName), fileSize);",
"// }",
"config",
"=",
"new",
"Configuration",
"(",
"getConf",
"(",
")",
")",
";",
"config",
".",
"setInt",
"(",
"\"dfs.replication\"",
",",
"3",
")",
";",
"config",
".",
"set",
"(",
"\"dfs.rootdir\"",
",",
"root",
".",
"toString",
"(",
")",
")",
";",
"JobConf",
"job",
"=",
"new",
"JobConf",
"(",
"config",
",",
"DataGenerator",
".",
"class",
")",
";",
"job",
".",
"setJobName",
"(",
"\"data-genarator\"",
")",
";",
"FileOutputFormat",
".",
"setOutputPath",
"(",
"job",
",",
"new",
"Path",
"(",
"\"data-generator-result\"",
")",
")",
";",
"// create the input for the map-reduce job",
"Path",
"inputPath",
"=",
"new",
"Path",
"(",
"ROOT",
"+",
"\"load_input\"",
")",
";",
"fs",
".",
"mkdirs",
"(",
"inputPath",
")",
";",
"fs",
".",
"copyFromLocalFile",
"(",
"new",
"Path",
"(",
"inDir",
"+",
"\"/\"",
"+",
"StructureGenerator",
".",
"FILE_STRUCTURE_FILE_NAME",
")",
",",
"inputPath",
")",
";",
"FileInputFormat",
".",
"setInputPaths",
"(",
"job",
",",
"new",
"Path",
"(",
"ROOT",
"+",
"\"load_input\"",
")",
")",
";",
"job",
".",
"setInputFormat",
"(",
"TextInputFormat",
".",
"class",
")",
";",
"job",
".",
"setOutputKeyClass",
"(",
"Text",
".",
"class",
")",
";",
"job",
".",
"setOutputValueClass",
"(",
"Text",
".",
"class",
")",
";",
"job",
".",
"setMapperClass",
"(",
"CreateFiles",
".",
"class",
")",
";",
"job",
".",
"setNumMapTasks",
"(",
"nFiles",
"/",
"10",
")",
";",
"job",
".",
"setNumReduceTasks",
"(",
"0",
")",
";",
"JobClient",
".",
"runJob",
"(",
"job",
")",
";",
"}"
] | Read file structure file under the input directory. Create each file
under the specified root. The file names are relative to the root. | [
"Read",
"file",
"structure",
"file",
"under",
"the",
"input",
"directory",
".",
"Create",
"each",
"file",
"under",
"the",
"specified",
"root",
".",
"The",
"file",
"names",
"are",
"relative",
"to",
"the",
"root",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/benchmark/src/java/org/apache/hadoop/hdfs/DataGenerator.java#L117-L157 |
albfernandez/itext2 | src/main/java/com/lowagie/text/rtf/parser/ctrlwords/RtfCtrlWordMgr.java | RtfCtrlWordMgr.dispatchKeyword | private int dispatchKeyword(RtfCtrlWordData ctrlWordData, int groupLevel) {
"""
Dispatch the token to the correct control word handling object.
@param ctrlWordData The <code>RtfCtrlWordData</code> object with control word and param
@param groupLevel The current document group parsing level
@return errOK if ok, otherwise an error code.
"""
int result = RtfParser.errOK;
if(ctrlWordData != null) {
RtfCtrlWordHandler ctrlWord = ctrlWordMap.getCtrlWordHandler(ctrlWordData.ctrlWord);
if(ctrlWord != null) {
ctrlWord.handleControlword(ctrlWordData);
if(debug && debugFound) {
System.out.println("Keyword found:" +
" New:" + ctrlWordData.ctrlWord +
" Param:" + ctrlWordData.param +
" bParam=" + ctrlWordData.hasParam);
}
} else {
result = RtfParser.errCtrlWordNotFound;
//result = RtfParser2.errAssertion;
if(debug && debugNotFound) {
System.out.println("Keyword unknown:" +
" New:" + ctrlWordData.ctrlWord +
" Param:" + ctrlWordData.param +
" bParam=" + ctrlWordData.hasParam);
}
}
}
return result;
} | java | private int dispatchKeyword(RtfCtrlWordData ctrlWordData, int groupLevel) {
int result = RtfParser.errOK;
if(ctrlWordData != null) {
RtfCtrlWordHandler ctrlWord = ctrlWordMap.getCtrlWordHandler(ctrlWordData.ctrlWord);
if(ctrlWord != null) {
ctrlWord.handleControlword(ctrlWordData);
if(debug && debugFound) {
System.out.println("Keyword found:" +
" New:" + ctrlWordData.ctrlWord +
" Param:" + ctrlWordData.param +
" bParam=" + ctrlWordData.hasParam);
}
} else {
result = RtfParser.errCtrlWordNotFound;
//result = RtfParser2.errAssertion;
if(debug && debugNotFound) {
System.out.println("Keyword unknown:" +
" New:" + ctrlWordData.ctrlWord +
" Param:" + ctrlWordData.param +
" bParam=" + ctrlWordData.hasParam);
}
}
}
return result;
} | [
"private",
"int",
"dispatchKeyword",
"(",
"RtfCtrlWordData",
"ctrlWordData",
",",
"int",
"groupLevel",
")",
"{",
"int",
"result",
"=",
"RtfParser",
".",
"errOK",
";",
"if",
"(",
"ctrlWordData",
"!=",
"null",
")",
"{",
"RtfCtrlWordHandler",
"ctrlWord",
"=",
"ctrlWordMap",
".",
"getCtrlWordHandler",
"(",
"ctrlWordData",
".",
"ctrlWord",
")",
";",
"if",
"(",
"ctrlWord",
"!=",
"null",
")",
"{",
"ctrlWord",
".",
"handleControlword",
"(",
"ctrlWordData",
")",
";",
"if",
"(",
"debug",
"&&",
"debugFound",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Keyword found:\"",
"+",
"\" New:\"",
"+",
"ctrlWordData",
".",
"ctrlWord",
"+",
"\" Param:\"",
"+",
"ctrlWordData",
".",
"param",
"+",
"\" bParam=\"",
"+",
"ctrlWordData",
".",
"hasParam",
")",
";",
"}",
"}",
"else",
"{",
"result",
"=",
"RtfParser",
".",
"errCtrlWordNotFound",
";",
"//result = RtfParser2.errAssertion;",
"if",
"(",
"debug",
"&&",
"debugNotFound",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Keyword unknown:\"",
"+",
"\" New:\"",
"+",
"ctrlWordData",
".",
"ctrlWord",
"+",
"\" Param:\"",
"+",
"ctrlWordData",
".",
"param",
"+",
"\" bParam=\"",
"+",
"ctrlWordData",
".",
"hasParam",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Dispatch the token to the correct control word handling object.
@param ctrlWordData The <code>RtfCtrlWordData</code> object with control word and param
@param groupLevel The current document group parsing level
@return errOK if ok, otherwise an error code. | [
"Dispatch",
"the",
"token",
"to",
"the",
"correct",
"control",
"word",
"handling",
"object",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/parser/ctrlwords/RtfCtrlWordMgr.java#L132-L156 |
knightliao/apollo | src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java | DateUtils.isOverlay | public static boolean isOverlay(String date1StartStr, String date1EndStr, String date2StartStr, String date2EndStr,
String patten) {
"""
校验两段时间是否有重合
@param date1StartStr 时间段1开始
@param date1EndStr 时间段1结束
@param date2StartStr 时间段2开始
@param date2EndStr 时间段2结束
@param patten
@return <p/>
<code>true</code>:有重合
<p/>
<code>false</code>:无重合
"""
Date date1Start = DateUtils.parseDate(date1StartStr, patten);
Date date1End = DateUtils.parseDate(date1EndStr, patten);
Date date2Start = DateUtils.parseDate(date2StartStr, patten);
Date date2End = DateUtils.parseDate(date2EndStr, patten);
return isOverlay(date1Start, date1End, date2Start, date2End);
} | java | public static boolean isOverlay(String date1StartStr, String date1EndStr, String date2StartStr, String date2EndStr,
String patten) {
Date date1Start = DateUtils.parseDate(date1StartStr, patten);
Date date1End = DateUtils.parseDate(date1EndStr, patten);
Date date2Start = DateUtils.parseDate(date2StartStr, patten);
Date date2End = DateUtils.parseDate(date2EndStr, patten);
return isOverlay(date1Start, date1End, date2Start, date2End);
} | [
"public",
"static",
"boolean",
"isOverlay",
"(",
"String",
"date1StartStr",
",",
"String",
"date1EndStr",
",",
"String",
"date2StartStr",
",",
"String",
"date2EndStr",
",",
"String",
"patten",
")",
"{",
"Date",
"date1Start",
"=",
"DateUtils",
".",
"parseDate",
"(",
"date1StartStr",
",",
"patten",
")",
";",
"Date",
"date1End",
"=",
"DateUtils",
".",
"parseDate",
"(",
"date1EndStr",
",",
"patten",
")",
";",
"Date",
"date2Start",
"=",
"DateUtils",
".",
"parseDate",
"(",
"date2StartStr",
",",
"patten",
")",
";",
"Date",
"date2End",
"=",
"DateUtils",
".",
"parseDate",
"(",
"date2EndStr",
",",
"patten",
")",
";",
"return",
"isOverlay",
"(",
"date1Start",
",",
"date1End",
",",
"date2Start",
",",
"date2End",
")",
";",
"}"
] | 校验两段时间是否有重合
@param date1StartStr 时间段1开始
@param date1EndStr 时间段1结束
@param date2StartStr 时间段2开始
@param date2EndStr 时间段2结束
@param patten
@return <p/>
<code>true</code>:有重合
<p/>
<code>false</code>:无重合 | [
"校验两段时间是否有重合"
] | train | https://github.com/knightliao/apollo/blob/d7a283659fa3e67af6375db8969b2d065a8ce6eb/src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java#L1151-L1158 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java | ScreenField.setSFieldToProperty | public int setSFieldToProperty(String strSuffix, boolean bDisplayOption, int iMoveMode) {
"""
Move the HTML input to the screen record fields.
@param strSuffix Only move fields with the suffix.
@return true if one was moved.
@exception DBException File exception.
"""
int iErrorCode = Constant.NORMAL_RETURN;
if (this.isInputField())
{
String strFieldName = this.getSFieldParam(strSuffix);
String strParamValue = this.getSFieldProperty(strFieldName);
if (strParamValue != null)
iErrorCode = this.setSFieldValue(strParamValue, bDisplayOption, iMoveMode);
}
return iErrorCode;
} | java | public int setSFieldToProperty(String strSuffix, boolean bDisplayOption, int iMoveMode)
{
int iErrorCode = Constant.NORMAL_RETURN;
if (this.isInputField())
{
String strFieldName = this.getSFieldParam(strSuffix);
String strParamValue = this.getSFieldProperty(strFieldName);
if (strParamValue != null)
iErrorCode = this.setSFieldValue(strParamValue, bDisplayOption, iMoveMode);
}
return iErrorCode;
} | [
"public",
"int",
"setSFieldToProperty",
"(",
"String",
"strSuffix",
",",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"{",
"int",
"iErrorCode",
"=",
"Constant",
".",
"NORMAL_RETURN",
";",
"if",
"(",
"this",
".",
"isInputField",
"(",
")",
")",
"{",
"String",
"strFieldName",
"=",
"this",
".",
"getSFieldParam",
"(",
"strSuffix",
")",
";",
"String",
"strParamValue",
"=",
"this",
".",
"getSFieldProperty",
"(",
"strFieldName",
")",
";",
"if",
"(",
"strParamValue",
"!=",
"null",
")",
"iErrorCode",
"=",
"this",
".",
"setSFieldValue",
"(",
"strParamValue",
",",
"bDisplayOption",
",",
"iMoveMode",
")",
";",
"}",
"return",
"iErrorCode",
";",
"}"
] | Move the HTML input to the screen record fields.
@param strSuffix Only move fields with the suffix.
@return true if one was moved.
@exception DBException File exception. | [
"Move",
"the",
"HTML",
"input",
"to",
"the",
"screen",
"record",
"fields",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java#L608-L620 |
Red5/red5-io | src/main/java/org/red5/io/amf/Output.java | Output.encodeString | protected static byte[] encodeString(String string) {
"""
Encode string.
@param string
string to encode
@return encoded string
"""
Element element = getStringCache().get(string);
byte[] encoded = (element == null ? null : (byte[]) element.getObjectValue());
if (encoded == null) {
ByteBuffer buf = AMF.CHARSET.encode(string);
encoded = new byte[buf.limit()];
buf.get(encoded);
getStringCache().put(new Element(string, encoded));
}
return encoded;
} | java | protected static byte[] encodeString(String string) {
Element element = getStringCache().get(string);
byte[] encoded = (element == null ? null : (byte[]) element.getObjectValue());
if (encoded == null) {
ByteBuffer buf = AMF.CHARSET.encode(string);
encoded = new byte[buf.limit()];
buf.get(encoded);
getStringCache().put(new Element(string, encoded));
}
return encoded;
} | [
"protected",
"static",
"byte",
"[",
"]",
"encodeString",
"(",
"String",
"string",
")",
"{",
"Element",
"element",
"=",
"getStringCache",
"(",
")",
".",
"get",
"(",
"string",
")",
";",
"byte",
"[",
"]",
"encoded",
"=",
"(",
"element",
"==",
"null",
"?",
"null",
":",
"(",
"byte",
"[",
"]",
")",
"element",
".",
"getObjectValue",
"(",
")",
")",
";",
"if",
"(",
"encoded",
"==",
"null",
")",
"{",
"ByteBuffer",
"buf",
"=",
"AMF",
".",
"CHARSET",
".",
"encode",
"(",
"string",
")",
";",
"encoded",
"=",
"new",
"byte",
"[",
"buf",
".",
"limit",
"(",
")",
"]",
";",
"buf",
".",
"get",
"(",
"encoded",
")",
";",
"getStringCache",
"(",
")",
".",
"put",
"(",
"new",
"Element",
"(",
"string",
",",
"encoded",
")",
")",
";",
"}",
"return",
"encoded",
";",
"}"
] | Encode string.
@param string
string to encode
@return encoded string | [
"Encode",
"string",
"."
] | train | https://github.com/Red5/red5-io/blob/9bbbc506423c5a8f18169d46d400df56c0072a33/src/main/java/org/red5/io/amf/Output.java#L526-L536 |
dadoonet/elasticsearch-beyonder | src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java | TemplateElasticsearchUpdater.createTemplate | @Deprecated
public static void createTemplate(Client client, String root, String template, boolean force) throws Exception {
"""
Create a template in Elasticsearch.
@param client Elasticsearch client
@param root dir within the classpath
@param template Template name
@param force set it to true if you want to force cleaning template before adding it
@throws Exception if something goes wrong
@deprecated Will be removed when we don't support TransportClient anymore
"""
String json = TemplateSettingsReader.readTemplate(root, template);
createTemplateWithJson(client, template, json, force);
} | java | @Deprecated
public static void createTemplate(Client client, String root, String template, boolean force) throws Exception {
String json = TemplateSettingsReader.readTemplate(root, template);
createTemplateWithJson(client, template, json, force);
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"createTemplate",
"(",
"Client",
"client",
",",
"String",
"root",
",",
"String",
"template",
",",
"boolean",
"force",
")",
"throws",
"Exception",
"{",
"String",
"json",
"=",
"TemplateSettingsReader",
".",
"readTemplate",
"(",
"root",
",",
"template",
")",
";",
"createTemplateWithJson",
"(",
"client",
",",
"template",
",",
"json",
",",
"force",
")",
";",
"}"
] | Create a template in Elasticsearch.
@param client Elasticsearch client
@param root dir within the classpath
@param template Template name
@param force set it to true if you want to force cleaning template before adding it
@throws Exception if something goes wrong
@deprecated Will be removed when we don't support TransportClient anymore | [
"Create",
"a",
"template",
"in",
"Elasticsearch",
"."
] | train | https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L50-L54 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.setCertificateContactsAsync | public Observable<Contacts> setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) {
"""
Sets the certificate contacts for the specified key vault.
Sets the certificate contacts for the specified key vault. This operation requires the certificates/managecontacts permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param contacts The contacts for the key vault certificate.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Contacts object
"""
return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).map(new Func1<ServiceResponse<Contacts>, Contacts>() {
@Override
public Contacts call(ServiceResponse<Contacts> response) {
return response.body();
}
});
} | java | public Observable<Contacts> setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) {
return setCertificateContactsWithServiceResponseAsync(vaultBaseUrl, contacts).map(new Func1<ServiceResponse<Contacts>, Contacts>() {
@Override
public Contacts call(ServiceResponse<Contacts> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Contacts",
">",
"setCertificateContactsAsync",
"(",
"String",
"vaultBaseUrl",
",",
"Contacts",
"contacts",
")",
"{",
"return",
"setCertificateContactsWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"contacts",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Contacts",
">",
",",
"Contacts",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Contacts",
"call",
"(",
"ServiceResponse",
"<",
"Contacts",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sets the certificate contacts for the specified key vault.
Sets the certificate contacts for the specified key vault. This operation requires the certificates/managecontacts permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param contacts The contacts for the key vault certificate.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Contacts object | [
"Sets",
"the",
"certificate",
"contacts",
"for",
"the",
"specified",
"key",
"vault",
".",
"Sets",
"the",
"certificate",
"contacts",
"for",
"the",
"specified",
"key",
"vault",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"managecontacts",
"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#L5440-L5447 |
apache/incubator-shardingsphere | sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/postgresql/command/PostgreSQLCommandExecutorFactory.java | PostgreSQLCommandExecutorFactory.newInstance | public static CommandExecutor newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket, final BackendConnection backendConnection) {
"""
Create new instance of command executor.
@param commandPacketType command packet type for PostgreSQL
@param commandPacket command packet for PostgreSQL
@param backendConnection backend connection
@return command executor
"""
log.debug("Execute packet type: {}, value: {}", commandPacketType, commandPacket);
switch (commandPacketType) {
case QUERY:
return new PostgreSQLComQueryExecutor((PostgreSQLComQueryPacket) commandPacket, backendConnection);
case PARSE:
return new PostgreSQLComParseExecutor((PostgreSQLComParsePacket) commandPacket, backendConnection);
case BIND:
return new PostgreSQLComBindExecutor((PostgreSQLComBindPacket) commandPacket, backendConnection);
case DESCRIBE:
return new PostgreSQLComDescribeExecutor();
case EXECUTE:
return new PostgreSQLComExecuteExecutor();
case SYNC:
return new PostgreSQLComSyncExecutor();
case TERMINATE:
return new PostgreSQLComTerminationExecutor();
default:
return new PostgreSQLUnsupportedCommandExecutor();
}
} | java | public static CommandExecutor newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket, final BackendConnection backendConnection) {
log.debug("Execute packet type: {}, value: {}", commandPacketType, commandPacket);
switch (commandPacketType) {
case QUERY:
return new PostgreSQLComQueryExecutor((PostgreSQLComQueryPacket) commandPacket, backendConnection);
case PARSE:
return new PostgreSQLComParseExecutor((PostgreSQLComParsePacket) commandPacket, backendConnection);
case BIND:
return new PostgreSQLComBindExecutor((PostgreSQLComBindPacket) commandPacket, backendConnection);
case DESCRIBE:
return new PostgreSQLComDescribeExecutor();
case EXECUTE:
return new PostgreSQLComExecuteExecutor();
case SYNC:
return new PostgreSQLComSyncExecutor();
case TERMINATE:
return new PostgreSQLComTerminationExecutor();
default:
return new PostgreSQLUnsupportedCommandExecutor();
}
} | [
"public",
"static",
"CommandExecutor",
"newInstance",
"(",
"final",
"PostgreSQLCommandPacketType",
"commandPacketType",
",",
"final",
"PostgreSQLCommandPacket",
"commandPacket",
",",
"final",
"BackendConnection",
"backendConnection",
")",
"{",
"log",
".",
"debug",
"(",
"\"Execute packet type: {}, value: {}\"",
",",
"commandPacketType",
",",
"commandPacket",
")",
";",
"switch",
"(",
"commandPacketType",
")",
"{",
"case",
"QUERY",
":",
"return",
"new",
"PostgreSQLComQueryExecutor",
"(",
"(",
"PostgreSQLComQueryPacket",
")",
"commandPacket",
",",
"backendConnection",
")",
";",
"case",
"PARSE",
":",
"return",
"new",
"PostgreSQLComParseExecutor",
"(",
"(",
"PostgreSQLComParsePacket",
")",
"commandPacket",
",",
"backendConnection",
")",
";",
"case",
"BIND",
":",
"return",
"new",
"PostgreSQLComBindExecutor",
"(",
"(",
"PostgreSQLComBindPacket",
")",
"commandPacket",
",",
"backendConnection",
")",
";",
"case",
"DESCRIBE",
":",
"return",
"new",
"PostgreSQLComDescribeExecutor",
"(",
")",
";",
"case",
"EXECUTE",
":",
"return",
"new",
"PostgreSQLComExecuteExecutor",
"(",
")",
";",
"case",
"SYNC",
":",
"return",
"new",
"PostgreSQLComSyncExecutor",
"(",
")",
";",
"case",
"TERMINATE",
":",
"return",
"new",
"PostgreSQLComTerminationExecutor",
"(",
")",
";",
"default",
":",
"return",
"new",
"PostgreSQLUnsupportedCommandExecutor",
"(",
")",
";",
"}",
"}"
] | Create new instance of command executor.
@param commandPacketType command packet type for PostgreSQL
@param commandPacket command packet for PostgreSQL
@param backendConnection backend connection
@return command executor | [
"Create",
"new",
"instance",
"of",
"command",
"executor",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/postgresql/command/PostgreSQLCommandExecutorFactory.java#L56-L76 |
j-a-w-r/jawr-tools | jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/spring/SpringControllerBundleProcessor.java | SpringControllerBundleProcessor.initJawrSpringServlets | @SuppressWarnings("rawtypes")
public List<ServletDefinition> initJawrSpringServlets(ServletContext servletContext) throws ServletException {
"""
Initialize the servlets which will handle the request to the JawrSpringController
@param servletContext the servlet context
@return the list of servlet definition for the JawrSpringControllers
@throws ServletException if a servlet exception occurs
"""
List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>();
ContextLoader contextLoader = new ContextLoader();
WebApplicationContext applicationCtx = contextLoader.initWebApplicationContext(servletContext);
Map<?, ?> jawrControllersMap = applicationCtx.getBeansOfType(JawrSpringController.class);
Iterator<?> entrySetIterator = jawrControllersMap.entrySet().iterator();
while(entrySetIterator.hasNext()){
JawrSpringController jawrController = (JawrSpringController) ((Map.Entry) entrySetIterator.next()).getValue();
Map<String, Object> initParams = new HashMap<String, Object>();
initParams.putAll(jawrController.getInitParams());
ServletConfig servletConfig = new MockServletConfig(SPRING_DISPATCHER_SERVLET,servletContext, initParams);
MockJawrSpringServlet servlet = new MockJawrSpringServlet(jawrController, servletConfig);
ServletDefinition servletDefinition = new ServletDefinition(servlet, servletConfig) ;
jawrServletDefinitions.add(servletDefinition);
}
contextLoader.closeWebApplicationContext(servletContext);
return jawrServletDefinitions;
} | java | @SuppressWarnings("rawtypes")
public List<ServletDefinition> initJawrSpringServlets(ServletContext servletContext) throws ServletException{
List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>();
ContextLoader contextLoader = new ContextLoader();
WebApplicationContext applicationCtx = contextLoader.initWebApplicationContext(servletContext);
Map<?, ?> jawrControllersMap = applicationCtx.getBeansOfType(JawrSpringController.class);
Iterator<?> entrySetIterator = jawrControllersMap.entrySet().iterator();
while(entrySetIterator.hasNext()){
JawrSpringController jawrController = (JawrSpringController) ((Map.Entry) entrySetIterator.next()).getValue();
Map<String, Object> initParams = new HashMap<String, Object>();
initParams.putAll(jawrController.getInitParams());
ServletConfig servletConfig = new MockServletConfig(SPRING_DISPATCHER_SERVLET,servletContext, initParams);
MockJawrSpringServlet servlet = new MockJawrSpringServlet(jawrController, servletConfig);
ServletDefinition servletDefinition = new ServletDefinition(servlet, servletConfig) ;
jawrServletDefinitions.add(servletDefinition);
}
contextLoader.closeWebApplicationContext(servletContext);
return jawrServletDefinitions;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"List",
"<",
"ServletDefinition",
">",
"initJawrSpringServlets",
"(",
"ServletContext",
"servletContext",
")",
"throws",
"ServletException",
"{",
"List",
"<",
"ServletDefinition",
">",
"jawrServletDefinitions",
"=",
"new",
"ArrayList",
"<",
"ServletDefinition",
">",
"(",
")",
";",
"ContextLoader",
"contextLoader",
"=",
"new",
"ContextLoader",
"(",
")",
";",
"WebApplicationContext",
"applicationCtx",
"=",
"contextLoader",
".",
"initWebApplicationContext",
"(",
"servletContext",
")",
";",
"Map",
"<",
"?",
",",
"?",
">",
"jawrControllersMap",
"=",
"applicationCtx",
".",
"getBeansOfType",
"(",
"JawrSpringController",
".",
"class",
")",
";",
"Iterator",
"<",
"?",
">",
"entrySetIterator",
"=",
"jawrControllersMap",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"entrySetIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"JawrSpringController",
"jawrController",
"=",
"(",
"JawrSpringController",
")",
"(",
"(",
"Map",
".",
"Entry",
")",
"entrySetIterator",
".",
"next",
"(",
")",
")",
".",
"getValue",
"(",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"initParams",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"initParams",
".",
"putAll",
"(",
"jawrController",
".",
"getInitParams",
"(",
")",
")",
";",
"ServletConfig",
"servletConfig",
"=",
"new",
"MockServletConfig",
"(",
"SPRING_DISPATCHER_SERVLET",
",",
"servletContext",
",",
"initParams",
")",
";",
"MockJawrSpringServlet",
"servlet",
"=",
"new",
"MockJawrSpringServlet",
"(",
"jawrController",
",",
"servletConfig",
")",
";",
"ServletDefinition",
"servletDefinition",
"=",
"new",
"ServletDefinition",
"(",
"servlet",
",",
"servletConfig",
")",
";",
"jawrServletDefinitions",
".",
"add",
"(",
"servletDefinition",
")",
";",
"}",
"contextLoader",
".",
"closeWebApplicationContext",
"(",
"servletContext",
")",
";",
"return",
"jawrServletDefinitions",
";",
"}"
] | Initialize the servlets which will handle the request to the JawrSpringController
@param servletContext the servlet context
@return the list of servlet definition for the JawrSpringControllers
@throws ServletException if a servlet exception occurs | [
"Initialize",
"the",
"servlets",
"which",
"will",
"handle",
"the",
"request",
"to",
"the",
"JawrSpringController"
] | train | https://github.com/j-a-w-r/jawr-tools/blob/ebae989e55b53fd7dca4450ed9294c6f64309041/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/spring/SpringControllerBundleProcessor.java#L51-L73 |
alkacon/opencms-core | src/org/opencms/module/CmsModuleImportExportHandler.java | CmsModuleImportExportHandler.readModuleFromManifest | public static CmsModule readModuleFromManifest(byte[] manifest) throws CmsConfigurationException {
"""
Reads a module object from an external file source.<p>
@param manifest the manifest data
@return the imported module
@throws CmsConfigurationException if the module could not be imported
"""
// instantiate Digester and enable XML validation
Digester digester = new Digester();
digester.setUseContextClassLoader(true);
digester.setValidating(false);
digester.setRuleNamespaceURI(null);
digester.setErrorHandler(new CmsXmlErrorHandler("manifest data"));
// add this class to the Digester
CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler();
final String[] version = new String[] {null};
digester.push(handler);
digester.addRule("*/export_version", new Rule() {
@Override
public void body(String namespace, String name, String text) throws Exception {
version[0] = text.trim();
}
});
CmsModuleXmlHandler.addXmlDigesterRules(digester);
InputStream stream = new ByteArrayInputStream(manifest);
try {
digester.parse(stream);
} catch (IOException e) {
CmsMessageContainer message = Messages.get().container(Messages.ERR_IO_MODULE_IMPORT_1, "manifest data");
LOG.error(message.key(), e);
throw new CmsConfigurationException(message, e);
} catch (SAXException e) {
CmsMessageContainer message = Messages.get().container(Messages.ERR_SAX_MODULE_IMPORT_1, "manifest data");
LOG.error(message.key(), e);
throw new CmsConfigurationException(message, e);
}
CmsModule importedModule = handler.getModule();
// the digester must have set the module now
if (importedModule == null) {
throw new CmsConfigurationException(
Messages.get().container(Messages.ERR_IMPORT_MOD_ALREADY_INSTALLED_1, "manifest data"));
} else {
importedModule.setExportVersion(version[0]);
}
return importedModule;
} | java | public static CmsModule readModuleFromManifest(byte[] manifest) throws CmsConfigurationException {
// instantiate Digester and enable XML validation
Digester digester = new Digester();
digester.setUseContextClassLoader(true);
digester.setValidating(false);
digester.setRuleNamespaceURI(null);
digester.setErrorHandler(new CmsXmlErrorHandler("manifest data"));
// add this class to the Digester
CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler();
final String[] version = new String[] {null};
digester.push(handler);
digester.addRule("*/export_version", new Rule() {
@Override
public void body(String namespace, String name, String text) throws Exception {
version[0] = text.trim();
}
});
CmsModuleXmlHandler.addXmlDigesterRules(digester);
InputStream stream = new ByteArrayInputStream(manifest);
try {
digester.parse(stream);
} catch (IOException e) {
CmsMessageContainer message = Messages.get().container(Messages.ERR_IO_MODULE_IMPORT_1, "manifest data");
LOG.error(message.key(), e);
throw new CmsConfigurationException(message, e);
} catch (SAXException e) {
CmsMessageContainer message = Messages.get().container(Messages.ERR_SAX_MODULE_IMPORT_1, "manifest data");
LOG.error(message.key(), e);
throw new CmsConfigurationException(message, e);
}
CmsModule importedModule = handler.getModule();
// the digester must have set the module now
if (importedModule == null) {
throw new CmsConfigurationException(
Messages.get().container(Messages.ERR_IMPORT_MOD_ALREADY_INSTALLED_1, "manifest data"));
} else {
importedModule.setExportVersion(version[0]);
}
return importedModule;
} | [
"public",
"static",
"CmsModule",
"readModuleFromManifest",
"(",
"byte",
"[",
"]",
"manifest",
")",
"throws",
"CmsConfigurationException",
"{",
"// instantiate Digester and enable XML validation",
"Digester",
"digester",
"=",
"new",
"Digester",
"(",
")",
";",
"digester",
".",
"setUseContextClassLoader",
"(",
"true",
")",
";",
"digester",
".",
"setValidating",
"(",
"false",
")",
";",
"digester",
".",
"setRuleNamespaceURI",
"(",
"null",
")",
";",
"digester",
".",
"setErrorHandler",
"(",
"new",
"CmsXmlErrorHandler",
"(",
"\"manifest data\"",
")",
")",
";",
"// add this class to the Digester",
"CmsModuleImportExportHandler",
"handler",
"=",
"new",
"CmsModuleImportExportHandler",
"(",
")",
";",
"final",
"String",
"[",
"]",
"version",
"=",
"new",
"String",
"[",
"]",
"{",
"null",
"}",
";",
"digester",
".",
"push",
"(",
"handler",
")",
";",
"digester",
".",
"addRule",
"(",
"\"*/export_version\"",
",",
"new",
"Rule",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"body",
"(",
"String",
"namespace",
",",
"String",
"name",
",",
"String",
"text",
")",
"throws",
"Exception",
"{",
"version",
"[",
"0",
"]",
"=",
"text",
".",
"trim",
"(",
")",
";",
"}",
"}",
")",
";",
"CmsModuleXmlHandler",
".",
"addXmlDigesterRules",
"(",
"digester",
")",
";",
"InputStream",
"stream",
"=",
"new",
"ByteArrayInputStream",
"(",
"manifest",
")",
";",
"try",
"{",
"digester",
".",
"parse",
"(",
"stream",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"CmsMessageContainer",
"message",
"=",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_IO_MODULE_IMPORT_1",
",",
"\"manifest data\"",
")",
";",
"LOG",
".",
"error",
"(",
"message",
".",
"key",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"CmsConfigurationException",
"(",
"message",
",",
"e",
")",
";",
"}",
"catch",
"(",
"SAXException",
"e",
")",
"{",
"CmsMessageContainer",
"message",
"=",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_SAX_MODULE_IMPORT_1",
",",
"\"manifest data\"",
")",
";",
"LOG",
".",
"error",
"(",
"message",
".",
"key",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"CmsConfigurationException",
"(",
"message",
",",
"e",
")",
";",
"}",
"CmsModule",
"importedModule",
"=",
"handler",
".",
"getModule",
"(",
")",
";",
"// the digester must have set the module now",
"if",
"(",
"importedModule",
"==",
"null",
")",
"{",
"throw",
"new",
"CmsConfigurationException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_IMPORT_MOD_ALREADY_INSTALLED_1",
",",
"\"manifest data\"",
")",
")",
";",
"}",
"else",
"{",
"importedModule",
".",
"setExportVersion",
"(",
"version",
"[",
"0",
"]",
")",
";",
"}",
"return",
"importedModule",
";",
"}"
] | Reads a module object from an external file source.<p>
@param manifest the manifest data
@return the imported module
@throws CmsConfigurationException if the module could not be imported | [
"Reads",
"a",
"module",
"object",
"from",
"an",
"external",
"file",
"source",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleImportExportHandler.java#L278-L326 |
Axway/Grapes | commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java | DataModelFactory.createPromotionDetails | public static PromotionDetails createPromotionDetails(final Boolean canBePromoted, final Boolean isSnapshot, final List<String> unPromotedDependencies, final List<Artifact> doNotUseArtifacts) throws IOException {
"""
Generates a PromotionDetails regarding the parameters.
@param canBePromoted Boolean
@param isSnapshot Boolean
@param unPromotedDependencies List<String>
@param doNotUseArtifacts List<Artifact>
@return PromotionDetails
@throws IOException
"""
try{
final PromotionDetails promotionDetails = new PromotionDetails();
promotionDetails.setPromotable(canBePromoted);
promotionDetails.setSnapshot(isSnapshot);
promotionDetails.setUnPromotedDependencies(unPromotedDependencies);
promotionDetails.setDoNotUseArtifacts(doNotUseArtifacts);
return promotionDetails;
}
catch(Exception e){
throw new IOException(e);
}
} | java | public static PromotionDetails createPromotionDetails(final Boolean canBePromoted, final Boolean isSnapshot, final List<String> unPromotedDependencies, final List<Artifact> doNotUseArtifacts) throws IOException{
try{
final PromotionDetails promotionDetails = new PromotionDetails();
promotionDetails.setPromotable(canBePromoted);
promotionDetails.setSnapshot(isSnapshot);
promotionDetails.setUnPromotedDependencies(unPromotedDependencies);
promotionDetails.setDoNotUseArtifacts(doNotUseArtifacts);
return promotionDetails;
}
catch(Exception e){
throw new IOException(e);
}
} | [
"public",
"static",
"PromotionDetails",
"createPromotionDetails",
"(",
"final",
"Boolean",
"canBePromoted",
",",
"final",
"Boolean",
"isSnapshot",
",",
"final",
"List",
"<",
"String",
">",
"unPromotedDependencies",
",",
"final",
"List",
"<",
"Artifact",
">",
"doNotUseArtifacts",
")",
"throws",
"IOException",
"{",
"try",
"{",
"final",
"PromotionDetails",
"promotionDetails",
"=",
"new",
"PromotionDetails",
"(",
")",
";",
"promotionDetails",
".",
"setPromotable",
"(",
"canBePromoted",
")",
";",
"promotionDetails",
".",
"setSnapshot",
"(",
"isSnapshot",
")",
";",
"promotionDetails",
".",
"setUnPromotedDependencies",
"(",
"unPromotedDependencies",
")",
";",
"promotionDetails",
".",
"setDoNotUseArtifacts",
"(",
"doNotUseArtifacts",
")",
";",
"return",
"promotionDetails",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"e",
")",
";",
"}",
"}"
] | Generates a PromotionDetails regarding the parameters.
@param canBePromoted Boolean
@param isSnapshot Boolean
@param unPromotedDependencies List<String>
@param doNotUseArtifacts List<Artifact>
@return PromotionDetails
@throws IOException | [
"Generates",
"a",
"PromotionDetails",
"regarding",
"the",
"parameters",
"."
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java#L180-L194 |
virgo47/javasimon | core/src/main/java/org/javasimon/AbstractSimon.java | AbstractSimon.replaceChild | void replaceChild(Simon simon, AbstractSimon newSimon) {
"""
Replaces one of the children for a new one (unknown to concrete). Used only internally.
@param simon original Simon (unknown)
@param newSimon new Simon
"""
children.remove(simon);
if (newSimon != null) {
children.add(newSimon);
newSimon.setParent(this);
}
} | java | void replaceChild(Simon simon, AbstractSimon newSimon) {
children.remove(simon);
if (newSimon != null) {
children.add(newSimon);
newSimon.setParent(this);
}
} | [
"void",
"replaceChild",
"(",
"Simon",
"simon",
",",
"AbstractSimon",
"newSimon",
")",
"{",
"children",
".",
"remove",
"(",
"simon",
")",
";",
"if",
"(",
"newSimon",
"!=",
"null",
")",
"{",
"children",
".",
"add",
"(",
"newSimon",
")",
";",
"newSimon",
".",
"setParent",
"(",
"this",
")",
";",
"}",
"}"
] | Replaces one of the children for a new one (unknown to concrete). Used only internally.
@param simon original Simon (unknown)
@param newSimon new Simon | [
"Replaces",
"one",
"of",
"the",
"children",
"for",
"a",
"new",
"one",
"(",
"unknown",
"to",
"concrete",
")",
".",
"Used",
"only",
"internally",
"."
] | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/AbstractSimon.java#L179-L185 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/HashUtils.java | HashUtils.sha256Hex | public static String sha256Hex(String data, Charset charset) throws NoSuchAlgorithmException {
"""
Hashes a string using the SHA-256 algorithm. Returns a hexadecimal result.
@since 1.1
@param data the string to hash
@param charset the charset of the string
@return the hexadecimal SHA-256 hash of the string
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers
"""
return sha256Hex(data.getBytes(charset));
} | java | public static String sha256Hex(String data, Charset charset) throws NoSuchAlgorithmException {
return sha256Hex(data.getBytes(charset));
} | [
"public",
"static",
"String",
"sha256Hex",
"(",
"String",
"data",
",",
"Charset",
"charset",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"return",
"sha256Hex",
"(",
"data",
".",
"getBytes",
"(",
"charset",
")",
")",
";",
"}"
] | Hashes a string using the SHA-256 algorithm. Returns a hexadecimal result.
@since 1.1
@param data the string to hash
@param charset the charset of the string
@return the hexadecimal SHA-256 hash of the string
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers | [
"Hashes",
"a",
"string",
"using",
"the",
"SHA",
"-",
"256",
"algorithm",
".",
"Returns",
"a",
"hexadecimal",
"result",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/HashUtils.java#L434-L436 |
aws/aws-sdk-java | aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/ReEncryptRequest.java | ReEncryptRequest.withDestinationEncryptionContext | public ReEncryptRequest withDestinationEncryptionContext(java.util.Map<String, String> destinationEncryptionContext) {
"""
<p>
Encryption context to use when the data is reencrypted.
</p>
@param destinationEncryptionContext
Encryption context to use when the data is reencrypted.
@return Returns a reference to this object so that method calls can be chained together.
"""
setDestinationEncryptionContext(destinationEncryptionContext);
return this;
} | java | public ReEncryptRequest withDestinationEncryptionContext(java.util.Map<String, String> destinationEncryptionContext) {
setDestinationEncryptionContext(destinationEncryptionContext);
return this;
} | [
"public",
"ReEncryptRequest",
"withDestinationEncryptionContext",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"destinationEncryptionContext",
")",
"{",
"setDestinationEncryptionContext",
"(",
"destinationEncryptionContext",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Encryption context to use when the data is reencrypted.
</p>
@param destinationEncryptionContext
Encryption context to use when the data is reencrypted.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Encryption",
"context",
"to",
"use",
"when",
"the",
"data",
"is",
"reencrypted",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/ReEncryptRequest.java#L509-L512 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/util/Util.java | Util.cacheStream | public static InputStream cacheStream(@javax.annotation.Nonnull final String url, @javax.annotation.Nonnull final String file) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
"""
Cache input stream.
@param url the url
@param file the file
@return the input stream
@throws IOException the io exception
@throws NoSuchAlgorithmException the no such algorithm exception
@throws KeyStoreException the key store exception
@throws KeyManagementException the key management exception
"""
if (new File(file).exists()) {
return new FileInputStream(file);
}
else {
return new TeeInputStream(get(url), new FileOutputStream(file));
}
} | java | public static InputStream cacheStream(@javax.annotation.Nonnull final String url, @javax.annotation.Nonnull final String file) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
if (new File(file).exists()) {
return new FileInputStream(file);
}
else {
return new TeeInputStream(get(url), new FileOutputStream(file));
}
} | [
"public",
"static",
"InputStream",
"cacheStream",
"(",
"@",
"javax",
".",
"annotation",
".",
"Nonnull",
"final",
"String",
"url",
",",
"@",
"javax",
".",
"annotation",
".",
"Nonnull",
"final",
"String",
"file",
")",
"throws",
"IOException",
",",
"NoSuchAlgorithmException",
",",
"KeyStoreException",
",",
"KeyManagementException",
"{",
"if",
"(",
"new",
"File",
"(",
"file",
")",
".",
"exists",
"(",
")",
")",
"{",
"return",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"}",
"else",
"{",
"return",
"new",
"TeeInputStream",
"(",
"get",
"(",
"url",
")",
",",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
";",
"}",
"}"
] | Cache input stream.
@param url the url
@param file the file
@return the input stream
@throws IOException the io exception
@throws NoSuchAlgorithmException the no such algorithm exception
@throws KeyStoreException the key store exception
@throws KeyManagementException the key management exception | [
"Cache",
"input",
"stream",
"."
] | train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/Util.java#L180-L187 |
Prototik/HoloEverywhere | library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java | RadialPickerLayout.onMeasure | @Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
"""
Measure the view to end up as a square, based on the minimum of the height and width.
"""
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int minDimension = Math.min(measuredWidth, measuredHeight);
super.onMeasure(MeasureSpec.makeMeasureSpec(minDimension, widthMode),
MeasureSpec.makeMeasureSpec(minDimension, heightMode));
} | java | @Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int minDimension = Math.min(measuredWidth, measuredHeight);
super.onMeasure(MeasureSpec.makeMeasureSpec(minDimension, widthMode),
MeasureSpec.makeMeasureSpec(minDimension, heightMode));
} | [
"@",
"Override",
"public",
"void",
"onMeasure",
"(",
"int",
"widthMeasureSpec",
",",
"int",
"heightMeasureSpec",
")",
"{",
"int",
"measuredWidth",
"=",
"MeasureSpec",
".",
"getSize",
"(",
"widthMeasureSpec",
")",
";",
"int",
"widthMode",
"=",
"MeasureSpec",
".",
"getMode",
"(",
"widthMeasureSpec",
")",
";",
"int",
"measuredHeight",
"=",
"MeasureSpec",
".",
"getSize",
"(",
"heightMeasureSpec",
")",
";",
"int",
"heightMode",
"=",
"MeasureSpec",
".",
"getMode",
"(",
"heightMeasureSpec",
")",
";",
"int",
"minDimension",
"=",
"Math",
".",
"min",
"(",
"measuredWidth",
",",
"measuredHeight",
")",
";",
"super",
".",
"onMeasure",
"(",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"minDimension",
",",
"widthMode",
")",
",",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"minDimension",
",",
"heightMode",
")",
")",
";",
"}"
] | Measure the view to end up as a square, based on the minimum of the height and width. | [
"Measure",
"the",
"view",
"to",
"end",
"up",
"as",
"a",
"square",
"based",
"on",
"the",
"minimum",
"of",
"the",
"height",
"and",
"width",
"."
] | train | https://github.com/Prototik/HoloEverywhere/blob/b870abb5ab009a5a6dbab3fb855ec2854e35e125/library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java#L142-L152 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/Neighbours.java | Neighbours.addTopicSpaceReference | void addTopicSpaceReference(SIBUuid8 neighbourUuid,
SIBUuid12 topicSpace,
String topic,
boolean warmRestarted) {
"""
When the Destination manager doesn't know about a Destination, the topic space
reference is created here until either the proxy is deleted, or the topic space
is created.
@param neighbourUuid the uuid of the remote ME
@param topicSpace the name of the topic space destination
@param topic The topic registered.
@param warmRestarted If the messaging engine has been warm restarted.
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"addTopicSpaceReference",
new Object[] { neighbourUuid, topicSpace, topic, new Boolean(warmRestarted) });
// Synchronize around the topic space references to stop removal and
// additions occuring at the same time.
synchronized (_topicSpaces)
{
// From the list of topic spaces, get the HashMap that contains the
// list of topicSpaces to topics.
TemporarySubscription sub =
(TemporarySubscription) _topicSpaces.get(topicSpace);
Neighbour neighbour = null;
// If the ME has warm restarted, then the Neighbour object will actually
// be in the recoveredNeighbours instance.
if (warmRestarted)
{
synchronized(_recoveredNeighbours)
{
neighbour = (Neighbour)_recoveredNeighbours.get(neighbourUuid);
}
}
else
neighbour = getNeighbour(neighbourUuid);
MESubscription subscription =
neighbour.getSubscription(topicSpace, topic);
if (sub == null)
{
// Consruct a new TemporarySubscription object.
sub = new TemporarySubscription(neighbourUuid, subscription);
// Put the topic space reference into the list of topic
// spaces, keyed on the topic space.
_topicSpaces.put(topicSpace, sub);
}
else
{
// Add a topic to the list of topics on this topic space for this ME
sub.addTopic(neighbourUuid, subscription);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addTopicSpaceReference");
} | java | void addTopicSpaceReference(SIBUuid8 neighbourUuid,
SIBUuid12 topicSpace,
String topic,
boolean warmRestarted)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"addTopicSpaceReference",
new Object[] { neighbourUuid, topicSpace, topic, new Boolean(warmRestarted) });
// Synchronize around the topic space references to stop removal and
// additions occuring at the same time.
synchronized (_topicSpaces)
{
// From the list of topic spaces, get the HashMap that contains the
// list of topicSpaces to topics.
TemporarySubscription sub =
(TemporarySubscription) _topicSpaces.get(topicSpace);
Neighbour neighbour = null;
// If the ME has warm restarted, then the Neighbour object will actually
// be in the recoveredNeighbours instance.
if (warmRestarted)
{
synchronized(_recoveredNeighbours)
{
neighbour = (Neighbour)_recoveredNeighbours.get(neighbourUuid);
}
}
else
neighbour = getNeighbour(neighbourUuid);
MESubscription subscription =
neighbour.getSubscription(topicSpace, topic);
if (sub == null)
{
// Consruct a new TemporarySubscription object.
sub = new TemporarySubscription(neighbourUuid, subscription);
// Put the topic space reference into the list of topic
// spaces, keyed on the topic space.
_topicSpaces.put(topicSpace, sub);
}
else
{
// Add a topic to the list of topics on this topic space for this ME
sub.addTopic(neighbourUuid, subscription);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addTopicSpaceReference");
} | [
"void",
"addTopicSpaceReference",
"(",
"SIBUuid8",
"neighbourUuid",
",",
"SIBUuid12",
"topicSpace",
",",
"String",
"topic",
",",
"boolean",
"warmRestarted",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"addTopicSpaceReference\"",
",",
"new",
"Object",
"[",
"]",
"{",
"neighbourUuid",
",",
"topicSpace",
",",
"topic",
",",
"new",
"Boolean",
"(",
"warmRestarted",
")",
"}",
")",
";",
"// Synchronize around the topic space references to stop removal and",
"// additions occuring at the same time. ",
"synchronized",
"(",
"_topicSpaces",
")",
"{",
"// From the list of topic spaces, get the HashMap that contains the ",
"// list of topicSpaces to topics.",
"TemporarySubscription",
"sub",
"=",
"(",
"TemporarySubscription",
")",
"_topicSpaces",
".",
"get",
"(",
"topicSpace",
")",
";",
"Neighbour",
"neighbour",
"=",
"null",
";",
"// If the ME has warm restarted, then the Neighbour object will actually",
"// be in the recoveredNeighbours instance.",
"if",
"(",
"warmRestarted",
")",
"{",
"synchronized",
"(",
"_recoveredNeighbours",
")",
"{",
"neighbour",
"=",
"(",
"Neighbour",
")",
"_recoveredNeighbours",
".",
"get",
"(",
"neighbourUuid",
")",
";",
"}",
"}",
"else",
"neighbour",
"=",
"getNeighbour",
"(",
"neighbourUuid",
")",
";",
"MESubscription",
"subscription",
"=",
"neighbour",
".",
"getSubscription",
"(",
"topicSpace",
",",
"topic",
")",
";",
"if",
"(",
"sub",
"==",
"null",
")",
"{",
"// Consruct a new TemporarySubscription object.",
"sub",
"=",
"new",
"TemporarySubscription",
"(",
"neighbourUuid",
",",
"subscription",
")",
";",
"// Put the topic space reference into the list of topic",
"// spaces, keyed on the topic space.",
"_topicSpaces",
".",
"put",
"(",
"topicSpace",
",",
"sub",
")",
";",
"}",
"else",
"{",
"// Add a topic to the list of topics on this topic space for this ME",
"sub",
".",
"addTopic",
"(",
"neighbourUuid",
",",
"subscription",
")",
";",
"}",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"addTopicSpaceReference\"",
")",
";",
"}"
] | When the Destination manager doesn't know about a Destination, the topic space
reference is created here until either the proxy is deleted, or the topic space
is created.
@param neighbourUuid the uuid of the remote ME
@param topicSpace the name of the topic space destination
@param topic The topic registered.
@param warmRestarted If the messaging engine has been warm restarted. | [
"When",
"the",
"Destination",
"manager",
"doesn",
"t",
"know",
"about",
"a",
"Destination",
"the",
"topic",
"space",
"reference",
"is",
"created",
"here",
"until",
"either",
"the",
"proxy",
"is",
"deleted",
"or",
"the",
"topic",
"space",
"is",
"created",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/Neighbours.java#L208-L264 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.createGroup | public GitlabGroup createGroup(GitlabGroup group, GitlabUser sudoUser) throws IOException {
"""
Creates a Group
@param group The gitlab Group object
@param sudoUser The user to create the group on behalf of
@return The GitLab Group
@throws IOException on gitlab api call error
"""
Query query = new Query()
.append("name", group.getName())
.append("path", group.getPath())
.appendIf("description", group.getDescription())
.appendIf("membership_lock", group.getMembershipLock())
.appendIf("share_with_group_lock", group.getShareWithGroupLock())
.appendIf("visibility", group.getVisibility().toString())
.appendIf("lfs_enabled", group.isLfsEnabled())
.appendIf("request_access_enabled", group.isRequestAccessEnabled())
.appendIf("shared_runners_minutes_limit", group.getSharedRunnersMinutesLimit())
.appendIf("ldap_cn", group.getLdapCn())
.appendIf("ldap_access", group.getLdapAccess())
.appendIf(PARAM_SUDO, sudoUser != null ? sudoUser.getId() : null);
String tailUrl = GitlabGroup.URL + query.toString();
return dispatch().to(tailUrl, GitlabGroup.class);
} | java | public GitlabGroup createGroup(GitlabGroup group, GitlabUser sudoUser) throws IOException {
Query query = new Query()
.append("name", group.getName())
.append("path", group.getPath())
.appendIf("description", group.getDescription())
.appendIf("membership_lock", group.getMembershipLock())
.appendIf("share_with_group_lock", group.getShareWithGroupLock())
.appendIf("visibility", group.getVisibility().toString())
.appendIf("lfs_enabled", group.isLfsEnabled())
.appendIf("request_access_enabled", group.isRequestAccessEnabled())
.appendIf("shared_runners_minutes_limit", group.getSharedRunnersMinutesLimit())
.appendIf("ldap_cn", group.getLdapCn())
.appendIf("ldap_access", group.getLdapAccess())
.appendIf(PARAM_SUDO, sudoUser != null ? sudoUser.getId() : null);
String tailUrl = GitlabGroup.URL + query.toString();
return dispatch().to(tailUrl, GitlabGroup.class);
} | [
"public",
"GitlabGroup",
"createGroup",
"(",
"GitlabGroup",
"group",
",",
"GitlabUser",
"sudoUser",
")",
"throws",
"IOException",
"{",
"Query",
"query",
"=",
"new",
"Query",
"(",
")",
".",
"append",
"(",
"\"name\"",
",",
"group",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\"path\"",
",",
"group",
".",
"getPath",
"(",
")",
")",
".",
"appendIf",
"(",
"\"description\"",
",",
"group",
".",
"getDescription",
"(",
")",
")",
".",
"appendIf",
"(",
"\"membership_lock\"",
",",
"group",
".",
"getMembershipLock",
"(",
")",
")",
".",
"appendIf",
"(",
"\"share_with_group_lock\"",
",",
"group",
".",
"getShareWithGroupLock",
"(",
")",
")",
".",
"appendIf",
"(",
"\"visibility\"",
",",
"group",
".",
"getVisibility",
"(",
")",
".",
"toString",
"(",
")",
")",
".",
"appendIf",
"(",
"\"lfs_enabled\"",
",",
"group",
".",
"isLfsEnabled",
"(",
")",
")",
".",
"appendIf",
"(",
"\"request_access_enabled\"",
",",
"group",
".",
"isRequestAccessEnabled",
"(",
")",
")",
".",
"appendIf",
"(",
"\"shared_runners_minutes_limit\"",
",",
"group",
".",
"getSharedRunnersMinutesLimit",
"(",
")",
")",
".",
"appendIf",
"(",
"\"ldap_cn\"",
",",
"group",
".",
"getLdapCn",
"(",
")",
")",
".",
"appendIf",
"(",
"\"ldap_access\"",
",",
"group",
".",
"getLdapAccess",
"(",
")",
")",
".",
"appendIf",
"(",
"PARAM_SUDO",
",",
"sudoUser",
"!=",
"null",
"?",
"sudoUser",
".",
"getId",
"(",
")",
":",
"null",
")",
";",
"String",
"tailUrl",
"=",
"GitlabGroup",
".",
"URL",
"+",
"query",
".",
"toString",
"(",
")",
";",
"return",
"dispatch",
"(",
")",
".",
"to",
"(",
"tailUrl",
",",
"GitlabGroup",
".",
"class",
")",
";",
"}"
] | Creates a Group
@param group The gitlab Group object
@param sudoUser The user to create the group on behalf of
@return The GitLab Group
@throws IOException on gitlab api call error | [
"Creates",
"a",
"Group"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L660-L679 |
attribyte/wpdb | src/main/java/org/attribyte/wp/db/DB.java | DB.selectOption | public String selectOption(final String optionName, final String defaultValue) throws SQLException {
"""
Gets a configuration option with a default value.
@param optionName The option name.
@param defaultValue A default value if no option is set.
@return The option value or the default value if not found.
@throws SQLException on database error.
"""
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.optionSelectTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectOptionSQL);
stmt.setString(1, optionName);
rs = stmt.executeQuery();
if(rs.next()) {
String val = rs.getString(1);
return val != null ? val.trim() : defaultValue;
} else {
return defaultValue;
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
} | java | public String selectOption(final String optionName, final String defaultValue) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.optionSelectTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectOptionSQL);
stmt.setString(1, optionName);
rs = stmt.executeQuery();
if(rs.next()) {
String val = rs.getString(1);
return val != null ? val.trim() : defaultValue;
} else {
return defaultValue;
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
} | [
"public",
"String",
"selectOption",
"(",
"final",
"String",
"optionName",
",",
"final",
"String",
"defaultValue",
")",
"throws",
"SQLException",
"{",
"Connection",
"conn",
"=",
"null",
";",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"ResultSet",
"rs",
"=",
"null",
";",
"Timer",
".",
"Context",
"ctx",
"=",
"metrics",
".",
"optionSelectTimer",
".",
"time",
"(",
")",
";",
"try",
"{",
"conn",
"=",
"connectionSupplier",
".",
"getConnection",
"(",
")",
";",
"stmt",
"=",
"conn",
".",
"prepareStatement",
"(",
"selectOptionSQL",
")",
";",
"stmt",
".",
"setString",
"(",
"1",
",",
"optionName",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"String",
"val",
"=",
"rs",
".",
"getString",
"(",
"1",
")",
";",
"return",
"val",
"!=",
"null",
"?",
"val",
".",
"trim",
"(",
")",
":",
"defaultValue",
";",
"}",
"else",
"{",
"return",
"defaultValue",
";",
"}",
"}",
"finally",
"{",
"ctx",
".",
"stop",
"(",
")",
";",
"SQLUtil",
".",
"closeQuietly",
"(",
"conn",
",",
"stmt",
",",
"rs",
")",
";",
"}",
"}"
] | Gets a configuration option with a default value.
@param optionName The option name.
@param defaultValue A default value if no option is set.
@return The option value or the default value if not found.
@throws SQLException on database error. | [
"Gets",
"a",
"configuration",
"option",
"with",
"a",
"default",
"value",
"."
] | train | https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L2671-L2691 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java | ConfigUtils.getConfig | public static Config getConfig(Config config, String path, Config def) {
"""
Return {@link Config} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return config value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
"""
if (config.hasPath(path)) {
return config.getConfig(path);
}
return def;
} | java | public static Config getConfig(Config config, String path, Config def) {
if (config.hasPath(path)) {
return config.getConfig(path);
}
return def;
} | [
"public",
"static",
"Config",
"getConfig",
"(",
"Config",
"config",
",",
"String",
"path",
",",
"Config",
"def",
")",
"{",
"if",
"(",
"config",
".",
"hasPath",
"(",
"path",
")",
")",
"{",
"return",
"config",
".",
"getConfig",
"(",
"path",
")",
";",
"}",
"return",
"def",
";",
"}"
] | Return {@link Config} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return config value at <code>path</code> if <code>config</code> has path. If not return <code>def</code> | [
"Return",
"{",
"@link",
"Config",
"}",
"value",
"at",
"<code",
">",
"path<",
"/",
"code",
">",
"if",
"<code",
">",
"config<",
"/",
"code",
">",
"has",
"path",
".",
"If",
"not",
"return",
"<code",
">",
"def<",
"/",
"code",
">"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java#L392-L397 |
bramp/ffmpeg-cli-wrapper | src/main/java/net/bramp/ffmpeg/Preconditions.java | Preconditions.checkValidStream | public static URI checkValidStream(URI uri) throws IllegalArgumentException {
"""
Checks if the URI is valid for streaming to.
@param uri The URI to check
@return The passed in URI if it is valid
@throws IllegalArgumentException if the URI is not valid.
"""
String scheme = checkNotNull(uri).getScheme();
scheme = checkNotNull(scheme, "URI is missing a scheme").toLowerCase();
if (rtps.contains(scheme)) {
return uri;
}
if (udpTcp.contains(scheme)) {
if (uri.getPort() == -1) {
throw new IllegalArgumentException("must set port when using udp or tcp scheme");
}
return uri;
}
throw new IllegalArgumentException("not a valid output URL, must use rtp/tcp/udp scheme");
} | java | public static URI checkValidStream(URI uri) throws IllegalArgumentException {
String scheme = checkNotNull(uri).getScheme();
scheme = checkNotNull(scheme, "URI is missing a scheme").toLowerCase();
if (rtps.contains(scheme)) {
return uri;
}
if (udpTcp.contains(scheme)) {
if (uri.getPort() == -1) {
throw new IllegalArgumentException("must set port when using udp or tcp scheme");
}
return uri;
}
throw new IllegalArgumentException("not a valid output URL, must use rtp/tcp/udp scheme");
} | [
"public",
"static",
"URI",
"checkValidStream",
"(",
"URI",
"uri",
")",
"throws",
"IllegalArgumentException",
"{",
"String",
"scheme",
"=",
"checkNotNull",
"(",
"uri",
")",
".",
"getScheme",
"(",
")",
";",
"scheme",
"=",
"checkNotNull",
"(",
"scheme",
",",
"\"URI is missing a scheme\"",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"rtps",
".",
"contains",
"(",
"scheme",
")",
")",
"{",
"return",
"uri",
";",
"}",
"if",
"(",
"udpTcp",
".",
"contains",
"(",
"scheme",
")",
")",
"{",
"if",
"(",
"uri",
".",
"getPort",
"(",
")",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"must set port when using udp or tcp scheme\"",
")",
";",
"}",
"return",
"uri",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"not a valid output URL, must use rtp/tcp/udp scheme\"",
")",
";",
"}"
] | Checks if the URI is valid for streaming to.
@param uri The URI to check
@return The passed in URI if it is valid
@throws IllegalArgumentException if the URI is not valid. | [
"Checks",
"if",
"the",
"URI",
"is",
"valid",
"for",
"streaming",
"to",
"."
] | train | https://github.com/bramp/ffmpeg-cli-wrapper/blob/3819b155edf9132acc75bb6af66dcef1b98c64b2/src/main/java/net/bramp/ffmpeg/Preconditions.java#L43-L59 |
Azure/azure-sdk-for-java | policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyAssignmentsInner.java | PolicyAssignmentsInner.createById | public PolicyAssignmentInner createById(String policyAssignmentId, PolicyAssignmentInner parameters) {
"""
Creates a policy assignment by ID.
Policy assignments are inherited by child resources. For example, when you apply a policy to a resource group that policy is assigned to all resources in the group. When providing a scope for the assigment, use '/subscriptions/{subscription-id}/' for subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' for resources.
@param policyAssignmentId The ID of the policy assignment to create. Use the format '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
@param parameters Parameters for policy assignment.
@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 PolicyAssignmentInner object if successful.
"""
return createByIdWithServiceResponseAsync(policyAssignmentId, parameters).toBlocking().single().body();
} | java | public PolicyAssignmentInner createById(String policyAssignmentId, PolicyAssignmentInner parameters) {
return createByIdWithServiceResponseAsync(policyAssignmentId, parameters).toBlocking().single().body();
} | [
"public",
"PolicyAssignmentInner",
"createById",
"(",
"String",
"policyAssignmentId",
",",
"PolicyAssignmentInner",
"parameters",
")",
"{",
"return",
"createByIdWithServiceResponseAsync",
"(",
"policyAssignmentId",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Creates a policy assignment by ID.
Policy assignments are inherited by child resources. For example, when you apply a policy to a resource group that policy is assigned to all resources in the group. When providing a scope for the assigment, use '/subscriptions/{subscription-id}/' for subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' for resources.
@param policyAssignmentId The ID of the policy assignment to create. Use the format '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
@param parameters Parameters for policy assignment.
@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 PolicyAssignmentInner object if successful. | [
"Creates",
"a",
"policy",
"assignment",
"by",
"ID",
".",
"Policy",
"assignments",
"are",
"inherited",
"by",
"child",
"resources",
".",
"For",
"example",
"when",
"you",
"apply",
"a",
"policy",
"to",
"a",
"resource",
"group",
"that",
"policy",
"is",
"assigned",
"to",
"all",
"resources",
"in",
"the",
"group",
".",
"When",
"providing",
"a",
"scope",
"for",
"the",
"assigment",
"use",
"/",
"subscriptions",
"/",
"{",
"subscription",
"-",
"id",
"}",
"/",
"for",
"subscriptions",
"/",
"subscriptions",
"/",
"{",
"subscription",
"-",
"id",
"}",
"/",
"resourceGroups",
"/",
"{",
"resource",
"-",
"group",
"-",
"name",
"}",
"for",
"resource",
"groups",
"and",
"/",
"subscriptions",
"/",
"{",
"subscription",
"-",
"id",
"}",
"/",
"resourceGroups",
"/",
"{",
"resource",
"-",
"group",
"-",
"name",
"}",
"/",
"providers",
"/",
"{",
"resource",
"-",
"provider",
"-",
"namespace",
"}",
"/",
"{",
"resource",
"-",
"type",
"}",
"/",
"{",
"resource",
"-",
"name",
"}",
"for",
"resources",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyAssignmentsInner.java#L1204-L1206 |
bwaldvogel/liblinear-java | src/main/java/de/bwaldvogel/liblinear/Train.java | Train.readProblem | public static Problem readProblem(File file, double bias) throws IOException, InvalidInputDataException {
"""
reads a problem from LibSVM format
@param file the SVM file
@throws IOException obviously in case of any I/O exception ;)
@throws InvalidInputDataException if the input file is not correctly formatted
"""
try (InputStream inputStream = new FileInputStream(file)) {
return readProblem(inputStream, bias);
}
} | java | public static Problem readProblem(File file, double bias) throws IOException, InvalidInputDataException {
try (InputStream inputStream = new FileInputStream(file)) {
return readProblem(inputStream, bias);
}
} | [
"public",
"static",
"Problem",
"readProblem",
"(",
"File",
"file",
",",
"double",
"bias",
")",
"throws",
"IOException",
",",
"InvalidInputDataException",
"{",
"try",
"(",
"InputStream",
"inputStream",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"readProblem",
"(",
"inputStream",
",",
"bias",
")",
";",
"}",
"}"
] | reads a problem from LibSVM format
@param file the SVM file
@throws IOException obviously in case of any I/O exception ;)
@throws InvalidInputDataException if the input file is not correctly formatted | [
"reads",
"a",
"problem",
"from",
"LibSVM",
"format"
] | train | https://github.com/bwaldvogel/liblinear-java/blob/02b228c23a1e3490ba1f703813b09153c8901c2e/src/main/java/de/bwaldvogel/liblinear/Train.java#L269-L273 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java | CharOperation.endsWith | public static final boolean endsWith(char[] array, char[] toBeFound) {
"""
Return true if array ends with the sequence of characters contained in toBeFound, otherwise false. <br>
<br>
For example:
<ol>
<li>
<pre>
array = { 'a', 'b', 'c', 'd' }
toBeFound = { 'b', 'c' }
result => false
</pre>
</li>
<li>
<pre>
array = { 'a', 'b', 'c' }
toBeFound = { 'b', 'c' }
result => true
</pre>
</li>
</ol>
@param array
the array to check
@param toBeFound
the array to find
@return true if array ends with the sequence of characters contained in toBeFound, otherwise false.
@throws NullPointerException
if array is null or toBeFound is null
"""
int i = toBeFound.length;
int j = array.length - i;
if (j < 0)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i + j])
{
return false;
}
}
return true;
} | java | public static final boolean endsWith(char[] array, char[] toBeFound)
{
int i = toBeFound.length;
int j = array.length - i;
if (j < 0)
{
return false;
}
while (--i >= 0)
{
if (toBeFound[i] != array[i + j])
{
return false;
}
}
return true;
} | [
"public",
"static",
"final",
"boolean",
"endsWith",
"(",
"char",
"[",
"]",
"array",
",",
"char",
"[",
"]",
"toBeFound",
")",
"{",
"int",
"i",
"=",
"toBeFound",
".",
"length",
";",
"int",
"j",
"=",
"array",
".",
"length",
"-",
"i",
";",
"if",
"(",
"j",
"<",
"0",
")",
"{",
"return",
"false",
";",
"}",
"while",
"(",
"--",
"i",
">=",
"0",
")",
"{",
"if",
"(",
"toBeFound",
"[",
"i",
"]",
"!=",
"array",
"[",
"i",
"+",
"j",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Return true if array ends with the sequence of characters contained in toBeFound, otherwise false. <br>
<br>
For example:
<ol>
<li>
<pre>
array = { 'a', 'b', 'c', 'd' }
toBeFound = { 'b', 'c' }
result => false
</pre>
</li>
<li>
<pre>
array = { 'a', 'b', 'c' }
toBeFound = { 'b', 'c' }
result => true
</pre>
</li>
</ol>
@param array
the array to check
@param toBeFound
the array to find
@return true if array ends with the sequence of characters contained in toBeFound, otherwise false.
@throws NullPointerException
if array is null or toBeFound is null | [
"Return",
"true",
"if",
"array",
"ends",
"with",
"the",
"sequence",
"of",
"characters",
"contained",
"in",
"toBeFound",
"otherwise",
"false",
".",
"<br",
">",
"<br",
">",
"For",
"example",
":",
"<ol",
">",
"<li",
">"
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/utils/CharOperation.java#L1352-L1369 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d1/dfx/Tuple1dfx.java | Tuple1dfx.set | public void set(Segment1D<?, ?> segment, double curviline, double shift) {
"""
Change the attributes of the tuple.
@param segment the segment.
@param curviline the curviline coordinate.
@param shift the shift distance.
"""
assert segment != null : AssertMessages.notNullParameter(0);
segmentProperty().set(new WeakReference<>(segment));
xProperty().set(curviline);
yProperty().set(shift);
} | java | public void set(Segment1D<?, ?> segment, double curviline, double shift) {
assert segment != null : AssertMessages.notNullParameter(0);
segmentProperty().set(new WeakReference<>(segment));
xProperty().set(curviline);
yProperty().set(shift);
} | [
"public",
"void",
"set",
"(",
"Segment1D",
"<",
"?",
",",
"?",
">",
"segment",
",",
"double",
"curviline",
",",
"double",
"shift",
")",
"{",
"assert",
"segment",
"!=",
"null",
":",
"AssertMessages",
".",
"notNullParameter",
"(",
"0",
")",
";",
"segmentProperty",
"(",
")",
".",
"set",
"(",
"new",
"WeakReference",
"<>",
"(",
"segment",
")",
")",
";",
"xProperty",
"(",
")",
".",
"set",
"(",
"curviline",
")",
";",
"yProperty",
"(",
")",
".",
"set",
"(",
"shift",
")",
";",
"}"
] | Change the attributes of the tuple.
@param segment the segment.
@param curviline the curviline coordinate.
@param shift the shift distance. | [
"Change",
"the",
"attributes",
"of",
"the",
"tuple",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d1/dfx/Tuple1dfx.java#L268-L273 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java | BehaviorTreeLibrary.registerArchetypeTree | public void registerArchetypeTree (String treeReference, BehaviorTree<?> archetypeTree) {
"""
Registers the {@link BehaviorTree} archetypeTree with the specified reference. Existing archetypes in the repository with
the same treeReference will be replaced.
@param treeReference the tree identifier, typically a path.
@param archetypeTree the archetype tree.
@throws IllegalArgumentException if the archetypeTree is null
"""
if (archetypeTree == null) {
throw new IllegalArgumentException("The registered archetype must not be null.");
}
repository.put(treeReference, archetypeTree);
} | java | public void registerArchetypeTree (String treeReference, BehaviorTree<?> archetypeTree) {
if (archetypeTree == null) {
throw new IllegalArgumentException("The registered archetype must not be null.");
}
repository.put(treeReference, archetypeTree);
} | [
"public",
"void",
"registerArchetypeTree",
"(",
"String",
"treeReference",
",",
"BehaviorTree",
"<",
"?",
">",
"archetypeTree",
")",
"{",
"if",
"(",
"archetypeTree",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The registered archetype must not be null.\"",
")",
";",
"}",
"repository",
".",
"put",
"(",
"treeReference",
",",
"archetypeTree",
")",
";",
"}"
] | Registers the {@link BehaviorTree} archetypeTree with the specified reference. Existing archetypes in the repository with
the same treeReference will be replaced.
@param treeReference the tree identifier, typically a path.
@param archetypeTree the archetype tree.
@throws IllegalArgumentException if the archetypeTree is null | [
"Registers",
"the",
"{"
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java#L141-L146 |
Activiti/Activiti | activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/SequentialMultiInstanceBehavior.java | SequentialMultiInstanceBehavior.createInstances | protected int createInstances(DelegateExecution multiInstanceExecution) {
"""
Handles the sequential case of spawning the instances. Will only create one instance, since at most one instance can be active.
"""
int nrOfInstances = resolveNrOfInstances(multiInstanceExecution);
if (nrOfInstances == 0) {
return nrOfInstances;
} else if (nrOfInstances < 0) {
throw new ActivitiIllegalArgumentException("Invalid number of instances: must be a non-negative integer value" + ", but was " + nrOfInstances);
}
// Create child execution that will execute the inner behavior
ExecutionEntity childExecution = Context.getCommandContext().getExecutionEntityManager()
.createChildExecution((ExecutionEntity) multiInstanceExecution);
childExecution.setCurrentFlowElement(multiInstanceExecution.getCurrentFlowElement());
multiInstanceExecution.setMultiInstanceRoot(true);
multiInstanceExecution.setActive(false);
// Set Multi-instance variables
setLoopVariable(multiInstanceExecution, NUMBER_OF_INSTANCES, nrOfInstances);
setLoopVariable(multiInstanceExecution, NUMBER_OF_COMPLETED_INSTANCES, 0);
setLoopVariable(multiInstanceExecution, NUMBER_OF_ACTIVE_INSTANCES, 1);
setLoopVariable(childExecution, getCollectionElementIndexVariable(), 0);
logLoopDetails(multiInstanceExecution, "initialized", 0, 0, 1, nrOfInstances);
if (nrOfInstances > 0) {
executeOriginalBehavior(childExecution, 0);
}
return nrOfInstances;
} | java | protected int createInstances(DelegateExecution multiInstanceExecution) {
int nrOfInstances = resolveNrOfInstances(multiInstanceExecution);
if (nrOfInstances == 0) {
return nrOfInstances;
} else if (nrOfInstances < 0) {
throw new ActivitiIllegalArgumentException("Invalid number of instances: must be a non-negative integer value" + ", but was " + nrOfInstances);
}
// Create child execution that will execute the inner behavior
ExecutionEntity childExecution = Context.getCommandContext().getExecutionEntityManager()
.createChildExecution((ExecutionEntity) multiInstanceExecution);
childExecution.setCurrentFlowElement(multiInstanceExecution.getCurrentFlowElement());
multiInstanceExecution.setMultiInstanceRoot(true);
multiInstanceExecution.setActive(false);
// Set Multi-instance variables
setLoopVariable(multiInstanceExecution, NUMBER_OF_INSTANCES, nrOfInstances);
setLoopVariable(multiInstanceExecution, NUMBER_OF_COMPLETED_INSTANCES, 0);
setLoopVariable(multiInstanceExecution, NUMBER_OF_ACTIVE_INSTANCES, 1);
setLoopVariable(childExecution, getCollectionElementIndexVariable(), 0);
logLoopDetails(multiInstanceExecution, "initialized", 0, 0, 1, nrOfInstances);
if (nrOfInstances > 0) {
executeOriginalBehavior(childExecution, 0);
}
return nrOfInstances;
} | [
"protected",
"int",
"createInstances",
"(",
"DelegateExecution",
"multiInstanceExecution",
")",
"{",
"int",
"nrOfInstances",
"=",
"resolveNrOfInstances",
"(",
"multiInstanceExecution",
")",
";",
"if",
"(",
"nrOfInstances",
"==",
"0",
")",
"{",
"return",
"nrOfInstances",
";",
"}",
"else",
"if",
"(",
"nrOfInstances",
"<",
"0",
")",
"{",
"throw",
"new",
"ActivitiIllegalArgumentException",
"(",
"\"Invalid number of instances: must be a non-negative integer value\"",
"+",
"\", but was \"",
"+",
"nrOfInstances",
")",
";",
"}",
"// Create child execution that will execute the inner behavior",
"ExecutionEntity",
"childExecution",
"=",
"Context",
".",
"getCommandContext",
"(",
")",
".",
"getExecutionEntityManager",
"(",
")",
".",
"createChildExecution",
"(",
"(",
"ExecutionEntity",
")",
"multiInstanceExecution",
")",
";",
"childExecution",
".",
"setCurrentFlowElement",
"(",
"multiInstanceExecution",
".",
"getCurrentFlowElement",
"(",
")",
")",
";",
"multiInstanceExecution",
".",
"setMultiInstanceRoot",
"(",
"true",
")",
";",
"multiInstanceExecution",
".",
"setActive",
"(",
"false",
")",
";",
"// Set Multi-instance variables",
"setLoopVariable",
"(",
"multiInstanceExecution",
",",
"NUMBER_OF_INSTANCES",
",",
"nrOfInstances",
")",
";",
"setLoopVariable",
"(",
"multiInstanceExecution",
",",
"NUMBER_OF_COMPLETED_INSTANCES",
",",
"0",
")",
";",
"setLoopVariable",
"(",
"multiInstanceExecution",
",",
"NUMBER_OF_ACTIVE_INSTANCES",
",",
"1",
")",
";",
"setLoopVariable",
"(",
"childExecution",
",",
"getCollectionElementIndexVariable",
"(",
")",
",",
"0",
")",
";",
"logLoopDetails",
"(",
"multiInstanceExecution",
",",
"\"initialized\"",
",",
"0",
",",
"0",
",",
"1",
",",
"nrOfInstances",
")",
";",
"if",
"(",
"nrOfInstances",
">",
"0",
")",
"{",
"executeOriginalBehavior",
"(",
"childExecution",
",",
"0",
")",
";",
"}",
"return",
"nrOfInstances",
";",
"}"
] | Handles the sequential case of spawning the instances. Will only create one instance, since at most one instance can be active. | [
"Handles",
"the",
"sequential",
"case",
"of",
"spawning",
"the",
"instances",
".",
"Will",
"only",
"create",
"one",
"instance",
"since",
"at",
"most",
"one",
"instance",
"can",
"be",
"active",
"."
] | train | https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/SequentialMultiInstanceBehavior.java#L41-L68 |
beangle/beangle3 | ioc/spring/src/main/java/org/beangle/inject/spring/config/BeanDefinitionParser.java | BeanDefinitionParser.parseLookupOverrideSubElements | public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) {
"""
Parse lookup-override sub-elements of the given bean element.
@param beanEle a {@link org.w3c.dom.Element} object.
@param overrides a {@link org.springframework.beans.factory.support.MethodOverrides} object.
"""
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) {
Element ele = (Element) node;
String methodName = ele.getAttribute(NAME_ATTRIBUTE);
String beanRef = ele.getAttribute(BEAN_ELEMENT);
LookupOverride override = new LookupOverride(methodName, beanRef);
override.setSource(extractSource(ele));
overrides.addOverride(override);
}
}
} | java | public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) {
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) {
Element ele = (Element) node;
String methodName = ele.getAttribute(NAME_ATTRIBUTE);
String beanRef = ele.getAttribute(BEAN_ELEMENT);
LookupOverride override = new LookupOverride(methodName, beanRef);
override.setSource(extractSource(ele));
overrides.addOverride(override);
}
}
} | [
"public",
"void",
"parseLookupOverrideSubElements",
"(",
"Element",
"beanEle",
",",
"MethodOverrides",
"overrides",
")",
"{",
"NodeList",
"nl",
"=",
"beanEle",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nl",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"Node",
"node",
"=",
"nl",
".",
"item",
"(",
"i",
")",
";",
"if",
"(",
"node",
"instanceof",
"Element",
"&&",
"nodeNameEquals",
"(",
"node",
",",
"LOOKUP_METHOD_ELEMENT",
")",
")",
"{",
"Element",
"ele",
"=",
"(",
"Element",
")",
"node",
";",
"String",
"methodName",
"=",
"ele",
".",
"getAttribute",
"(",
"NAME_ATTRIBUTE",
")",
";",
"String",
"beanRef",
"=",
"ele",
".",
"getAttribute",
"(",
"BEAN_ELEMENT",
")",
";",
"LookupOverride",
"override",
"=",
"new",
"LookupOverride",
"(",
"methodName",
",",
"beanRef",
")",
";",
"override",
".",
"setSource",
"(",
"extractSource",
"(",
"ele",
")",
")",
";",
"overrides",
".",
"addOverride",
"(",
"override",
")",
";",
"}",
"}",
"}"
] | Parse lookup-override sub-elements of the given bean element.
@param beanEle a {@link org.w3c.dom.Element} object.
@param overrides a {@link org.springframework.beans.factory.support.MethodOverrides} object. | [
"Parse",
"lookup",
"-",
"override",
"sub",
"-",
"elements",
"of",
"the",
"given",
"bean",
"element",
"."
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/ioc/spring/src/main/java/org/beangle/inject/spring/config/BeanDefinitionParser.java#L422-L435 |
google/error-prone | check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java | ErrorProneScanner.visitParameterizedType | @Override
public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) {
"""
generated by javac to implement autoboxing. We are only interested in source-level constructs.
"""
VisitorState state =
processMatchers(
parameterizedTypeMatchers,
tree,
ParameterizedTypeTreeMatcher::matchParameterizedType,
visitorState);
return super.visitParameterizedType(tree, state);
} | java | @Override
public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) {
VisitorState state =
processMatchers(
parameterizedTypeMatchers,
tree,
ParameterizedTypeTreeMatcher::matchParameterizedType,
visitorState);
return super.visitParameterizedType(tree, state);
} | [
"@",
"Override",
"public",
"Void",
"visitParameterizedType",
"(",
"ParameterizedTypeTree",
"tree",
",",
"VisitorState",
"visitorState",
")",
"{",
"VisitorState",
"state",
"=",
"processMatchers",
"(",
"parameterizedTypeMatchers",
",",
"tree",
",",
"ParameterizedTypeTreeMatcher",
"::",
"matchParameterizedType",
",",
"visitorState",
")",
";",
"return",
"super",
".",
"visitParameterizedType",
"(",
"tree",
",",
"state",
")",
";",
"}"
] | generated by javac to implement autoboxing. We are only interested in source-level constructs. | [
"generated",
"by",
"javac",
"to",
"implement",
"autoboxing",
".",
"We",
"are",
"only",
"interested",
"in",
"source",
"-",
"level",
"constructs",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java#L766-L775 |
pac4j/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/generic/GenericOAuth20ProfileDefinition.java | GenericOAuth20ProfileDefinition.profileAttribute | public void profileAttribute(final String name, String tag, final AttributeConverter<? extends Object> converter) {
"""
Add an attribute as a primary one and its converter.
@param name name of the attribute
@param tag json reference
@param converter converter
"""
profileAttributes.put(name, tag);
if (converter != null) {
getConverters().put(name, converter);
} else {
getConverters().put(name, new StringConverter());
}
} | java | public void profileAttribute(final String name, String tag, final AttributeConverter<? extends Object> converter) {
profileAttributes.put(name, tag);
if (converter != null) {
getConverters().put(name, converter);
} else {
getConverters().put(name, new StringConverter());
}
} | [
"public",
"void",
"profileAttribute",
"(",
"final",
"String",
"name",
",",
"String",
"tag",
",",
"final",
"AttributeConverter",
"<",
"?",
"extends",
"Object",
">",
"converter",
")",
"{",
"profileAttributes",
".",
"put",
"(",
"name",
",",
"tag",
")",
";",
"if",
"(",
"converter",
"!=",
"null",
")",
"{",
"getConverters",
"(",
")",
".",
"put",
"(",
"name",
",",
"converter",
")",
";",
"}",
"else",
"{",
"getConverters",
"(",
")",
".",
"put",
"(",
"name",
",",
"new",
"StringConverter",
"(",
")",
")",
";",
"}",
"}"
] | Add an attribute as a primary one and its converter.
@param name name of the attribute
@param tag json reference
@param converter converter | [
"Add",
"an",
"attribute",
"as",
"a",
"primary",
"one",
"and",
"its",
"converter",
"."
] | train | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/generic/GenericOAuth20ProfileDefinition.java#L105-L112 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-automl/src/main/java/com/google/cloud/automl/v1beta1/AutoMlClient.java | AutoMlClient.createDataset | public final Dataset createDataset(String parent, Dataset dataset) {
"""
Creates a dataset.
<p>Sample code:
<pre><code>
try (AutoMlClient autoMlClient = AutoMlClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Dataset dataset = Dataset.newBuilder().build();
Dataset response = autoMlClient.createDataset(parent.toString(), dataset);
}
</code></pre>
@param parent The resource name of the project to create the dataset for.
@param dataset The dataset to create.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
CreateDatasetRequest request =
CreateDatasetRequest.newBuilder().setParent(parent).setDataset(dataset).build();
return createDataset(request);
} | java | public final Dataset createDataset(String parent, Dataset dataset) {
CreateDatasetRequest request =
CreateDatasetRequest.newBuilder().setParent(parent).setDataset(dataset).build();
return createDataset(request);
} | [
"public",
"final",
"Dataset",
"createDataset",
"(",
"String",
"parent",
",",
"Dataset",
"dataset",
")",
"{",
"CreateDatasetRequest",
"request",
"=",
"CreateDatasetRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
")",
".",
"setDataset",
"(",
"dataset",
")",
".",
"build",
"(",
")",
";",
"return",
"createDataset",
"(",
"request",
")",
";",
"}"
] | Creates a dataset.
<p>Sample code:
<pre><code>
try (AutoMlClient autoMlClient = AutoMlClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Dataset dataset = Dataset.newBuilder().build();
Dataset response = autoMlClient.createDataset(parent.toString(), dataset);
}
</code></pre>
@param parent The resource name of the project to create the dataset for.
@param dataset The dataset to create.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"dataset",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-automl/src/main/java/com/google/cloud/automl/v1beta1/AutoMlClient.java#L231-L236 |
mgm-tp/jfunk | jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java | ConstraintFactory.createModel | public Constraint createModel(final MathRandom random, final Element element) {
"""
Generates an instance based on the data in the given object. The object's class will be
determined by the class attribute of the element. IF the element contains an id attribute the
generated instance is stored in a map using this id as key.
"""
if (element == null) {
return null;
}
Class<? extends Constraint> classObject = null;
Constraint object = null;
try {
classObject = getClassObject(element);
Constructor<? extends Constraint> constructor = getConstructor(classObject);
object = getObject(random, element, constructor);
} catch (InvocationTargetException ex) {
throw new JFunkException("Could not initialise object of class " + classObject, ex.getCause());
} catch (Exception ex) {
throw new JFunkException("Could not initialise object of class " + classObject, ex);
}
putToCache(element, object);
return object;
} | java | public Constraint createModel(final MathRandom random, final Element element) {
if (element == null) {
return null;
}
Class<? extends Constraint> classObject = null;
Constraint object = null;
try {
classObject = getClassObject(element);
Constructor<? extends Constraint> constructor = getConstructor(classObject);
object = getObject(random, element, constructor);
} catch (InvocationTargetException ex) {
throw new JFunkException("Could not initialise object of class " + classObject, ex.getCause());
} catch (Exception ex) {
throw new JFunkException("Could not initialise object of class " + classObject, ex);
}
putToCache(element, object);
return object;
} | [
"public",
"Constraint",
"createModel",
"(",
"final",
"MathRandom",
"random",
",",
"final",
"Element",
"element",
")",
"{",
"if",
"(",
"element",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Class",
"<",
"?",
"extends",
"Constraint",
">",
"classObject",
"=",
"null",
";",
"Constraint",
"object",
"=",
"null",
";",
"try",
"{",
"classObject",
"=",
"getClassObject",
"(",
"element",
")",
";",
"Constructor",
"<",
"?",
"extends",
"Constraint",
">",
"constructor",
"=",
"getConstructor",
"(",
"classObject",
")",
";",
"object",
"=",
"getObject",
"(",
"random",
",",
"element",
",",
"constructor",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"ex",
")",
"{",
"throw",
"new",
"JFunkException",
"(",
"\"Could not initialise object of class \"",
"+",
"classObject",
",",
"ex",
".",
"getCause",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"JFunkException",
"(",
"\"Could not initialise object of class \"",
"+",
"classObject",
",",
"ex",
")",
";",
"}",
"putToCache",
"(",
"element",
",",
"object",
")",
";",
"return",
"object",
";",
"}"
] | Generates an instance based on the data in the given object. The object's class will be
determined by the class attribute of the element. IF the element contains an id attribute the
generated instance is stored in a map using this id as key. | [
"Generates",
"an",
"instance",
"based",
"on",
"the",
"data",
"in",
"the",
"given",
"object",
".",
"The",
"object",
"s",
"class",
"will",
"be",
"determined",
"by",
"the",
"class",
"attribute",
"of",
"the",
"element",
".",
"IF",
"the",
"element",
"contains",
"an",
"id",
"attribute",
"the",
"generated",
"instance",
"is",
"stored",
"in",
"a",
"map",
"using",
"this",
"id",
"as",
"key",
"."
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java#L62-L79 |
jbundle/jbundle | thin/opt/chat/src/main/java/org/jbundle/thin/opt/chat/ChatScreen.java | ChatScreen.doAction | public boolean doAction(String strAction, int iOptions) {
"""
Process this action.
@param strAction The action to process.
By default, this method handles RESET, SUBMIT, and DELETE.
"""
if (SEND.equalsIgnoreCase(strAction))
{
String strMessage = m_tfTextIn.getText();
m_tfTextIn.setText(Constants.BLANK);
Map<String,Object> properties = new Hashtable<String,Object>();
properties.put(MESSAGE_PARAM, strMessage);
BaseMessage message = new MapMessage(new BaseMessageHeader(CHAT_TYPE, MessageConstants.INTRANET_QUEUE, null, null), properties);
this.getBaseApplet().getApplication().getMessageManager().sendMessage(message);
return true;
}
return super.doAction(strAction, iOptions);
} | java | public boolean doAction(String strAction, int iOptions)
{
if (SEND.equalsIgnoreCase(strAction))
{
String strMessage = m_tfTextIn.getText();
m_tfTextIn.setText(Constants.BLANK);
Map<String,Object> properties = new Hashtable<String,Object>();
properties.put(MESSAGE_PARAM, strMessage);
BaseMessage message = new MapMessage(new BaseMessageHeader(CHAT_TYPE, MessageConstants.INTRANET_QUEUE, null, null), properties);
this.getBaseApplet().getApplication().getMessageManager().sendMessage(message);
return true;
}
return super.doAction(strAction, iOptions);
} | [
"public",
"boolean",
"doAction",
"(",
"String",
"strAction",
",",
"int",
"iOptions",
")",
"{",
"if",
"(",
"SEND",
".",
"equalsIgnoreCase",
"(",
"strAction",
")",
")",
"{",
"String",
"strMessage",
"=",
"m_tfTextIn",
".",
"getText",
"(",
")",
";",
"m_tfTextIn",
".",
"setText",
"(",
"Constants",
".",
"BLANK",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
"=",
"new",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"properties",
".",
"put",
"(",
"MESSAGE_PARAM",
",",
"strMessage",
")",
";",
"BaseMessage",
"message",
"=",
"new",
"MapMessage",
"(",
"new",
"BaseMessageHeader",
"(",
"CHAT_TYPE",
",",
"MessageConstants",
".",
"INTRANET_QUEUE",
",",
"null",
",",
"null",
")",
",",
"properties",
")",
";",
"this",
".",
"getBaseApplet",
"(",
")",
".",
"getApplication",
"(",
")",
".",
"getMessageManager",
"(",
")",
".",
"sendMessage",
"(",
"message",
")",
";",
"return",
"true",
";",
"}",
"return",
"super",
".",
"doAction",
"(",
"strAction",
",",
"iOptions",
")",
";",
"}"
] | Process this action.
@param strAction The action to process.
By default, this method handles RESET, SUBMIT, and DELETE. | [
"Process",
"this",
"action",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/opt/chat/src/main/java/org/jbundle/thin/opt/chat/ChatScreen.java#L161-L175 |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/GeoParserFactory.java | GeoParserFactory.getDefault | public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow) throws ClavinException {
"""
Get a GeoParser with defined values for maxHitDepth and
maxContentWindow.
@param pathToLuceneIndex Path to the local Lucene index.
@param maxHitDepth Number of candidate matches to consider
@param maxContentWindow How much context to consider when resolving
@return GeoParser
@throws ClavinException If the index cannot be created.
"""
return getDefault(pathToLuceneIndex, maxHitDepth, maxContentWindow, false);
} | java | public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow) throws ClavinException {
return getDefault(pathToLuceneIndex, maxHitDepth, maxContentWindow, false);
} | [
"public",
"static",
"GeoParser",
"getDefault",
"(",
"String",
"pathToLuceneIndex",
",",
"int",
"maxHitDepth",
",",
"int",
"maxContentWindow",
")",
"throws",
"ClavinException",
"{",
"return",
"getDefault",
"(",
"pathToLuceneIndex",
",",
"maxHitDepth",
",",
"maxContentWindow",
",",
"false",
")",
";",
"}"
] | Get a GeoParser with defined values for maxHitDepth and
maxContentWindow.
@param pathToLuceneIndex Path to the local Lucene index.
@param maxHitDepth Number of candidate matches to consider
@param maxContentWindow How much context to consider when resolving
@return GeoParser
@throws ClavinException If the index cannot be created. | [
"Get",
"a",
"GeoParser",
"with",
"defined",
"values",
"for",
"maxHitDepth",
"and",
"maxContentWindow",
"."
] | train | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParserFactory.java#L79-L81 |
trustathsh/ifmapj | src/main/java/util/CanonicalXML.java | CanonicalXML.endElement | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
"""
Receive notification of the end of an element.
<p/>
<p>By default, do nothing. Application writers may override this
method in a subclass to take specific actions at the end of
each element (such as finalising a tree node or writing
output to a file).</p>
@param uri The Namespace URI, or the empty string if the
element has no Namespace URI or if Namespace
processing is not being performed.
@param localName The local name (without prefix), or the
empty string if Namespace processing is not being
performed.
@param qName The qualified name (with prefix), or the
empty string if qualified names are not available.
@throws org.xml.sax.SAXException Any SAX exception, possibly
wrapping another exception.
@see org.xml.sax.ContentHandler#endElement
"""
flushChars();
write("</");
write(qName);
write(">");
} | java | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
flushChars();
write("</");
write(qName);
write(">");
} | [
"@",
"Override",
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"flushChars",
"(",
")",
";",
"write",
"(",
"\"</\"",
")",
";",
"write",
"(",
"qName",
")",
";",
"write",
"(",
"\">\"",
")",
";",
"}"
] | Receive notification of the end of an element.
<p/>
<p>By default, do nothing. Application writers may override this
method in a subclass to take specific actions at the end of
each element (such as finalising a tree node or writing
output to a file).</p>
@param uri The Namespace URI, or the empty string if the
element has no Namespace URI or if Namespace
processing is not being performed.
@param localName The local name (without prefix), or the
empty string if Namespace processing is not being
performed.
@param qName The qualified name (with prefix), or the
empty string if qualified names are not available.
@throws org.xml.sax.SAXException Any SAX exception, possibly
wrapping another exception.
@see org.xml.sax.ContentHandler#endElement | [
"Receive",
"notification",
"of",
"the",
"end",
"of",
"an",
"element",
".",
"<p",
"/",
">",
"<p",
">",
"By",
"default",
"do",
"nothing",
".",
"Application",
"writers",
"may",
"override",
"this",
"method",
"in",
"a",
"subclass",
"to",
"take",
"specific",
"actions",
"at",
"the",
"end",
"of",
"each",
"element",
"(",
"such",
"as",
"finalising",
"a",
"tree",
"node",
"or",
"writing",
"output",
"to",
"a",
"file",
")",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/util/CanonicalXML.java#L342-L348 |
overturetool/overture | core/interpreter/src/main/java/org/overture/interpreter/runtime/ClassInterpreter.java | ClassInterpreter.execute | @Override
public Value execute(String line, DBGPReader dbgp) throws Exception {
"""
Parse the line passed, type check it and evaluate it as an expression in the initial context.
@param line
A VDM expression.
@return The value of the expression.
@throws Exception
Parser, type checking or runtime errors.
"""
PExp expr = parseExpression(line, getDefaultName());
Environment env = getGlobalEnvironment();
Environment created = new FlatCheckedEnvironment(assistantFactory, createdDefinitions.asList(), env, NameScope.NAMESANDSTATE);
typeCheck(expr, created);
return execute(expr, dbgp);
} | java | @Override
public Value execute(String line, DBGPReader dbgp) throws Exception
{
PExp expr = parseExpression(line, getDefaultName());
Environment env = getGlobalEnvironment();
Environment created = new FlatCheckedEnvironment(assistantFactory, createdDefinitions.asList(), env, NameScope.NAMESANDSTATE);
typeCheck(expr, created);
return execute(expr, dbgp);
} | [
"@",
"Override",
"public",
"Value",
"execute",
"(",
"String",
"line",
",",
"DBGPReader",
"dbgp",
")",
"throws",
"Exception",
"{",
"PExp",
"expr",
"=",
"parseExpression",
"(",
"line",
",",
"getDefaultName",
"(",
")",
")",
";",
"Environment",
"env",
"=",
"getGlobalEnvironment",
"(",
")",
";",
"Environment",
"created",
"=",
"new",
"FlatCheckedEnvironment",
"(",
"assistantFactory",
",",
"createdDefinitions",
".",
"asList",
"(",
")",
",",
"env",
",",
"NameScope",
".",
"NAMESANDSTATE",
")",
";",
"typeCheck",
"(",
"expr",
",",
"created",
")",
";",
"return",
"execute",
"(",
"expr",
",",
"dbgp",
")",
";",
"}"
] | Parse the line passed, type check it and evaluate it as an expression in the initial context.
@param line
A VDM expression.
@return The value of the expression.
@throws Exception
Parser, type checking or runtime errors. | [
"Parse",
"the",
"line",
"passed",
"type",
"check",
"it",
"and",
"evaluate",
"it",
"as",
"an",
"expression",
"in",
"the",
"initial",
"context",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/ClassInterpreter.java#L282-L291 |
joniles/mpxj | src/main/java/net/sf/mpxj/asta/AstaReader.java | AstaReader.populateLeaf | private void populateLeaf(String parentName, Row row, Task task) {
"""
Adds a leaf node, which could be a task or a milestone.
@param parentName parent bar name
@param row row to add
@param task task to populate with data from the row
"""
if (row.getInteger("TASKID") != null)
{
populateTask(row, task);
}
else
{
populateMilestone(row, task);
}
String name = task.getName();
if (name == null || name.isEmpty())
{
task.setName(parentName);
}
} | java | private void populateLeaf(String parentName, Row row, Task task)
{
if (row.getInteger("TASKID") != null)
{
populateTask(row, task);
}
else
{
populateMilestone(row, task);
}
String name = task.getName();
if (name == null || name.isEmpty())
{
task.setName(parentName);
}
} | [
"private",
"void",
"populateLeaf",
"(",
"String",
"parentName",
",",
"Row",
"row",
",",
"Task",
"task",
")",
"{",
"if",
"(",
"row",
".",
"getInteger",
"(",
"\"TASKID\"",
")",
"!=",
"null",
")",
"{",
"populateTask",
"(",
"row",
",",
"task",
")",
";",
"}",
"else",
"{",
"populateMilestone",
"(",
"row",
",",
"task",
")",
";",
"}",
"String",
"name",
"=",
"task",
".",
"getName",
"(",
")",
";",
"if",
"(",
"name",
"==",
"null",
"||",
"name",
".",
"isEmpty",
"(",
")",
")",
"{",
"task",
".",
"setName",
"(",
"parentName",
")",
";",
"}",
"}"
] | Adds a leaf node, which could be a task or a milestone.
@param parentName parent bar name
@param row row to add
@param task task to populate with data from the row | [
"Adds",
"a",
"leaf",
"node",
"which",
"could",
"be",
"a",
"task",
"or",
"a",
"milestone",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/asta/AstaReader.java#L384-L400 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java | ComboBoxArrowButtonPainter.paintArrowDown | private void paintArrowDown(Graphics2D g, JComponent c, int width, int height) {
"""
DOCUMENT ME!
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param width the width.
@param height the height.
"""
int xOffset = width / 2 - 3;
int yOffset = height / 2 - 5;
g.translate(xOffset, yOffset);
Shape s = shapeGenerator.createArrowLeft(1, 1, 4.2, 6);
g.setPaint(getCommonArrowPaint(s, type));
g.fill(s);
g.translate(-xOffset, -yOffset);
} | java | private void paintArrowDown(Graphics2D g, JComponent c, int width, int height) {
int xOffset = width / 2 - 3;
int yOffset = height / 2 - 5;
g.translate(xOffset, yOffset);
Shape s = shapeGenerator.createArrowLeft(1, 1, 4.2, 6);
g.setPaint(getCommonArrowPaint(s, type));
g.fill(s);
g.translate(-xOffset, -yOffset);
} | [
"private",
"void",
"paintArrowDown",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"int",
"xOffset",
"=",
"width",
"/",
"2",
"-",
"3",
";",
"int",
"yOffset",
"=",
"height",
"/",
"2",
"-",
"5",
";",
"g",
".",
"translate",
"(",
"xOffset",
",",
"yOffset",
")",
";",
"Shape",
"s",
"=",
"shapeGenerator",
".",
"createArrowLeft",
"(",
"1",
",",
"1",
",",
"4.2",
",",
"6",
")",
";",
"g",
".",
"setPaint",
"(",
"getCommonArrowPaint",
"(",
"s",
",",
"type",
")",
")",
";",
"g",
".",
"fill",
"(",
"s",
")",
";",
"g",
".",
"translate",
"(",
"-",
"xOffset",
",",
"-",
"yOffset",
")",
";",
"}"
] | DOCUMENT ME!
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param width the width.
@param height the height. | [
"DOCUMENT",
"ME!"
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java#L192-L204 |
huahin/huahin-core | src/main/java/org/huahinframework/core/util/StringUtil.java | StringUtil.getMatchNo | public static int getMatchNo(String[] strings, String s) {
"""
get match string number
@param strings strings
@param s match string
@return match string number
"""
for (int i = 0; i < strings.length; i++) {
if (s.equals(strings[i])) {
return i;
}
}
return -1;
} | java | public static int getMatchNo(String[] strings, String s) {
for (int i = 0; i < strings.length; i++) {
if (s.equals(strings[i])) {
return i;
}
}
return -1;
} | [
"public",
"static",
"int",
"getMatchNo",
"(",
"String",
"[",
"]",
"strings",
",",
"String",
"s",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"strings",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"s",
".",
"equals",
"(",
"strings",
"[",
"i",
"]",
")",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | get match string number
@param strings strings
@param s match string
@return match string number | [
"get",
"match",
"string",
"number"
] | train | https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/util/StringUtil.java#L118-L125 |
qatools/properties | src/main/java/ru/qatools/properties/utils/PropsReplacer.java | PropsReplacer.replaceProps | private String replaceProps(String pattern, String path, Properties properties) {
"""
Replace properties in given path using pattern
@param pattern - pattern to replace. First group should contains property name
@param path - given path to replace in
@param properties - list of properties using to replace
@return path with replaced properties
"""
Matcher matcher = Pattern.compile(pattern).matcher(path);
String replaced = path;
while (matcher.find()) {
replaced = replaced.replace(matcher.group(0), properties.getProperty(matcher.group(1), ""));
}
return replaced;
} | java | private String replaceProps(String pattern, String path, Properties properties) {
Matcher matcher = Pattern.compile(pattern).matcher(path);
String replaced = path;
while (matcher.find()) {
replaced = replaced.replace(matcher.group(0), properties.getProperty(matcher.group(1), ""));
}
return replaced;
} | [
"private",
"String",
"replaceProps",
"(",
"String",
"pattern",
",",
"String",
"path",
",",
"Properties",
"properties",
")",
"{",
"Matcher",
"matcher",
"=",
"Pattern",
".",
"compile",
"(",
"pattern",
")",
".",
"matcher",
"(",
"path",
")",
";",
"String",
"replaced",
"=",
"path",
";",
"while",
"(",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"replaced",
"=",
"replaced",
".",
"replace",
"(",
"matcher",
".",
"group",
"(",
"0",
")",
",",
"properties",
".",
"getProperty",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
",",
"\"\"",
")",
")",
";",
"}",
"return",
"replaced",
";",
"}"
] | Replace properties in given path using pattern
@param pattern - pattern to replace. First group should contains property name
@param path - given path to replace in
@param properties - list of properties using to replace
@return path with replaced properties | [
"Replace",
"properties",
"in",
"given",
"path",
"using",
"pattern"
] | train | https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/utils/PropsReplacer.java#L45-L52 |
mozilla/rhino | src/org/mozilla/javascript/Parser.java | Parser.attributeAccess | private AstNode attributeAccess()
throws IOException {
"""
Xml attribute expression:<p>
{@code @attr}, {@code @ns::attr}, {@code @ns::*}, {@code @ns::*},
{@code @*}, {@code @*::attr}, {@code @*::*}, {@code @ns::[expr]},
{@code @*::[expr]}, {@code @[expr]} <p>
Called if we peeked an '@' token.
"""
int tt = nextToken(), atPos = ts.tokenBeg;
switch (tt) {
// handles: @name, @ns::name, @ns::*, @ns::[expr]
case Token.NAME:
return propertyName(atPos, ts.getString(), 0);
// handles: @*, @*::name, @*::*, @*::[expr]
case Token.MUL:
saveNameTokenData(ts.tokenBeg, "*", ts.lineno);
return propertyName(atPos, "*", 0);
// handles @[expr]
case Token.LB:
return xmlElemRef(atPos, null, -1);
default:
reportError("msg.no.name.after.xmlAttr");
return makeErrorNode();
}
} | java | private AstNode attributeAccess()
throws IOException
{
int tt = nextToken(), atPos = ts.tokenBeg;
switch (tt) {
// handles: @name, @ns::name, @ns::*, @ns::[expr]
case Token.NAME:
return propertyName(atPos, ts.getString(), 0);
// handles: @*, @*::name, @*::*, @*::[expr]
case Token.MUL:
saveNameTokenData(ts.tokenBeg, "*", ts.lineno);
return propertyName(atPos, "*", 0);
// handles @[expr]
case Token.LB:
return xmlElemRef(atPos, null, -1);
default:
reportError("msg.no.name.after.xmlAttr");
return makeErrorNode();
}
} | [
"private",
"AstNode",
"attributeAccess",
"(",
")",
"throws",
"IOException",
"{",
"int",
"tt",
"=",
"nextToken",
"(",
")",
",",
"atPos",
"=",
"ts",
".",
"tokenBeg",
";",
"switch",
"(",
"tt",
")",
"{",
"// handles: @name, @ns::name, @ns::*, @ns::[expr]",
"case",
"Token",
".",
"NAME",
":",
"return",
"propertyName",
"(",
"atPos",
",",
"ts",
".",
"getString",
"(",
")",
",",
"0",
")",
";",
"// handles: @*, @*::name, @*::*, @*::[expr]",
"case",
"Token",
".",
"MUL",
":",
"saveNameTokenData",
"(",
"ts",
".",
"tokenBeg",
",",
"\"*\"",
",",
"ts",
".",
"lineno",
")",
";",
"return",
"propertyName",
"(",
"atPos",
",",
"\"*\"",
",",
"0",
")",
";",
"// handles @[expr]",
"case",
"Token",
".",
"LB",
":",
"return",
"xmlElemRef",
"(",
"atPos",
",",
"null",
",",
"-",
"1",
")",
";",
"default",
":",
"reportError",
"(",
"\"msg.no.name.after.xmlAttr\"",
")",
";",
"return",
"makeErrorNode",
"(",
")",
";",
"}",
"}"
] | Xml attribute expression:<p>
{@code @attr}, {@code @ns::attr}, {@code @ns::*}, {@code @ns::*},
{@code @*}, {@code @*::attr}, {@code @*::*}, {@code @ns::[expr]},
{@code @*::[expr]}, {@code @[expr]} <p>
Called if we peeked an '@' token. | [
"Xml",
"attribute",
"expression",
":",
"<p",
">",
"{"
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/Parser.java#L2976-L2999 |
apiman/apiman | manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java | EsMarshalling.unmarshallOrganizationSummary | public static OrganizationSummaryBean unmarshallOrganizationSummary(Map<String, Object> source) {
"""
Unmarshals the given map source into a bean.
@param source the source
@return the organization summary
"""
if (source == null) {
return null;
}
OrganizationSummaryBean bean = new OrganizationSummaryBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
postMarshall(bean);
return bean;
} | java | public static OrganizationSummaryBean unmarshallOrganizationSummary(Map<String, Object> source) {
if (source == null) {
return null;
}
OrganizationSummaryBean bean = new OrganizationSummaryBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
postMarshall(bean);
return bean;
} | [
"public",
"static",
"OrganizationSummaryBean",
"unmarshallOrganizationSummary",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"OrganizationSummaryBean",
"bean",
"=",
"new",
"OrganizationSummaryBean",
"(",
")",
";",
"bean",
".",
"setId",
"(",
"asString",
"(",
"source",
".",
"get",
"(",
"\"id\"",
")",
")",
")",
";",
"bean",
".",
"setName",
"(",
"asString",
"(",
"source",
".",
"get",
"(",
"\"name\"",
")",
")",
")",
";",
"bean",
".",
"setDescription",
"(",
"asString",
"(",
"source",
".",
"get",
"(",
"\"description\"",
")",
")",
")",
";",
"postMarshall",
"(",
"bean",
")",
";",
"return",
"bean",
";",
"}"
] | Unmarshals the given map source into a bean.
@param source the source
@return the organization summary | [
"Unmarshals",
"the",
"given",
"map",
"source",
"into",
"a",
"bean",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1173-L1183 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java | StitchingFromMotion2D.resizeStitchImage | public void resizeStitchImage( int widthStitch, int heightStitch , IT newToOldStitch ) {
"""
Resizes the stitch image. If no transform is provided then the old stitch region is simply
places on top of the new one and copied. Pixels which do not exist in the old image are filled with zero.
@param widthStitch The new width of the stitch image.
@param heightStitch The new height of the stitch image.
@param newToOldStitch (Optional) Transform from new stitch image pixels to old stick pixels. Can be null.
"""
// copy the old image into the new one
workImage.reshape(widthStitch,heightStitch);
GImageMiscOps.fill(workImage, 0);
if( newToOldStitch != null ) {
PixelTransform<Point2D_F32> newToOld = converter.convertPixel(newToOldStitch,null);
distorter.setModel(newToOld);
distorter.apply(stitchedImage, workImage);
// update the transforms
IT tmp = (IT)worldToCurr.createInstance();
newToOldStitch.concat(worldToInit, tmp);
worldToInit.set(tmp);
computeCurrToInit_PixelTran();
} else {
int overlapWidth = Math.min(widthStitch,stitchedImage.width);
int overlapHeight = Math.min(heightStitch,stitchedImage.height);
GImageMiscOps.copy(0,0,0,0,overlapWidth,overlapHeight,stitchedImage,workImage);
}
stitchedImage.reshape(widthStitch,heightStitch);
I tmp = stitchedImage;
stitchedImage = workImage;
workImage = tmp;
this.widthStitch = widthStitch;
this.heightStitch = heightStitch;
} | java | public void resizeStitchImage( int widthStitch, int heightStitch , IT newToOldStitch ) {
// copy the old image into the new one
workImage.reshape(widthStitch,heightStitch);
GImageMiscOps.fill(workImage, 0);
if( newToOldStitch != null ) {
PixelTransform<Point2D_F32> newToOld = converter.convertPixel(newToOldStitch,null);
distorter.setModel(newToOld);
distorter.apply(stitchedImage, workImage);
// update the transforms
IT tmp = (IT)worldToCurr.createInstance();
newToOldStitch.concat(worldToInit, tmp);
worldToInit.set(tmp);
computeCurrToInit_PixelTran();
} else {
int overlapWidth = Math.min(widthStitch,stitchedImage.width);
int overlapHeight = Math.min(heightStitch,stitchedImage.height);
GImageMiscOps.copy(0,0,0,0,overlapWidth,overlapHeight,stitchedImage,workImage);
}
stitchedImage.reshape(widthStitch,heightStitch);
I tmp = stitchedImage;
stitchedImage = workImage;
workImage = tmp;
this.widthStitch = widthStitch;
this.heightStitch = heightStitch;
} | [
"public",
"void",
"resizeStitchImage",
"(",
"int",
"widthStitch",
",",
"int",
"heightStitch",
",",
"IT",
"newToOldStitch",
")",
"{",
"// copy the old image into the new one",
"workImage",
".",
"reshape",
"(",
"widthStitch",
",",
"heightStitch",
")",
";",
"GImageMiscOps",
".",
"fill",
"(",
"workImage",
",",
"0",
")",
";",
"if",
"(",
"newToOldStitch",
"!=",
"null",
")",
"{",
"PixelTransform",
"<",
"Point2D_F32",
">",
"newToOld",
"=",
"converter",
".",
"convertPixel",
"(",
"newToOldStitch",
",",
"null",
")",
";",
"distorter",
".",
"setModel",
"(",
"newToOld",
")",
";",
"distorter",
".",
"apply",
"(",
"stitchedImage",
",",
"workImage",
")",
";",
"// update the transforms",
"IT",
"tmp",
"=",
"(",
"IT",
")",
"worldToCurr",
".",
"createInstance",
"(",
")",
";",
"newToOldStitch",
".",
"concat",
"(",
"worldToInit",
",",
"tmp",
")",
";",
"worldToInit",
".",
"set",
"(",
"tmp",
")",
";",
"computeCurrToInit_PixelTran",
"(",
")",
";",
"}",
"else",
"{",
"int",
"overlapWidth",
"=",
"Math",
".",
"min",
"(",
"widthStitch",
",",
"stitchedImage",
".",
"width",
")",
";",
"int",
"overlapHeight",
"=",
"Math",
".",
"min",
"(",
"heightStitch",
",",
"stitchedImage",
".",
"height",
")",
";",
"GImageMiscOps",
".",
"copy",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"overlapWidth",
",",
"overlapHeight",
",",
"stitchedImage",
",",
"workImage",
")",
";",
"}",
"stitchedImage",
".",
"reshape",
"(",
"widthStitch",
",",
"heightStitch",
")",
";",
"I",
"tmp",
"=",
"stitchedImage",
";",
"stitchedImage",
"=",
"workImage",
";",
"workImage",
"=",
"tmp",
";",
"this",
".",
"widthStitch",
"=",
"widthStitch",
";",
"this",
".",
"heightStitch",
"=",
"heightStitch",
";",
"}"
] | Resizes the stitch image. If no transform is provided then the old stitch region is simply
places on top of the new one and copied. Pixels which do not exist in the old image are filled with zero.
@param widthStitch The new width of the stitch image.
@param heightStitch The new height of the stitch image.
@param newToOldStitch (Optional) Transform from new stitch image pixels to old stick pixels. Can be null. | [
"Resizes",
"the",
"stitch",
"image",
".",
"If",
"no",
"transform",
"is",
"provided",
"then",
"the",
"old",
"stitch",
"region",
"is",
"simply",
"places",
"on",
"top",
"of",
"the",
"new",
"one",
"and",
"copied",
".",
"Pixels",
"which",
"do",
"not",
"exist",
"in",
"the",
"old",
"image",
"are",
"filled",
"with",
"zero",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java#L264-L292 |
JDBDT/jdbdt | src/main/java/org/jdbdt/DBSetup.java | DBSetup.doInsert | private static void doInsert(CallInfo callInfo, Table table, DataSet data) {
"""
Utility method to perform actual data insertion.
@param callInfo Call Info.
@param table Table.
@param data Data set.
"""
StringBuilder sql = new StringBuilder("INSERT INTO ");
List<String> tableColumns = table.getColumns();
int columnCount = tableColumns.size();
int[] paramIdx = new int[columnCount];
int param = 0;
Iterator<String> itr = tableColumns.iterator();
String col = itr.next();
paramIdx[param] = ++param;
sql.append(table.getName())
.append('(')
.append(col);
while (itr.hasNext()) {
paramIdx[param] = ++param;
col = itr.next();
sql.append(',')
.append(col);
}
sql.append(") VALUES (?");
for (int i=1; i < columnCount; i++) {
sql.append(",?");
}
sql.append(')');
dataSetOperation(callInfo, table, data, sql.toString(), paramIdx);
} | java | private static void doInsert(CallInfo callInfo, Table table, DataSet data) {
StringBuilder sql = new StringBuilder("INSERT INTO ");
List<String> tableColumns = table.getColumns();
int columnCount = tableColumns.size();
int[] paramIdx = new int[columnCount];
int param = 0;
Iterator<String> itr = tableColumns.iterator();
String col = itr.next();
paramIdx[param] = ++param;
sql.append(table.getName())
.append('(')
.append(col);
while (itr.hasNext()) {
paramIdx[param] = ++param;
col = itr.next();
sql.append(',')
.append(col);
}
sql.append(") VALUES (?");
for (int i=1; i < columnCount; i++) {
sql.append(",?");
}
sql.append(')');
dataSetOperation(callInfo, table, data, sql.toString(), paramIdx);
} | [
"private",
"static",
"void",
"doInsert",
"(",
"CallInfo",
"callInfo",
",",
"Table",
"table",
",",
"DataSet",
"data",
")",
"{",
"StringBuilder",
"sql",
"=",
"new",
"StringBuilder",
"(",
"\"INSERT INTO \"",
")",
";",
"List",
"<",
"String",
">",
"tableColumns",
"=",
"table",
".",
"getColumns",
"(",
")",
";",
"int",
"columnCount",
"=",
"tableColumns",
".",
"size",
"(",
")",
";",
"int",
"[",
"]",
"paramIdx",
"=",
"new",
"int",
"[",
"columnCount",
"]",
";",
"int",
"param",
"=",
"0",
";",
"Iterator",
"<",
"String",
">",
"itr",
"=",
"tableColumns",
".",
"iterator",
"(",
")",
";",
"String",
"col",
"=",
"itr",
".",
"next",
"(",
")",
";",
"paramIdx",
"[",
"param",
"]",
"=",
"++",
"param",
";",
"sql",
".",
"append",
"(",
"table",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"col",
")",
";",
"while",
"(",
"itr",
".",
"hasNext",
"(",
")",
")",
"{",
"paramIdx",
"[",
"param",
"]",
"=",
"++",
"param",
";",
"col",
"=",
"itr",
".",
"next",
"(",
")",
";",
"sql",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"col",
")",
";",
"}",
"sql",
".",
"append",
"(",
"\") VALUES (?\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"columnCount",
";",
"i",
"++",
")",
"{",
"sql",
".",
"append",
"(",
"\",?\"",
")",
";",
"}",
"sql",
".",
"append",
"(",
"'",
"'",
")",
";",
"dataSetOperation",
"(",
"callInfo",
",",
"table",
",",
"data",
",",
"sql",
".",
"toString",
"(",
")",
",",
"paramIdx",
")",
";",
"}"
] | Utility method to perform actual data insertion.
@param callInfo Call Info.
@param table Table.
@param data Data set. | [
"Utility",
"method",
"to",
"perform",
"actual",
"data",
"insertion",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/DBSetup.java#L106-L133 |
bazaarvoice/emodb | common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java | BufferUtils.getString | public static String getString(ByteBuffer buf, Charset encoding) {
"""
Converts all remaining bytes in the buffer a String using the specified encoding.
Does not move the buffer position.
"""
return getString(buf, 0, buf.remaining(), encoding);
} | java | public static String getString(ByteBuffer buf, Charset encoding) {
return getString(buf, 0, buf.remaining(), encoding);
} | [
"public",
"static",
"String",
"getString",
"(",
"ByteBuffer",
"buf",
",",
"Charset",
"encoding",
")",
"{",
"return",
"getString",
"(",
"buf",
",",
"0",
",",
"buf",
".",
"remaining",
"(",
")",
",",
"encoding",
")",
";",
"}"
] | Converts all remaining bytes in the buffer a String using the specified encoding.
Does not move the buffer position. | [
"Converts",
"all",
"remaining",
"bytes",
"in",
"the",
"buffer",
"a",
"String",
"using",
"the",
"specified",
"encoding",
".",
"Does",
"not",
"move",
"the",
"buffer",
"position",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java#L14-L16 |
phax/ph-schedule | ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java | JDK8TriggerBuilder.usingJobData | @Nonnull
public JDK8TriggerBuilder <T> usingJobData (final String dataKey, final int value) {
"""
Add the given key-value pair to the Trigger's {@link JobDataMap}.
@param dataKey
Job data key.
@param value
Job data value
@return the updated JDK8TriggerBuilder
@see ITrigger#getJobDataMap()
"""
return usingJobData (dataKey, Integer.valueOf (value));
} | java | @Nonnull
public JDK8TriggerBuilder <T> usingJobData (final String dataKey, final int value)
{
return usingJobData (dataKey, Integer.valueOf (value));
} | [
"@",
"Nonnull",
"public",
"JDK8TriggerBuilder",
"<",
"T",
">",
"usingJobData",
"(",
"final",
"String",
"dataKey",
",",
"final",
"int",
"value",
")",
"{",
"return",
"usingJobData",
"(",
"dataKey",
",",
"Integer",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Add the given key-value pair to the Trigger's {@link JobDataMap}.
@param dataKey
Job data key.
@param value
Job data value
@return the updated JDK8TriggerBuilder
@see ITrigger#getJobDataMap() | [
"Add",
"the",
"given",
"key",
"-",
"value",
"pair",
"to",
"the",
"Trigger",
"s",
"{",
"@link",
"JobDataMap",
"}",
"."
] | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java#L405-L409 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_account_accountName_filter_name_GET | public OvhFilter domain_account_accountName_filter_name_GET(String domain, String accountName, String name) throws IOException {
"""
Get this object properties
REST: GET /email/domain/{domain}/account/{accountName}/filter/{name}
@param domain [required] Name of your domain name
@param accountName [required] Name of account
@param name [required] Filter name
"""
String qPath = "/email/domain/{domain}/account/{accountName}/filter/{name}";
StringBuilder sb = path(qPath, domain, accountName, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | java | public OvhFilter domain_account_accountName_filter_name_GET(String domain, String accountName, String name) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}/filter/{name}";
StringBuilder sb = path(qPath, domain, accountName, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | [
"public",
"OvhFilter",
"domain_account_accountName_filter_name_GET",
"(",
"String",
"domain",
",",
"String",
"accountName",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/account/{accountName}/filter/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"domain",
",",
"accountName",
",",
"name",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhFilter",
".",
"class",
")",
";",
"}"
] | Get this object properties
REST: GET /email/domain/{domain}/account/{accountName}/filter/{name}
@param domain [required] Name of your domain name
@param accountName [required] Name of account
@param name [required] Filter name | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L754-L759 |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java | StringUtil.toStringArray | public static String[] toStringArray(String pString, String pDelimiters) {
"""
Converts a delimiter separated String to an array of Strings.
@param pString The comma-separated string
@param pDelimiters The delimiter string
@return a {@code String} array containing the delimiter separated elements
"""
if (isEmpty(pString)) {
return new String[0];
}
StringTokenIterator st = new StringTokenIterator(pString, pDelimiters);
List<String> v = new ArrayList<String>();
while (st.hasMoreElements()) {
v.add(st.nextToken());
}
return v.toArray(new String[v.size()]);
} | java | public static String[] toStringArray(String pString, String pDelimiters) {
if (isEmpty(pString)) {
return new String[0];
}
StringTokenIterator st = new StringTokenIterator(pString, pDelimiters);
List<String> v = new ArrayList<String>();
while (st.hasMoreElements()) {
v.add(st.nextToken());
}
return v.toArray(new String[v.size()]);
} | [
"public",
"static",
"String",
"[",
"]",
"toStringArray",
"(",
"String",
"pString",
",",
"String",
"pDelimiters",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"pString",
")",
")",
"{",
"return",
"new",
"String",
"[",
"0",
"]",
";",
"}",
"StringTokenIterator",
"st",
"=",
"new",
"StringTokenIterator",
"(",
"pString",
",",
"pDelimiters",
")",
";",
"List",
"<",
"String",
">",
"v",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"while",
"(",
"st",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"v",
".",
"add",
"(",
"st",
".",
"nextToken",
"(",
")",
")",
";",
"}",
"return",
"v",
".",
"toArray",
"(",
"new",
"String",
"[",
"v",
".",
"size",
"(",
")",
"]",
")",
";",
"}"
] | Converts a delimiter separated String to an array of Strings.
@param pString The comma-separated string
@param pDelimiters The delimiter string
@return a {@code String} array containing the delimiter separated elements | [
"Converts",
"a",
"delimiter",
"separated",
"String",
"to",
"an",
"array",
"of",
"Strings",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java#L930-L943 |
samskivert/samskivert | src/main/java/com/samskivert/velocity/DispatcherServlet.java | DispatcherServlet.doRequest | protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
"""
Handles all requests (by default).
@param request HttpServletRequest object containing client request.
@param response HttpServletResponse object for the response.
"""
InvocationContext context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context);
}
} catch (Exception e) {
log.warning("doRequest failed", "uri", request.getRequestURI(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} | java | protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
InvocationContext context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context);
}
} catch (Exception e) {
log.warning("doRequest failed", "uri", request.getRequestURI(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} | [
"protected",
"void",
"doRequest",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"InvocationContext",
"context",
"=",
"null",
";",
"try",
"{",
"context",
"=",
"new",
"InvocationContext",
"(",
"request",
",",
"response",
")",
";",
"setContentType",
"(",
"request",
",",
"response",
")",
";",
"Template",
"template",
"=",
"handleRequest",
"(",
"request",
",",
"response",
",",
"context",
")",
";",
"if",
"(",
"template",
"!=",
"null",
")",
"{",
"mergeTemplate",
"(",
"template",
",",
"context",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"warning",
"(",
"\"doRequest failed\"",
",",
"\"uri\"",
",",
"request",
".",
"getRequestURI",
"(",
")",
",",
"e",
")",
";",
"response",
".",
"sendError",
"(",
"HttpServletResponse",
".",
"SC_INTERNAL_SERVER_ERROR",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Handles all requests (by default).
@param request HttpServletRequest object containing client request.
@param response HttpServletResponse object for the response. | [
"Handles",
"all",
"requests",
"(",
"by",
"default",
")",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/DispatcherServlet.java#L443-L460 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java | PolylineSplitMerge.computeSideError | double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) {
"""
Scores a side based on the sum of Euclidean distance squared of each point along the line. Euclidean squared
is used because its fast to compute
@param indexA first index. Inclusive
@param indexB last index. Exclusive
"""
assignLine(contour, indexA, indexB, line);
// don't sample the end points because the error will be zero by definition
int numSamples;
double sumOfDistances = 0;
int length;
if( indexB >= indexA ) {
length = indexB-indexA-1;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int index = indexA+1+length*i/numSamples;
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
} else {
length = contour.size()-indexA-1 + indexB;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int where = length*i/numSamples;
int index = (indexA+1+where)%contour.size();
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
}
// handle divide by zero error
if( numSamples > 0 )
return sumOfDistances;
else
return 0;
} | java | double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) {
assignLine(contour, indexA, indexB, line);
// don't sample the end points because the error will be zero by definition
int numSamples;
double sumOfDistances = 0;
int length;
if( indexB >= indexA ) {
length = indexB-indexA-1;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int index = indexA+1+length*i/numSamples;
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
} else {
length = contour.size()-indexA-1 + indexB;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int where = length*i/numSamples;
int index = (indexA+1+where)%contour.size();
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
}
// handle divide by zero error
if( numSamples > 0 )
return sumOfDistances;
else
return 0;
} | [
"double",
"computeSideError",
"(",
"List",
"<",
"Point2D_I32",
">",
"contour",
",",
"int",
"indexA",
",",
"int",
"indexB",
")",
"{",
"assignLine",
"(",
"contour",
",",
"indexA",
",",
"indexB",
",",
"line",
")",
";",
"// don't sample the end points because the error will be zero by definition",
"int",
"numSamples",
";",
"double",
"sumOfDistances",
"=",
"0",
";",
"int",
"length",
";",
"if",
"(",
"indexB",
">=",
"indexA",
")",
"{",
"length",
"=",
"indexB",
"-",
"indexA",
"-",
"1",
";",
"numSamples",
"=",
"Math",
".",
"min",
"(",
"length",
",",
"maxNumberOfSideSamples",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numSamples",
";",
"i",
"++",
")",
"{",
"int",
"index",
"=",
"indexA",
"+",
"1",
"+",
"length",
"*",
"i",
"/",
"numSamples",
";",
"Point2D_I32",
"p",
"=",
"contour",
".",
"get",
"(",
"index",
")",
";",
"sumOfDistances",
"+=",
"Distance2D_F64",
".",
"distanceSq",
"(",
"line",
",",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
";",
"}",
"sumOfDistances",
"/=",
"numSamples",
";",
"}",
"else",
"{",
"length",
"=",
"contour",
".",
"size",
"(",
")",
"-",
"indexA",
"-",
"1",
"+",
"indexB",
";",
"numSamples",
"=",
"Math",
".",
"min",
"(",
"length",
",",
"maxNumberOfSideSamples",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numSamples",
";",
"i",
"++",
")",
"{",
"int",
"where",
"=",
"length",
"*",
"i",
"/",
"numSamples",
";",
"int",
"index",
"=",
"(",
"indexA",
"+",
"1",
"+",
"where",
")",
"%",
"contour",
".",
"size",
"(",
")",
";",
"Point2D_I32",
"p",
"=",
"contour",
".",
"get",
"(",
"index",
")",
";",
"sumOfDistances",
"+=",
"Distance2D_F64",
".",
"distanceSq",
"(",
"line",
",",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
";",
"}",
"sumOfDistances",
"/=",
"numSamples",
";",
"}",
"// handle divide by zero error",
"if",
"(",
"numSamples",
">",
"0",
")",
"return",
"sumOfDistances",
";",
"else",
"return",
"0",
";",
"}"
] | Scores a side based on the sum of Euclidean distance squared of each point along the line. Euclidean squared
is used because its fast to compute
@param indexA first index. Inclusive
@param indexB last index. Exclusive | [
"Scores",
"a",
"side",
"based",
"on",
"the",
"sum",
"of",
"Euclidean",
"distance",
"squared",
"of",
"each",
"point",
"along",
"the",
"line",
".",
"Euclidean",
"squared",
"is",
"used",
"because",
"its",
"fast",
"to",
"compute"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java#L625-L658 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java | BingSpellCheckOperationsImpl.spellCheckerAsync | public Observable<SpellCheck> spellCheckerAsync(String text, SpellCheckerOptionalParameter spellCheckerOptionalParameter) {
"""
The Bing Spell Check API lets you perform contextual grammar and spell checking. Bing has developed a web-based spell-checker that leverages machine learning and statistical machine translation to dynamically train a constantly evolving and highly contextual algorithm. The spell-checker is based on a massive corpus of web searches and documents.
@param text The text string to check for spelling and grammar errors. The combined length of the text string, preContextText string, and postContextText string may not exceed 10,000 characters. You may specify this parameter in the query string of a GET request or in the body of a POST request. Because of the query string length limit, you'll typically use a POST request unless you're checking only short strings.
@param spellCheckerOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SpellCheck object
"""
return spellCheckerWithServiceResponseAsync(text, spellCheckerOptionalParameter).map(new Func1<ServiceResponse<SpellCheck>, SpellCheck>() {
@Override
public SpellCheck call(ServiceResponse<SpellCheck> response) {
return response.body();
}
});
} | java | public Observable<SpellCheck> spellCheckerAsync(String text, SpellCheckerOptionalParameter spellCheckerOptionalParameter) {
return spellCheckerWithServiceResponseAsync(text, spellCheckerOptionalParameter).map(new Func1<ServiceResponse<SpellCheck>, SpellCheck>() {
@Override
public SpellCheck call(ServiceResponse<SpellCheck> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SpellCheck",
">",
"spellCheckerAsync",
"(",
"String",
"text",
",",
"SpellCheckerOptionalParameter",
"spellCheckerOptionalParameter",
")",
"{",
"return",
"spellCheckerWithServiceResponseAsync",
"(",
"text",
",",
"spellCheckerOptionalParameter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"SpellCheck",
">",
",",
"SpellCheck",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"SpellCheck",
"call",
"(",
"ServiceResponse",
"<",
"SpellCheck",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | The Bing Spell Check API lets you perform contextual grammar and spell checking. Bing has developed a web-based spell-checker that leverages machine learning and statistical machine translation to dynamically train a constantly evolving and highly contextual algorithm. The spell-checker is based on a massive corpus of web searches and documents.
@param text The text string to check for spelling and grammar errors. The combined length of the text string, preContextText string, and postContextText string may not exceed 10,000 characters. You may specify this parameter in the query string of a GET request or in the body of a POST request. Because of the query string length limit, you'll typically use a POST request unless you're checking only short strings.
@param spellCheckerOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SpellCheck object | [
"The",
"Bing",
"Spell",
"Check",
"API",
"lets",
"you",
"perform",
"contextual",
"grammar",
"and",
"spell",
"checking",
".",
"Bing",
"has",
"developed",
"a",
"web",
"-",
"based",
"spell",
"-",
"checker",
"that",
"leverages",
"machine",
"learning",
"and",
"statistical",
"machine",
"translation",
"to",
"dynamically",
"train",
"a",
"constantly",
"evolving",
"and",
"highly",
"contextual",
"algorithm",
".",
"The",
"spell",
"-",
"checker",
"is",
"based",
"on",
"a",
"massive",
"corpus",
"of",
"web",
"searches",
"and",
"documents",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java#L100-L107 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.getMethod | public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {
"""
Convenience method to get a method from a class type without having to
catch the checked exceptions otherwise required. These exceptions are
wrapped as runtime exceptions.
The method will first try to look for a declared method in the same
class. If the method is not declared in this class it will look for the
method in the super class. This will continue throughout the whole class
hierarchy. If the method is not found an {@link IllegalArgumentException}
is thrown.
@param type The type of the class where the method is located.
@param methodName The method names.
@param parameterTypes All parameter types of the method (may be {@code null}).
@return A .
"""
Class<?> thisType = type;
if (parameterTypes == null) {
parameterTypes = new Class<?>[0];
}
while (thisType != null) {
Method[] methodsToTraverse = null;
if (thisType.isInterface()) {
// Interfaces only contain public (and abstract) methods, no
// need to traverse the hierarchy.
methodsToTraverse = getAllPublicMethods(thisType);
} else {
methodsToTraverse = thisType.getDeclaredMethods();
}
for (Method method : methodsToTraverse) {
if (methodName.equals(method.getName())
&& checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) {
method.setAccessible(true);
return method;
}
}
thisType = thisType.getSuperclass();
}
throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes});
return null;
} | java | public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {
Class<?> thisType = type;
if (parameterTypes == null) {
parameterTypes = new Class<?>[0];
}
while (thisType != null) {
Method[] methodsToTraverse = null;
if (thisType.isInterface()) {
// Interfaces only contain public (and abstract) methods, no
// need to traverse the hierarchy.
methodsToTraverse = getAllPublicMethods(thisType);
} else {
methodsToTraverse = thisType.getDeclaredMethods();
}
for (Method method : methodsToTraverse) {
if (methodName.equals(method.getName())
&& checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) {
method.setAccessible(true);
return method;
}
}
thisType = thisType.getSuperclass();
}
throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes});
return null;
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"parameterTypes",
")",
"{",
"Class",
"<",
"?",
">",
"thisType",
"=",
"type",
";",
"if",
"(",
"parameterTypes",
"==",
"null",
")",
"{",
"parameterTypes",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"0",
"]",
";",
"}",
"while",
"(",
"thisType",
"!=",
"null",
")",
"{",
"Method",
"[",
"]",
"methodsToTraverse",
"=",
"null",
";",
"if",
"(",
"thisType",
".",
"isInterface",
"(",
")",
")",
"{",
"// Interfaces only contain public (and abstract) methods, no",
"// need to traverse the hierarchy.",
"methodsToTraverse",
"=",
"getAllPublicMethods",
"(",
"thisType",
")",
";",
"}",
"else",
"{",
"methodsToTraverse",
"=",
"thisType",
".",
"getDeclaredMethods",
"(",
")",
";",
"}",
"for",
"(",
"Method",
"method",
":",
"methodsToTraverse",
")",
"{",
"if",
"(",
"methodName",
".",
"equals",
"(",
"method",
".",
"getName",
"(",
")",
")",
"&&",
"checkIfParameterTypesAreSame",
"(",
"method",
".",
"isVarArgs",
"(",
")",
",",
"parameterTypes",
",",
"method",
".",
"getParameterTypes",
"(",
")",
")",
")",
"{",
"method",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"method",
";",
"}",
"}",
"thisType",
"=",
"thisType",
".",
"getSuperclass",
"(",
")",
";",
"}",
"throwExceptionIfMethodWasNotFound",
"(",
"type",
",",
"methodName",
",",
"null",
",",
"new",
"Object",
"[",
"]",
"{",
"parameterTypes",
"}",
")",
";",
"return",
"null",
";",
"}"
] | Convenience method to get a method from a class type without having to
catch the checked exceptions otherwise required. These exceptions are
wrapped as runtime exceptions.
The method will first try to look for a declared method in the same
class. If the method is not declared in this class it will look for the
method in the super class. This will continue throughout the whole class
hierarchy. If the method is not found an {@link IllegalArgumentException}
is thrown.
@param type The type of the class where the method is located.
@param methodName The method names.
@param parameterTypes All parameter types of the method (may be {@code null}).
@return A . | [
"Convenience",
"method",
"to",
"get",
"a",
"method",
"from",
"a",
"class",
"type",
"without",
"having",
"to",
"catch",
"the",
"checked",
"exceptions",
"otherwise",
"required",
".",
"These",
"exceptions",
"are",
"wrapped",
"as",
"runtime",
"exceptions",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L158-L184 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleCache.java | StyleCache.setFeatureStyle | public boolean setFeatureStyle(PolylineOptions polylineOptions, FeatureRow featureRow) {
"""
Set the feature row style into the polyline options
@param polylineOptions polyline options
@param featureRow feature row
@return true if style was set into the polyline options
"""
return StyleUtils.setFeatureStyle(polylineOptions, featureStyleExtension, featureRow, density);
} | java | public boolean setFeatureStyle(PolylineOptions polylineOptions, FeatureRow featureRow) {
return StyleUtils.setFeatureStyle(polylineOptions, featureStyleExtension, featureRow, density);
} | [
"public",
"boolean",
"setFeatureStyle",
"(",
"PolylineOptions",
"polylineOptions",
",",
"FeatureRow",
"featureRow",
")",
"{",
"return",
"StyleUtils",
".",
"setFeatureStyle",
"(",
"polylineOptions",
",",
"featureStyleExtension",
",",
"featureRow",
",",
"density",
")",
";",
"}"
] | Set the feature row style into the polyline options
@param polylineOptions polyline options
@param featureRow feature row
@return true if style was set into the polyline options | [
"Set",
"the",
"feature",
"row",
"style",
"into",
"the",
"polyline",
"options"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleCache.java#L229-L231 |
Bernardo-MG/maven-site-fixer | src/main/java/com/bernardomg/velocity/tool/SiteTool.java | SiteTool.transformIcons | public final void transformIcons(final Element root) {
"""
Transforms the default icons used by the Maven Site to Font Awesome
icons.
@param root
root element with the page
"""
final Map<String, String> replacements; // Texts to replace and
// replacements
checkNotNull(root, "Received a null pointer as root element");
replacements = new HashMap<>();
replacements.put("img[src$=images/add.gif]",
"<span><span class=\"fa fa-plus\" aria-hidden=\"true\"></span><span class=\"sr-only\">Addition</span></span>");
replacements.put("img[src$=images/remove.gif]",
"<span><span class=\"fa fa-minus\" aria-hidden=\"true\"></span><span class=\"sr-only\">Remove</span></span>");
replacements.put("img[src$=images/fix.gif]",
"<span><span class=\"fa fa-wrench\" aria-hidden=\"true\"></span><span class=\"sr-only\">Fix</span></span>");
replacements.put("img[src$=images/update.gif]",
"<span><span class=\"fa fa-refresh\" aria-hidden=\"true\"></span><span class=\"sr-only\">Refresh</span></span>");
replacements.put("img[src$=images/icon_help_sml.gif]",
"<span><span class=\"fa fa-question\" aria-hidden=\"true\"></span><span class=\"sr-only\">Question</span></span>");
replacements.put("img[src$=images/icon_success_sml.gif]",
"<span><span class=\"navbar-icon fa fa-check\" aria-hidden=\"true\" title=\"Passed\" aria-label=\"Passed\"></span><span class=\"sr-only\">Passed</span></span>");
replacements.put("img[src$=images/icon_warning_sml.gif]",
"<span><span class=\"fa fa-exclamation\" aria-hidden=\"true\"></span><span class=\"sr-only\">Warning</span>");
replacements.put("img[src$=images/icon_error_sml.gif]",
"<span><span class=\"navbar-icon fa fa-close\" aria-hidden=\"true\" title=\"Failed\" aria-label=\"Failed\"></span><span class=\"sr-only\">Failed</span></span>");
replacements.put("img[src$=images/icon_info_sml.gif]",
"<span><span class=\"fa fa-info\" aria-hidden=\"true\"></span><span class=\"sr-only\">Info</span></span>");
replaceAll(root, replacements);
} | java | public final void transformIcons(final Element root) {
final Map<String, String> replacements; // Texts to replace and
// replacements
checkNotNull(root, "Received a null pointer as root element");
replacements = new HashMap<>();
replacements.put("img[src$=images/add.gif]",
"<span><span class=\"fa fa-plus\" aria-hidden=\"true\"></span><span class=\"sr-only\">Addition</span></span>");
replacements.put("img[src$=images/remove.gif]",
"<span><span class=\"fa fa-minus\" aria-hidden=\"true\"></span><span class=\"sr-only\">Remove</span></span>");
replacements.put("img[src$=images/fix.gif]",
"<span><span class=\"fa fa-wrench\" aria-hidden=\"true\"></span><span class=\"sr-only\">Fix</span></span>");
replacements.put("img[src$=images/update.gif]",
"<span><span class=\"fa fa-refresh\" aria-hidden=\"true\"></span><span class=\"sr-only\">Refresh</span></span>");
replacements.put("img[src$=images/icon_help_sml.gif]",
"<span><span class=\"fa fa-question\" aria-hidden=\"true\"></span><span class=\"sr-only\">Question</span></span>");
replacements.put("img[src$=images/icon_success_sml.gif]",
"<span><span class=\"navbar-icon fa fa-check\" aria-hidden=\"true\" title=\"Passed\" aria-label=\"Passed\"></span><span class=\"sr-only\">Passed</span></span>");
replacements.put("img[src$=images/icon_warning_sml.gif]",
"<span><span class=\"fa fa-exclamation\" aria-hidden=\"true\"></span><span class=\"sr-only\">Warning</span>");
replacements.put("img[src$=images/icon_error_sml.gif]",
"<span><span class=\"navbar-icon fa fa-close\" aria-hidden=\"true\" title=\"Failed\" aria-label=\"Failed\"></span><span class=\"sr-only\">Failed</span></span>");
replacements.put("img[src$=images/icon_info_sml.gif]",
"<span><span class=\"fa fa-info\" aria-hidden=\"true\"></span><span class=\"sr-only\">Info</span></span>");
replaceAll(root, replacements);
} | [
"public",
"final",
"void",
"transformIcons",
"(",
"final",
"Element",
"root",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"replacements",
";",
"// Texts to replace and",
"// replacements",
"checkNotNull",
"(",
"root",
",",
"\"Received a null pointer as root element\"",
")",
";",
"replacements",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/add.gif]\"",
",",
"\"<span><span class=\\\"fa fa-plus\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Addition</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/remove.gif]\"",
",",
"\"<span><span class=\\\"fa fa-minus\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Remove</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/fix.gif]\"",
",",
"\"<span><span class=\\\"fa fa-wrench\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Fix</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/update.gif]\"",
",",
"\"<span><span class=\\\"fa fa-refresh\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Refresh</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/icon_help_sml.gif]\"",
",",
"\"<span><span class=\\\"fa fa-question\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Question</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/icon_success_sml.gif]\"",
",",
"\"<span><span class=\\\"navbar-icon fa fa-check\\\" aria-hidden=\\\"true\\\" title=\\\"Passed\\\" aria-label=\\\"Passed\\\"></span><span class=\\\"sr-only\\\">Passed</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/icon_warning_sml.gif]\"",
",",
"\"<span><span class=\\\"fa fa-exclamation\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Warning</span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/icon_error_sml.gif]\"",
",",
"\"<span><span class=\\\"navbar-icon fa fa-close\\\" aria-hidden=\\\"true\\\" title=\\\"Failed\\\" aria-label=\\\"Failed\\\"></span><span class=\\\"sr-only\\\">Failed</span></span>\"",
")",
";",
"replacements",
".",
"put",
"(",
"\"img[src$=images/icon_info_sml.gif]\"",
",",
"\"<span><span class=\\\"fa fa-info\\\" aria-hidden=\\\"true\\\"></span><span class=\\\"sr-only\\\">Info</span></span>\"",
")",
";",
"replaceAll",
"(",
"root",
",",
"replacements",
")",
";",
"}"
] | Transforms the default icons used by the Maven Site to Font Awesome
icons.
@param root
root element with the page | [
"Transforms",
"the",
"default",
"icons",
"used",
"by",
"the",
"Maven",
"Site",
"to",
"Font",
"Awesome",
"icons",
"."
] | train | https://github.com/Bernardo-MG/maven-site-fixer/blob/e064472faa7edb0fca11647a22d90ad72089baa3/src/main/java/com/bernardomg/velocity/tool/SiteTool.java#L252-L279 |
eurekaclinical/eurekaclinical-common | src/main/java/org/eurekaclinical/common/auth/AuthorizedUserSupport.java | AuthorizedUserSupport.getUser | public E getUser(HttpServletRequest servletRequest) {
"""
Returns the user object, or if there isn't one, throws an exception.
@param servletRequest the HTTP servlet request.
@return the user object.
@throws HttpStatusException if the logged-in user isn't in the user
table, which means the user is not authorized to use eureka-protempa-etl.
"""
AttributePrincipal principal = getUserPrincipal(servletRequest);
E result = this.userDao.getByPrincipal(principal);
if (result == null) {
throw new HttpStatusException(Status.FORBIDDEN, "User " + principal.getName() + " is not authorized to use this resource");
}
return result;
} | java | public E getUser(HttpServletRequest servletRequest) {
AttributePrincipal principal = getUserPrincipal(servletRequest);
E result = this.userDao.getByPrincipal(principal);
if (result == null) {
throw new HttpStatusException(Status.FORBIDDEN, "User " + principal.getName() + " is not authorized to use this resource");
}
return result;
} | [
"public",
"E",
"getUser",
"(",
"HttpServletRequest",
"servletRequest",
")",
"{",
"AttributePrincipal",
"principal",
"=",
"getUserPrincipal",
"(",
"servletRequest",
")",
";",
"E",
"result",
"=",
"this",
".",
"userDao",
".",
"getByPrincipal",
"(",
"principal",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"throw",
"new",
"HttpStatusException",
"(",
"Status",
".",
"FORBIDDEN",
",",
"\"User \"",
"+",
"principal",
".",
"getName",
"(",
")",
"+",
"\" is not authorized to use this resource\"",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Returns the user object, or if there isn't one, throws an exception.
@param servletRequest the HTTP servlet request.
@return the user object.
@throws HttpStatusException if the logged-in user isn't in the user
table, which means the user is not authorized to use eureka-protempa-etl. | [
"Returns",
"the",
"user",
"object",
"or",
"if",
"there",
"isn",
"t",
"one",
"throws",
"an",
"exception",
"."
] | train | https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/auth/AuthorizedUserSupport.java#L61-L68 |
elki-project/elki | elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java | GeneratorXMLDatabaseConnection.processElementClipping | private void processElementClipping(GeneratorSingleCluster cluster, Node cur) {
"""
Process a 'clipping' Element in the XML stream.
@param cluster
@param cur Current document nod
"""
double[] cmin = null, cmax = null;
String minstr = ((Element) cur).getAttribute(ATTR_MIN);
if(minstr != null && minstr.length() > 0) {
cmin = parseVector(minstr);
}
String maxstr = ((Element) cur).getAttribute(ATTR_MAX);
if(maxstr != null && maxstr.length() > 0) {
cmax = parseVector(maxstr);
}
if(cmin == null || cmax == null) {
throw new AbortException("No or incomplete clipping vectors given.");
}
// *** set clipping
cluster.setClipping(cmin, cmax);
// TODO: check for unknown attributes.
XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
while(iter.hasNext()) {
Node child = iter.next();
if(child.getNodeType() == Node.ELEMENT_NODE) {
LOG.warning("Unknown element in XML specification file: " + child.getNodeName());
}
}
} | java | private void processElementClipping(GeneratorSingleCluster cluster, Node cur) {
double[] cmin = null, cmax = null;
String minstr = ((Element) cur).getAttribute(ATTR_MIN);
if(minstr != null && minstr.length() > 0) {
cmin = parseVector(minstr);
}
String maxstr = ((Element) cur).getAttribute(ATTR_MAX);
if(maxstr != null && maxstr.length() > 0) {
cmax = parseVector(maxstr);
}
if(cmin == null || cmax == null) {
throw new AbortException("No or incomplete clipping vectors given.");
}
// *** set clipping
cluster.setClipping(cmin, cmax);
// TODO: check for unknown attributes.
XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
while(iter.hasNext()) {
Node child = iter.next();
if(child.getNodeType() == Node.ELEMENT_NODE) {
LOG.warning("Unknown element in XML specification file: " + child.getNodeName());
}
}
} | [
"private",
"void",
"processElementClipping",
"(",
"GeneratorSingleCluster",
"cluster",
",",
"Node",
"cur",
")",
"{",
"double",
"[",
"]",
"cmin",
"=",
"null",
",",
"cmax",
"=",
"null",
";",
"String",
"minstr",
"=",
"(",
"(",
"Element",
")",
"cur",
")",
".",
"getAttribute",
"(",
"ATTR_MIN",
")",
";",
"if",
"(",
"minstr",
"!=",
"null",
"&&",
"minstr",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"cmin",
"=",
"parseVector",
"(",
"minstr",
")",
";",
"}",
"String",
"maxstr",
"=",
"(",
"(",
"Element",
")",
"cur",
")",
".",
"getAttribute",
"(",
"ATTR_MAX",
")",
";",
"if",
"(",
"maxstr",
"!=",
"null",
"&&",
"maxstr",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"cmax",
"=",
"parseVector",
"(",
"maxstr",
")",
";",
"}",
"if",
"(",
"cmin",
"==",
"null",
"||",
"cmax",
"==",
"null",
")",
"{",
"throw",
"new",
"AbortException",
"(",
"\"No or incomplete clipping vectors given.\"",
")",
";",
"}",
"// *** set clipping",
"cluster",
".",
"setClipping",
"(",
"cmin",
",",
"cmax",
")",
";",
"// TODO: check for unknown attributes.",
"XMLNodeIterator",
"iter",
"=",
"new",
"XMLNodeIterator",
"(",
"cur",
".",
"getFirstChild",
"(",
")",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"Node",
"child",
"=",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"child",
".",
"getNodeType",
"(",
")",
"==",
"Node",
".",
"ELEMENT_NODE",
")",
"{",
"LOG",
".",
"warning",
"(",
"\"Unknown element in XML specification file: \"",
"+",
"child",
".",
"getNodeName",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Process a 'clipping' Element in the XML stream.
@param cluster
@param cur Current document nod | [
"Process",
"a",
"clipping",
"Element",
"in",
"the",
"XML",
"stream",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java#L601-L627 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java | JobState.newDatasetState | public DatasetState newDatasetState(boolean fullCopy) {
"""
Create a new {@link JobState.DatasetState} based on this {@link JobState} instance.
@param fullCopy whether to do a full copy of this {@link JobState} instance
@return a new {@link JobState.DatasetState} object
"""
DatasetState datasetState = new DatasetState(this.jobName, this.jobId);
datasetState.setStartTime(this.startTime);
datasetState.setEndTime(this.endTime);
datasetState.setDuration(this.duration);
if (fullCopy) {
datasetState.setState(this.state);
datasetState.setTaskCount(this.taskCount);
datasetState.addTaskStates(this.taskStates.values());
datasetState.addSkippedTaskStates(this.skippedTaskStates.values());
}
return datasetState;
} | java | public DatasetState newDatasetState(boolean fullCopy) {
DatasetState datasetState = new DatasetState(this.jobName, this.jobId);
datasetState.setStartTime(this.startTime);
datasetState.setEndTime(this.endTime);
datasetState.setDuration(this.duration);
if (fullCopy) {
datasetState.setState(this.state);
datasetState.setTaskCount(this.taskCount);
datasetState.addTaskStates(this.taskStates.values());
datasetState.addSkippedTaskStates(this.skippedTaskStates.values());
}
return datasetState;
} | [
"public",
"DatasetState",
"newDatasetState",
"(",
"boolean",
"fullCopy",
")",
"{",
"DatasetState",
"datasetState",
"=",
"new",
"DatasetState",
"(",
"this",
".",
"jobName",
",",
"this",
".",
"jobId",
")",
";",
"datasetState",
".",
"setStartTime",
"(",
"this",
".",
"startTime",
")",
";",
"datasetState",
".",
"setEndTime",
"(",
"this",
".",
"endTime",
")",
";",
"datasetState",
".",
"setDuration",
"(",
"this",
".",
"duration",
")",
";",
"if",
"(",
"fullCopy",
")",
"{",
"datasetState",
".",
"setState",
"(",
"this",
".",
"state",
")",
";",
"datasetState",
".",
"setTaskCount",
"(",
"this",
".",
"taskCount",
")",
";",
"datasetState",
".",
"addTaskStates",
"(",
"this",
".",
"taskStates",
".",
"values",
"(",
")",
")",
";",
"datasetState",
".",
"addSkippedTaskStates",
"(",
"this",
".",
"skippedTaskStates",
".",
"values",
"(",
")",
")",
";",
"}",
"return",
"datasetState",
";",
"}"
] | Create a new {@link JobState.DatasetState} based on this {@link JobState} instance.
@param fullCopy whether to do a full copy of this {@link JobState} instance
@return a new {@link JobState.DatasetState} object | [
"Create",
"a",
"new",
"{",
"@link",
"JobState",
".",
"DatasetState",
"}",
"based",
"on",
"this",
"{",
"@link",
"JobState",
"}",
"instance",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java#L748-L760 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java | QueryDataUtils.getReplierExportStrategyValue | private static String getReplierExportStrategyValue(ReplierExportStrategy replierExportStrategy, QueryReply queryReply) {
"""
Returns user identifier for given replier export strategy
@param replierExportStrategy replier export strategy
@param queryReply reply
@return user identifier
"""
if (queryReply != null) {
User user = queryReply.getUser();
if (user != null) {
switch (replierExportStrategy) {
case NONE:
break;
case HASH:
return RequestUtils.md5EncodeString(String.valueOf(user.getId()));
case NAME:
return user.getFullName(true, false);
case EMAIL:
return user.getDefaultEmailAsString();
}
}
}
return "-";
} | java | private static String getReplierExportStrategyValue(ReplierExportStrategy replierExportStrategy, QueryReply queryReply) {
if (queryReply != null) {
User user = queryReply.getUser();
if (user != null) {
switch (replierExportStrategy) {
case NONE:
break;
case HASH:
return RequestUtils.md5EncodeString(String.valueOf(user.getId()));
case NAME:
return user.getFullName(true, false);
case EMAIL:
return user.getDefaultEmailAsString();
}
}
}
return "-";
} | [
"private",
"static",
"String",
"getReplierExportStrategyValue",
"(",
"ReplierExportStrategy",
"replierExportStrategy",
",",
"QueryReply",
"queryReply",
")",
"{",
"if",
"(",
"queryReply",
"!=",
"null",
")",
"{",
"User",
"user",
"=",
"queryReply",
".",
"getUser",
"(",
")",
";",
"if",
"(",
"user",
"!=",
"null",
")",
"{",
"switch",
"(",
"replierExportStrategy",
")",
"{",
"case",
"NONE",
":",
"break",
";",
"case",
"HASH",
":",
"return",
"RequestUtils",
".",
"md5EncodeString",
"(",
"String",
".",
"valueOf",
"(",
"user",
".",
"getId",
"(",
")",
")",
")",
";",
"case",
"NAME",
":",
"return",
"user",
".",
"getFullName",
"(",
"true",
",",
"false",
")",
";",
"case",
"EMAIL",
":",
"return",
"user",
".",
"getDefaultEmailAsString",
"(",
")",
";",
"}",
"}",
"}",
"return",
"\"-\"",
";",
"}"
] | Returns user identifier for given replier export strategy
@param replierExportStrategy replier export strategy
@param queryReply reply
@return user identifier | [
"Returns",
"user",
"identifier",
"for",
"given",
"replier",
"export",
"strategy"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java#L301-L319 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/result/TemplateParserResult.java | TemplateParserResult.addRef | public void addRef(String name, TypeMirror elementType, boolean isArray) {
"""
Register a ref found in the template
@param name The name of the ref
@param elementType The type of the element the Ref is on
@param isArray Whether the ref is in a v-for (should be an array)
"""
refs.add(new RefInfo(name, elementType, isArray));
} | java | public void addRef(String name, TypeMirror elementType, boolean isArray) {
refs.add(new RefInfo(name, elementType, isArray));
} | [
"public",
"void",
"addRef",
"(",
"String",
"name",
",",
"TypeMirror",
"elementType",
",",
"boolean",
"isArray",
")",
"{",
"refs",
".",
"add",
"(",
"new",
"RefInfo",
"(",
"name",
",",
"elementType",
",",
"isArray",
")",
")",
";",
"}"
] | Register a ref found in the template
@param name The name of the ref
@param elementType The type of the element the Ref is on
@param isArray Whether the ref is in a v-for (should be an array) | [
"Register",
"a",
"ref",
"found",
"in",
"the",
"template"
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/result/TemplateParserResult.java#L97-L99 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.toIntFunction | public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function) {
"""
Wrap a {@link CheckedToIntFunction} in a {@link ToIntFunction}.
<p>
Example:
<code><pre>
map.computeIfAbsent("key", Unchecked.toIntFunction(k -> {
if (k.length() > 10)
throw new Exception("Only short strings allowed");
return 42;
}));
</pre></code>
"""
return toIntFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | java | public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function) {
return toIntFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | [
"public",
"static",
"<",
"T",
">",
"ToIntFunction",
"<",
"T",
">",
"toIntFunction",
"(",
"CheckedToIntFunction",
"<",
"T",
">",
"function",
")",
"{",
"return",
"toIntFunction",
"(",
"function",
",",
"THROWABLE_TO_RUNTIME_EXCEPTION",
")",
";",
"}"
] | Wrap a {@link CheckedToIntFunction} in a {@link ToIntFunction}.
<p>
Example:
<code><pre>
map.computeIfAbsent("key", Unchecked.toIntFunction(k -> {
if (k.length() > 10)
throw new Exception("Only short strings allowed");
return 42;
}));
</pre></code> | [
"Wrap",
"a",
"{",
"@link",
"CheckedToIntFunction",
"}",
"in",
"a",
"{",
"@link",
"ToIntFunction",
"}",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"map",
".",
"computeIfAbsent",
"(",
"key",
"Unchecked",
".",
"toIntFunction",
"(",
"k",
"-",
">",
"{",
"if",
"(",
"k",
".",
"length",
"()",
">",
"10",
")",
"throw",
"new",
"Exception",
"(",
"Only",
"short",
"strings",
"allowed",
")",
";"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L901-L903 |
norbsoft/android-typeface-helper | lib/src/main/java/com/norbsoft/typefacehelper/TypefaceHelper.java | TypefaceHelper.checkTypefaceStyleThrowing | private static void checkTypefaceStyleThrowing(int style) {
"""
Check if typeface style int is one of:
<ul>
<li>{@link android.graphics.Typeface#NORMAL}</li>
<li>{@link android.graphics.Typeface#BOLD}</li>
<li>{@link android.graphics.Typeface#ITALIC}</li>
<li>{@link android.graphics.Typeface#BOLD_ITALIC}</li>
</ul>
@param style
"""
switch (style) {
case Typeface.NORMAL:
case Typeface.BOLD:
case Typeface.ITALIC:
case Typeface.BOLD_ITALIC:
break;
default:
throw new IllegalArgumentException("Style have to be in (Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC, Typeface.BOLD_ITALIC)");
}
} | java | private static void checkTypefaceStyleThrowing(int style) {
switch (style) {
case Typeface.NORMAL:
case Typeface.BOLD:
case Typeface.ITALIC:
case Typeface.BOLD_ITALIC:
break;
default:
throw new IllegalArgumentException("Style have to be in (Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC, Typeface.BOLD_ITALIC)");
}
} | [
"private",
"static",
"void",
"checkTypefaceStyleThrowing",
"(",
"int",
"style",
")",
"{",
"switch",
"(",
"style",
")",
"{",
"case",
"Typeface",
".",
"NORMAL",
":",
"case",
"Typeface",
".",
"BOLD",
":",
"case",
"Typeface",
".",
"ITALIC",
":",
"case",
"Typeface",
".",
"BOLD_ITALIC",
":",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Style have to be in (Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC, Typeface.BOLD_ITALIC)\"",
")",
";",
"}",
"}"
] | Check if typeface style int is one of:
<ul>
<li>{@link android.graphics.Typeface#NORMAL}</li>
<li>{@link android.graphics.Typeface#BOLD}</li>
<li>{@link android.graphics.Typeface#ITALIC}</li>
<li>{@link android.graphics.Typeface#BOLD_ITALIC}</li>
</ul>
@param style | [
"Check",
"if",
"typeface",
"style",
"int",
"is",
"one",
"of",
":",
"<ul",
">",
"<li",
">",
"{"
] | train | https://github.com/norbsoft/android-typeface-helper/blob/f9e12655f01144efa937c1172f5de7f9b29c4df7/lib/src/main/java/com/norbsoft/typefacehelper/TypefaceHelper.java#L208-L218 |
haifengl/smile | core/src/main/java/smile/association/FPGrowth.java | FPGrowth.buildTotalSupportTree | TotalSupportTree buildTotalSupportTree() {
"""
Mines the frequent item sets. The discovered frequent item sets
will be stored in a total support tree.
"""
TotalSupportTree ttree = new TotalSupportTree(minSupport, T0.numFreqItems, T0.order);
learn(null, null, ttree);
return ttree;
} | java | TotalSupportTree buildTotalSupportTree() {
TotalSupportTree ttree = new TotalSupportTree(minSupport, T0.numFreqItems, T0.order);
learn(null, null, ttree);
return ttree;
} | [
"TotalSupportTree",
"buildTotalSupportTree",
"(",
")",
"{",
"TotalSupportTree",
"ttree",
"=",
"new",
"TotalSupportTree",
"(",
"minSupport",
",",
"T0",
".",
"numFreqItems",
",",
"T0",
".",
"order",
")",
";",
"learn",
"(",
"null",
",",
"null",
",",
"ttree",
")",
";",
"return",
"ttree",
";",
"}"
] | Mines the frequent item sets. The discovered frequent item sets
will be stored in a total support tree. | [
"Mines",
"the",
"frequent",
"item",
"sets",
".",
"The",
"discovered",
"frequent",
"item",
"sets",
"will",
"be",
"stored",
"in",
"a",
"total",
"support",
"tree",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/FPGrowth.java#L164-L168 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/bcc/BccClient.java | BccClient.unbindInstanceFromSecurityGroup | public void unbindInstanceFromSecurityGroup(String instanceId, String securityGroupId) {
"""
Unbinding the instance from securitygroup.
@param instanceId The id of the instance.
@param securityGroupId The id of the securitygroup.
"""
this.unbindInstanceFromSecurityGroup(new UnbindSecurityGroupRequest()
.withInstanceId(instanceId).withSecurityGroupId(securityGroupId));
} | java | public void unbindInstanceFromSecurityGroup(String instanceId, String securityGroupId) {
this.unbindInstanceFromSecurityGroup(new UnbindSecurityGroupRequest()
.withInstanceId(instanceId).withSecurityGroupId(securityGroupId));
} | [
"public",
"void",
"unbindInstanceFromSecurityGroup",
"(",
"String",
"instanceId",
",",
"String",
"securityGroupId",
")",
"{",
"this",
".",
"unbindInstanceFromSecurityGroup",
"(",
"new",
"UnbindSecurityGroupRequest",
"(",
")",
".",
"withInstanceId",
"(",
"instanceId",
")",
".",
"withSecurityGroupId",
"(",
"securityGroupId",
")",
")",
";",
"}"
] | Unbinding the instance from securitygroup.
@param instanceId The id of the instance.
@param securityGroupId The id of the securitygroup. | [
"Unbinding",
"the",
"instance",
"from",
"securitygroup",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L740-L743 |
alibaba/jstorm | jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/DirLock.java | DirLock.tryLock | public static DirLock tryLock(FileSystem fs, Path dir) throws IOException {
"""
Get a lock on file if not already locked
@param fs
@param dir the dir on which to get a lock
@return The lock object if it the lock was acquired. Returns null if the dir is already locked.
@throws IOException if there were errors
"""
Path lockFile = getDirLockFile(dir);
try {
FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile);
if (ostream!=null) {
LOG.debug("Thread ({}) Acquired lock on dir {}", threadInfo(), dir);
ostream.close();
return new DirLock(fs, lockFile);
} else {
LOG.debug("Thread ({}) cannot lock dir {} as its already locked.", threadInfo(), dir);
return null;
}
} catch (IOException e) {
LOG.error("Error when acquiring lock on dir " + dir, e);
throw e;
}
} | java | public static DirLock tryLock(FileSystem fs, Path dir) throws IOException {
Path lockFile = getDirLockFile(dir);
try {
FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile);
if (ostream!=null) {
LOG.debug("Thread ({}) Acquired lock on dir {}", threadInfo(), dir);
ostream.close();
return new DirLock(fs, lockFile);
} else {
LOG.debug("Thread ({}) cannot lock dir {} as its already locked.", threadInfo(), dir);
return null;
}
} catch (IOException e) {
LOG.error("Error when acquiring lock on dir " + dir, e);
throw e;
}
} | [
"public",
"static",
"DirLock",
"tryLock",
"(",
"FileSystem",
"fs",
",",
"Path",
"dir",
")",
"throws",
"IOException",
"{",
"Path",
"lockFile",
"=",
"getDirLockFile",
"(",
"dir",
")",
";",
"try",
"{",
"FSDataOutputStream",
"ostream",
"=",
"HdfsUtils",
".",
"tryCreateFile",
"(",
"fs",
",",
"lockFile",
")",
";",
"if",
"(",
"ostream",
"!=",
"null",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Thread ({}) Acquired lock on dir {}\"",
",",
"threadInfo",
"(",
")",
",",
"dir",
")",
";",
"ostream",
".",
"close",
"(",
")",
";",
"return",
"new",
"DirLock",
"(",
"fs",
",",
"lockFile",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"debug",
"(",
"\"Thread ({}) cannot lock dir {} as its already locked.\"",
",",
"threadInfo",
"(",
")",
",",
"dir",
")",
";",
"return",
"null",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Error when acquiring lock on dir \"",
"+",
"dir",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Get a lock on file if not already locked
@param fs
@param dir the dir on which to get a lock
@return The lock object if it the lock was acquired. Returns null if the dir is already locked.
@throws IOException if there were errors | [
"Get",
"a",
"lock",
"on",
"file",
"if",
"not",
"already",
"locked"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/DirLock.java#L55-L72 |
groupe-sii/ogham | ogham-sms-cloudhopper/src/main/java/fr/sii/ogham/sms/builder/cloudhopper/CharsetBuilder.java | CharsetBuilder.convert | public CharsetBuilder convert(String nioCharsetName, String cloudhopperCharset) {
"""
Registers a charset conversion. Conversion is required by Cloudhopper in
order to use a charset supported by the SMPP protocol.
You can register several charset conversions.
@param nioCharsetName
the charset used by the Java application
@param cloudhopperCharset
the charset supported by the SMPP protocol
@return this instance for fluent chaining
"""
mappings.add(new CharsetMapping(nioCharsetName, cloudhopperCharset));
return this;
} | java | public CharsetBuilder convert(String nioCharsetName, String cloudhopperCharset) {
mappings.add(new CharsetMapping(nioCharsetName, cloudhopperCharset));
return this;
} | [
"public",
"CharsetBuilder",
"convert",
"(",
"String",
"nioCharsetName",
",",
"String",
"cloudhopperCharset",
")",
"{",
"mappings",
".",
"add",
"(",
"new",
"CharsetMapping",
"(",
"nioCharsetName",
",",
"cloudhopperCharset",
")",
")",
";",
"return",
"this",
";",
"}"
] | Registers a charset conversion. Conversion is required by Cloudhopper in
order to use a charset supported by the SMPP protocol.
You can register several charset conversions.
@param nioCharsetName
the charset used by the Java application
@param cloudhopperCharset
the charset supported by the SMPP protocol
@return this instance for fluent chaining | [
"Registers",
"a",
"charset",
"conversion",
".",
"Conversion",
"is",
"required",
"by",
"Cloudhopper",
"in",
"order",
"to",
"use",
"a",
"charset",
"supported",
"by",
"the",
"SMPP",
"protocol",
"."
] | train | https://github.com/groupe-sii/ogham/blob/e273b845604add74b5a25dfd931cb3c166b1008f/ogham-sms-cloudhopper/src/main/java/fr/sii/ogham/sms/builder/cloudhopper/CharsetBuilder.java#L82-L85 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.callMethod | protected T callMethod(IFacebookMethod method, Pair<String, CharSequence>... paramPairs)
throws FacebookException, IOException {
"""
Call the specified method, with the given parameters, and return a DOM tree with the results.
@param method the fieldName of the method
@param paramPairs a list of arguments to the method
@throws Exception with a description of any errors given to us by the server.
"""
return callMethod(method, Arrays.asList(paramPairs));
} | java | protected T callMethod(IFacebookMethod method, Pair<String, CharSequence>... paramPairs)
throws FacebookException, IOException {
return callMethod(method, Arrays.asList(paramPairs));
} | [
"protected",
"T",
"callMethod",
"(",
"IFacebookMethod",
"method",
",",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
"...",
"paramPairs",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"return",
"callMethod",
"(",
"method",
",",
"Arrays",
".",
"asList",
"(",
"paramPairs",
")",
")",
";",
"}"
] | Call the specified method, with the given parameters, and return a DOM tree with the results.
@param method the fieldName of the method
@param paramPairs a list of arguments to the method
@throws Exception with a description of any errors given to us by the server. | [
"Call",
"the",
"specified",
"method",
"with",
"the",
"given",
"parameters",
"and",
"return",
"a",
"DOM",
"tree",
"with",
"the",
"results",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L651-L654 |
logic-ng/LogicNG | src/main/java/org/logicng/io/parsers/FormulaParser.java | FormulaParser.setLexerAndParser | void setLexerAndParser(final Lexer lexer, final ParserWithFormula parser) {
"""
Sets the internal lexer and the parser.
@param lexer the lexer
@param parser the parser
"""
this.lexer = lexer;
this.parser = parser;
this.parser.setFormulaFactory(this.f);
this.lexer.removeErrorListeners();
this.parser.removeErrorListeners();
this.parser.setErrorHandler(new BailErrorStrategy());
} | java | void setLexerAndParser(final Lexer lexer, final ParserWithFormula parser) {
this.lexer = lexer;
this.parser = parser;
this.parser.setFormulaFactory(this.f);
this.lexer.removeErrorListeners();
this.parser.removeErrorListeners();
this.parser.setErrorHandler(new BailErrorStrategy());
} | [
"void",
"setLexerAndParser",
"(",
"final",
"Lexer",
"lexer",
",",
"final",
"ParserWithFormula",
"parser",
")",
"{",
"this",
".",
"lexer",
"=",
"lexer",
";",
"this",
".",
"parser",
"=",
"parser",
";",
"this",
".",
"parser",
".",
"setFormulaFactory",
"(",
"this",
".",
"f",
")",
";",
"this",
".",
"lexer",
".",
"removeErrorListeners",
"(",
")",
";",
"this",
".",
"parser",
".",
"removeErrorListeners",
"(",
")",
";",
"this",
".",
"parser",
".",
"setErrorHandler",
"(",
"new",
"BailErrorStrategy",
"(",
")",
")",
";",
"}"
] | Sets the internal lexer and the parser.
@param lexer the lexer
@param parser the parser | [
"Sets",
"the",
"internal",
"lexer",
"and",
"the",
"parser",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/io/parsers/FormulaParser.java#L67-L74 |
auth0/auth0-java | src/main/java/com/auth0/client/auth/LogoutUrlBuilder.java | LogoutUrlBuilder.newInstance | static LogoutUrlBuilder newInstance(HttpUrl baseUrl, String clientId, String returnToUrl, boolean setClientId) {
"""
Creates a instance of the {@link LogoutUrlBuilder} using the given domain and base parameters.
@param baseUrl the base url constructed from a valid domain.
@param clientId the application's client_id value to set
@param returnToUrl the returnTo value to set. Must be already URL Encoded and must be white-listed in your Auth0's dashboard.
@param setClientId whether the client_id value must be set or not. This affects the white-list that the Auth0's Dashboard uses to validate the returnTo url.
If the client_id is set, the white-list is read from the Application's settings. If the client_id is not set, the white-list is read from the Tenant's settings.
@return a new instance of the {@link LogoutUrlBuilder} to configure.
"""
return new LogoutUrlBuilder(baseUrl, setClientId ? clientId : null, returnToUrl);
} | java | static LogoutUrlBuilder newInstance(HttpUrl baseUrl, String clientId, String returnToUrl, boolean setClientId) {
return new LogoutUrlBuilder(baseUrl, setClientId ? clientId : null, returnToUrl);
} | [
"static",
"LogoutUrlBuilder",
"newInstance",
"(",
"HttpUrl",
"baseUrl",
",",
"String",
"clientId",
",",
"String",
"returnToUrl",
",",
"boolean",
"setClientId",
")",
"{",
"return",
"new",
"LogoutUrlBuilder",
"(",
"baseUrl",
",",
"setClientId",
"?",
"clientId",
":",
"null",
",",
"returnToUrl",
")",
";",
"}"
] | Creates a instance of the {@link LogoutUrlBuilder} using the given domain and base parameters.
@param baseUrl the base url constructed from a valid domain.
@param clientId the application's client_id value to set
@param returnToUrl the returnTo value to set. Must be already URL Encoded and must be white-listed in your Auth0's dashboard.
@param setClientId whether the client_id value must be set or not. This affects the white-list that the Auth0's Dashboard uses to validate the returnTo url.
If the client_id is set, the white-list is read from the Application's settings. If the client_id is not set, the white-list is read from the Tenant's settings.
@return a new instance of the {@link LogoutUrlBuilder} to configure. | [
"Creates",
"a",
"instance",
"of",
"the",
"{",
"@link",
"LogoutUrlBuilder",
"}",
"using",
"the",
"given",
"domain",
"and",
"base",
"parameters",
"."
] | train | https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/LogoutUrlBuilder.java#L29-L31 |
apache/incubator-gobblin | gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java | AzkabanClient.deleteProject | public AzkabanClientStatus deleteProject(String projectName) throws AzkabanClientException {
"""
Deletes a project. Currently no response message will be returned after finishing
the delete operation. Thus success status is always expected.
@param projectName project name
@return A status object indicating if AJAX request is successful.
"""
AzkabanMultiCallables.DeleteProjectCallable callable =
AzkabanMultiCallables.DeleteProjectCallable.builder()
.client(this)
.projectName(projectName)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
} | java | public AzkabanClientStatus deleteProject(String projectName) throws AzkabanClientException {
AzkabanMultiCallables.DeleteProjectCallable callable =
AzkabanMultiCallables.DeleteProjectCallable.builder()
.client(this)
.projectName(projectName)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
} | [
"public",
"AzkabanClientStatus",
"deleteProject",
"(",
"String",
"projectName",
")",
"throws",
"AzkabanClientException",
"{",
"AzkabanMultiCallables",
".",
"DeleteProjectCallable",
"callable",
"=",
"AzkabanMultiCallables",
".",
"DeleteProjectCallable",
".",
"builder",
"(",
")",
".",
"client",
"(",
"this",
")",
".",
"projectName",
"(",
"projectName",
")",
".",
"build",
"(",
")",
";",
"return",
"runWithRetry",
"(",
"callable",
",",
"AzkabanClientStatus",
".",
"class",
")",
";",
"}"
] | Deletes a project. Currently no response message will be returned after finishing
the delete operation. Thus success status is always expected.
@param projectName project name
@return A status object indicating if AJAX request is successful. | [
"Deletes",
"a",
"project",
".",
"Currently",
"no",
"response",
"message",
"will",
"be",
"returned",
"after",
"finishing",
"the",
"delete",
"operation",
".",
"Thus",
"success",
"status",
"is",
"always",
"expected",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java#L298-L307 |
SonarSource/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/PathResolver.java | PathResolver.relativePath | @CheckForNull
public String relativePath(Path dir, Path file) {
"""
Similar to {@link Path#relativize(Path)} except that:
<ul>
<li>null is returned if file is not a child of dir
<li>the resulting path is converted to use Unix separators
</ul>
@since 6.0
"""
Path baseDir = dir.normalize();
Path path = file.normalize();
if (!path.startsWith(baseDir)) {
return null;
}
try {
Path relativized = baseDir.relativize(path);
return FilenameUtils.separatorsToUnix(relativized.toString());
} catch (IllegalArgumentException e) {
return null;
}
} | java | @CheckForNull
public String relativePath(Path dir, Path file) {
Path baseDir = dir.normalize();
Path path = file.normalize();
if (!path.startsWith(baseDir)) {
return null;
}
try {
Path relativized = baseDir.relativize(path);
return FilenameUtils.separatorsToUnix(relativized.toString());
} catch (IllegalArgumentException e) {
return null;
}
} | [
"@",
"CheckForNull",
"public",
"String",
"relativePath",
"(",
"Path",
"dir",
",",
"Path",
"file",
")",
"{",
"Path",
"baseDir",
"=",
"dir",
".",
"normalize",
"(",
")",
";",
"Path",
"path",
"=",
"file",
".",
"normalize",
"(",
")",
";",
"if",
"(",
"!",
"path",
".",
"startsWith",
"(",
"baseDir",
")",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"Path",
"relativized",
"=",
"baseDir",
".",
"relativize",
"(",
"path",
")",
";",
"return",
"FilenameUtils",
".",
"separatorsToUnix",
"(",
"relativized",
".",
"toString",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Similar to {@link Path#relativize(Path)} except that:
<ul>
<li>null is returned if file is not a child of dir
<li>the resulting path is converted to use Unix separators
</ul>
@since 6.0 | [
"Similar",
"to",
"{"
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/PathResolver.java#L82-L95 |
facebookarchive/hadoop-20 | src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/CapBasedLoadManager.java | CapBasedLoadManager.getCap | int getCap(int totalRunnableTasks, int localMaxTasks, int totalSlots) {
"""
Determine how many tasks of a given type we want to run on a TaskTracker.
This cap is chosen based on how many tasks of that type are outstanding in
total, so that when the cluster is used below capacity, tasks are spread
out uniformly across the nodes rather than being clumped up on whichever
machines sent out heartbeats earliest.
"""
double load = maxDiff + ((double)totalRunnableTasks) / totalSlots;
int cap = (int) Math.min(localMaxTasks, Math.ceil(load * localMaxTasks));
if (LOG.isDebugEnabled()) {
LOG.debug("load:" + load + " maxDiff:" + maxDiff +
" totalRunnable:" + totalRunnableTasks + " totalSlots:" + totalSlots +
" localMaxTasks:" + localMaxTasks +
" cap:" + cap);
}
return cap;
} | java | int getCap(int totalRunnableTasks, int localMaxTasks, int totalSlots) {
double load = maxDiff + ((double)totalRunnableTasks) / totalSlots;
int cap = (int) Math.min(localMaxTasks, Math.ceil(load * localMaxTasks));
if (LOG.isDebugEnabled()) {
LOG.debug("load:" + load + " maxDiff:" + maxDiff +
" totalRunnable:" + totalRunnableTasks + " totalSlots:" + totalSlots +
" localMaxTasks:" + localMaxTasks +
" cap:" + cap);
}
return cap;
} | [
"int",
"getCap",
"(",
"int",
"totalRunnableTasks",
",",
"int",
"localMaxTasks",
",",
"int",
"totalSlots",
")",
"{",
"double",
"load",
"=",
"maxDiff",
"+",
"(",
"(",
"double",
")",
"totalRunnableTasks",
")",
"/",
"totalSlots",
";",
"int",
"cap",
"=",
"(",
"int",
")",
"Math",
".",
"min",
"(",
"localMaxTasks",
",",
"Math",
".",
"ceil",
"(",
"load",
"*",
"localMaxTasks",
")",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"load:\"",
"+",
"load",
"+",
"\" maxDiff:\"",
"+",
"maxDiff",
"+",
"\" totalRunnable:\"",
"+",
"totalRunnableTasks",
"+",
"\" totalSlots:\"",
"+",
"totalSlots",
"+",
"\" localMaxTasks:\"",
"+",
"localMaxTasks",
"+",
"\" cap:\"",
"+",
"cap",
")",
";",
"}",
"return",
"cap",
";",
"}"
] | Determine how many tasks of a given type we want to run on a TaskTracker.
This cap is chosen based on how many tasks of that type are outstanding in
total, so that when the cluster is used below capacity, tasks are spread
out uniformly across the nodes rather than being clumped up on whichever
machines sent out heartbeats earliest. | [
"Determine",
"how",
"many",
"tasks",
"of",
"a",
"given",
"type",
"we",
"want",
"to",
"run",
"on",
"a",
"TaskTracker",
".",
"This",
"cap",
"is",
"chosen",
"based",
"on",
"how",
"many",
"tasks",
"of",
"that",
"type",
"are",
"outstanding",
"in",
"total",
"so",
"that",
"when",
"the",
"cluster",
"is",
"used",
"below",
"capacity",
"tasks",
"are",
"spread",
"out",
"uniformly",
"across",
"the",
"nodes",
"rather",
"than",
"being",
"clumped",
"up",
"on",
"whichever",
"machines",
"sent",
"out",
"heartbeats",
"earliest",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/CapBasedLoadManager.java#L96-L106 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java | BigDecimalMath.log2 | public static BigDecimal log2(BigDecimal x, MathContext mathContext) {
"""
Calculates the logarithm of {@link BigDecimal} x to the base 2.
@param x the {@link BigDecimal} to calculate the logarithm base 2 for
@param mathContext the {@link MathContext} used for the result
@return the calculated natural logarithm {@link BigDecimal} to the base 2 with the precision specified in the <code>mathContext</code>
@throws ArithmeticException if x <= 0
@throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
"""
checkMathContext(mathContext);
MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
BigDecimal result = log(x, mc).divide(logTwo(mc), mc);
return round(result, mathContext);
} | java | public static BigDecimal log2(BigDecimal x, MathContext mathContext) {
checkMathContext(mathContext);
MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
BigDecimal result = log(x, mc).divide(logTwo(mc), mc);
return round(result, mathContext);
} | [
"public",
"static",
"BigDecimal",
"log2",
"(",
"BigDecimal",
"x",
",",
"MathContext",
"mathContext",
")",
"{",
"checkMathContext",
"(",
"mathContext",
")",
";",
"MathContext",
"mc",
"=",
"new",
"MathContext",
"(",
"mathContext",
".",
"getPrecision",
"(",
")",
"+",
"4",
",",
"mathContext",
".",
"getRoundingMode",
"(",
")",
")",
";",
"BigDecimal",
"result",
"=",
"log",
"(",
"x",
",",
"mc",
")",
".",
"divide",
"(",
"logTwo",
"(",
"mc",
")",
",",
"mc",
")",
";",
"return",
"round",
"(",
"result",
",",
"mathContext",
")",
";",
"}"
] | Calculates the logarithm of {@link BigDecimal} x to the base 2.
@param x the {@link BigDecimal} to calculate the logarithm base 2 for
@param mathContext the {@link MathContext} used for the result
@return the calculated natural logarithm {@link BigDecimal} to the base 2 with the precision specified in the <code>mathContext</code>
@throws ArithmeticException if x <= 0
@throws UnsupportedOperationException if the {@link MathContext} has unlimited precision | [
"Calculates",
"the",
"logarithm",
"of",
"{",
"@link",
"BigDecimal",
"}",
"x",
"to",
"the",
"base",
"2",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java#L919-L925 |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getProperty | public static String getProperty(String name, String defaultValue) {
"""
Get the value of the property with the given name. If the named property is not found,
returns the supplied default value. This error handling behavior makes this method attractive
for use in static initializers.
@param name - the name of the property to be retrieved.
@param defaultValue - a fallback default value which will be returned if the property cannot
be found.
@return the value of the requested property, or the supplied default value if the named
property cannot be found.
@since 2.4
"""
if (PropertiesManager.props == null) loadProps();
String returnValue = defaultValue;
try {
returnValue = getProperty(name);
} catch (MissingPropertyException mpe) {
// Do nothing, since we have already recorded and logged the missing property.
}
return returnValue;
} | java | public static String getProperty(String name, String defaultValue) {
if (PropertiesManager.props == null) loadProps();
String returnValue = defaultValue;
try {
returnValue = getProperty(name);
} catch (MissingPropertyException mpe) {
// Do nothing, since we have already recorded and logged the missing property.
}
return returnValue;
} | [
"public",
"static",
"String",
"getProperty",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"String",
"returnValue",
"=",
"defaultValue",
";",
"try",
"{",
"returnValue",
"=",
"getProperty",
"(",
"name",
")",
";",
"}",
"catch",
"(",
"MissingPropertyException",
"mpe",
")",
"{",
"// Do nothing, since we have already recorded and logged the missing property.",
"}",
"return",
"returnValue",
";",
"}"
] | Get the value of the property with the given name. If the named property is not found,
returns the supplied default value. This error handling behavior makes this method attractive
for use in static initializers.
@param name - the name of the property to be retrieved.
@param defaultValue - a fallback default value which will be returned if the property cannot
be found.
@return the value of the requested property, or the supplied default value if the named
property cannot be found.
@since 2.4 | [
"Get",
"the",
"value",
"of",
"the",
"property",
"with",
"the",
"given",
"name",
".",
"If",
"the",
"named",
"property",
"is",
"not",
"found",
"returns",
"the",
"supplied",
"default",
"value",
".",
"This",
"error",
"handling",
"behavior",
"makes",
"this",
"method",
"attractive",
"for",
"use",
"in",
"static",
"initializers",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L329-L338 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/notification/ClientNotificationArea.java | ClientNotificationArea.updateClientNotificationListener | public void updateClientNotificationListener(RESTRequest request, String objectNameStr, NotificationFilter[] filters, JSONConverter converter) {
"""
Update the listener for the given object name with the provided filters
"""
NotificationTargetInformation nti = toNotificationTargetInformation(request, objectNameStr);
ClientNotificationListener listener = listeners.get(nti);
if (listener == null) {
throw ErrorHelper.createRESTHandlerJsonException(new RuntimeException("There are no listeners registered for " + nti), converter, APIConstants.STATUS_BAD_REQUEST);
}
//Make the update
listener.addClientNotification(filters);
} | java | public void updateClientNotificationListener(RESTRequest request, String objectNameStr, NotificationFilter[] filters, JSONConverter converter) {
NotificationTargetInformation nti = toNotificationTargetInformation(request, objectNameStr);
ClientNotificationListener listener = listeners.get(nti);
if (listener == null) {
throw ErrorHelper.createRESTHandlerJsonException(new RuntimeException("There are no listeners registered for " + nti), converter, APIConstants.STATUS_BAD_REQUEST);
}
//Make the update
listener.addClientNotification(filters);
} | [
"public",
"void",
"updateClientNotificationListener",
"(",
"RESTRequest",
"request",
",",
"String",
"objectNameStr",
",",
"NotificationFilter",
"[",
"]",
"filters",
",",
"JSONConverter",
"converter",
")",
"{",
"NotificationTargetInformation",
"nti",
"=",
"toNotificationTargetInformation",
"(",
"request",
",",
"objectNameStr",
")",
";",
"ClientNotificationListener",
"listener",
"=",
"listeners",
".",
"get",
"(",
"nti",
")",
";",
"if",
"(",
"listener",
"==",
"null",
")",
"{",
"throw",
"ErrorHelper",
".",
"createRESTHandlerJsonException",
"(",
"new",
"RuntimeException",
"(",
"\"There are no listeners registered for \"",
"+",
"nti",
")",
",",
"converter",
",",
"APIConstants",
".",
"STATUS_BAD_REQUEST",
")",
";",
"}",
"//Make the update",
"listener",
".",
"addClientNotification",
"(",
"filters",
")",
";",
"}"
] | Update the listener for the given object name with the provided filters | [
"Update",
"the",
"listener",
"for",
"the",
"given",
"object",
"name",
"with",
"the",
"provided",
"filters"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/notification/ClientNotificationArea.java#L265-L276 |
sarl/sarl | sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/JanusConfig.java | JanusConfig.getSystemPropertyAsBoolean | public static boolean getSystemPropertyAsBoolean(String name, boolean defaultValue) {
"""
Replies the value of the boolean system property.
@param name
- name of the property.
@param defaultValue
- value to reply if the these is no property found
@return the value, or defaultValue.
"""
final String value = getSystemProperty(name, null);
if (value != null) {
try {
return Boolean.parseBoolean(value);
} catch (Throwable exception) {
//
}
}
return defaultValue;
} | java | public static boolean getSystemPropertyAsBoolean(String name, boolean defaultValue) {
final String value = getSystemProperty(name, null);
if (value != null) {
try {
return Boolean.parseBoolean(value);
} catch (Throwable exception) {
//
}
}
return defaultValue;
} | [
"public",
"static",
"boolean",
"getSystemPropertyAsBoolean",
"(",
"String",
"name",
",",
"boolean",
"defaultValue",
")",
"{",
"final",
"String",
"value",
"=",
"getSystemProperty",
"(",
"name",
",",
"null",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"Boolean",
".",
"parseBoolean",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"Throwable",
"exception",
")",
"{",
"//",
"}",
"}",
"return",
"defaultValue",
";",
"}"
] | Replies the value of the boolean system property.
@param name
- name of the property.
@param defaultValue
- value to reply if the these is no property found
@return the value, or defaultValue. | [
"Replies",
"the",
"value",
"of",
"the",
"boolean",
"system",
"property",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/JanusConfig.java#L353-L363 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java | Cursor.setArea | public void setArea(int minX, int minY, int maxX, int maxY) {
"""
Allows cursor to move only inside the specified area. The cursor location will not exceed this area.
@param minX The minimal x.
@param minY The minimal y.
@param maxX The maximal x.
@param maxY The maximal y.
"""
this.minX = Math.min(minX, maxX);
this.minY = Math.min(minY, maxY);
this.maxX = Math.max(maxX, minX);
this.maxY = Math.max(maxY, minY);
} | java | public void setArea(int minX, int minY, int maxX, int maxY)
{
this.minX = Math.min(minX, maxX);
this.minY = Math.min(minY, maxY);
this.maxX = Math.max(maxX, minX);
this.maxY = Math.max(maxY, minY);
} | [
"public",
"void",
"setArea",
"(",
"int",
"minX",
",",
"int",
"minY",
",",
"int",
"maxX",
",",
"int",
"maxY",
")",
"{",
"this",
".",
"minX",
"=",
"Math",
".",
"min",
"(",
"minX",
",",
"maxX",
")",
";",
"this",
".",
"minY",
"=",
"Math",
".",
"min",
"(",
"minY",
",",
"maxY",
")",
";",
"this",
".",
"maxX",
"=",
"Math",
".",
"max",
"(",
"maxX",
",",
"minX",
")",
";",
"this",
".",
"maxY",
"=",
"Math",
".",
"max",
"(",
"maxY",
",",
"minY",
")",
";",
"}"
] | Allows cursor to move only inside the specified area. The cursor location will not exceed this area.
@param minX The minimal x.
@param minY The minimal y.
@param maxX The maximal x.
@param maxY The maximal y. | [
"Allows",
"cursor",
"to",
"move",
"only",
"inside",
"the",
"specified",
"area",
".",
"The",
"cursor",
"location",
"will",
"not",
"exceed",
"this",
"area",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java#L214-L220 |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java | ClusterComputeResourceService.createVmOverrideConfiguration | private ClusterDasVmConfigInfo createVmOverrideConfiguration(ManagedObjectReference vmMor, String restartPriority) {
"""
Das method adds a vm override to a HA enabled Cluster.
@param vmMor
@param restartPriority
@return
"""
ClusterDasVmConfigInfo clusterDasVmConfigInfo = new ClusterDasVmConfigInfo();
clusterDasVmConfigInfo.setKey(vmMor);
clusterDasVmConfigInfo.setDasSettings(createClusterDasVmSettings(restartPriority));
return clusterDasVmConfigInfo;
} | java | private ClusterDasVmConfigInfo createVmOverrideConfiguration(ManagedObjectReference vmMor, String restartPriority) {
ClusterDasVmConfigInfo clusterDasVmConfigInfo = new ClusterDasVmConfigInfo();
clusterDasVmConfigInfo.setKey(vmMor);
clusterDasVmConfigInfo.setDasSettings(createClusterDasVmSettings(restartPriority));
return clusterDasVmConfigInfo;
} | [
"private",
"ClusterDasVmConfigInfo",
"createVmOverrideConfiguration",
"(",
"ManagedObjectReference",
"vmMor",
",",
"String",
"restartPriority",
")",
"{",
"ClusterDasVmConfigInfo",
"clusterDasVmConfigInfo",
"=",
"new",
"ClusterDasVmConfigInfo",
"(",
")",
";",
"clusterDasVmConfigInfo",
".",
"setKey",
"(",
"vmMor",
")",
";",
"clusterDasVmConfigInfo",
".",
"setDasSettings",
"(",
"createClusterDasVmSettings",
"(",
"restartPriority",
")",
")",
";",
"return",
"clusterDasVmConfigInfo",
";",
"}"
] | Das method adds a vm override to a HA enabled Cluster.
@param vmMor
@param restartPriority
@return | [
"Das",
"method",
"adds",
"a",
"vm",
"override",
"to",
"a",
"HA",
"enabled",
"Cluster",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java#L423-L428 |
hawkular/hawkular-apm | client/instrumenter/src/main/java/org/hawkular/apm/instrumenter/RuleHelper.java | RuleHelper.appendOutBuffer | public void appendOutBuffer(Object obj, byte[] data, int offset, int len, boolean close) {
"""
This method appends data to the buffer associated with the supplied object.
@param obj The object associated with the buffer
@param data The data to be appended
@param offset The offset of the data
@param len The length of data
@param close Whether to close the buffer after appending the data
"""
if (len > 0) {
collector().appendOutBuffer(getRuleName(), obj, data, offset, len);
}
if (close) {
collector().recordOutBuffer(getRuleName(), obj);
}
} | java | public void appendOutBuffer(Object obj, byte[] data, int offset, int len, boolean close) {
if (len > 0) {
collector().appendOutBuffer(getRuleName(), obj, data, offset, len);
}
if (close) {
collector().recordOutBuffer(getRuleName(), obj);
}
} | [
"public",
"void",
"appendOutBuffer",
"(",
"Object",
"obj",
",",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"len",
",",
"boolean",
"close",
")",
"{",
"if",
"(",
"len",
">",
"0",
")",
"{",
"collector",
"(",
")",
".",
"appendOutBuffer",
"(",
"getRuleName",
"(",
")",
",",
"obj",
",",
"data",
",",
"offset",
",",
"len",
")",
";",
"}",
"if",
"(",
"close",
")",
"{",
"collector",
"(",
")",
".",
"recordOutBuffer",
"(",
"getRuleName",
"(",
")",
",",
"obj",
")",
";",
"}",
"}"
] | This method appends data to the buffer associated with the supplied object.
@param obj The object associated with the buffer
@param data The data to be appended
@param offset The offset of the data
@param len The length of data
@param close Whether to close the buffer after appending the data | [
"This",
"method",
"appends",
"data",
"to",
"the",
"buffer",
"associated",
"with",
"the",
"supplied",
"object",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/instrumenter/src/main/java/org/hawkular/apm/instrumenter/RuleHelper.java#L530-L537 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/impl/CacheLoaderInterceptor.java | CacheLoaderInterceptor.loadIfNeeded | protected final CompletionStage<Void> loadIfNeeded(final InvocationContext ctx, Object key, final FlagAffectedCommand cmd) {
"""
Loads from the cache loader the entry for the given key. A found value is loaded into the current context. The
method returns whether the value was found or not, or even if the cache loader was checked.
@param ctx The current invocation's context
@param key The key for the entry to look up
@param cmd The command that was called that now wants to query the cache loader
@return null or a CompletionStage that when complete all listeners will be notified
@throws Throwable
"""
if (skipLoad(cmd, key, ctx)) {
return null;
}
return loadInContext(ctx, key, cmd);
} | java | protected final CompletionStage<Void> loadIfNeeded(final InvocationContext ctx, Object key, final FlagAffectedCommand cmd) {
if (skipLoad(cmd, key, ctx)) {
return null;
}
return loadInContext(ctx, key, cmd);
} | [
"protected",
"final",
"CompletionStage",
"<",
"Void",
">",
"loadIfNeeded",
"(",
"final",
"InvocationContext",
"ctx",
",",
"Object",
"key",
",",
"final",
"FlagAffectedCommand",
"cmd",
")",
"{",
"if",
"(",
"skipLoad",
"(",
"cmd",
",",
"key",
",",
"ctx",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"loadInContext",
"(",
"ctx",
",",
"key",
",",
"cmd",
")",
";",
"}"
] | Loads from the cache loader the entry for the given key. A found value is loaded into the current context. The
method returns whether the value was found or not, or even if the cache loader was checked.
@param ctx The current invocation's context
@param key The key for the entry to look up
@param cmd The command that was called that now wants to query the cache loader
@return null or a CompletionStage that when complete all listeners will be notified
@throws Throwable | [
"Loads",
"from",
"the",
"cache",
"loader",
"the",
"entry",
"for",
"the",
"given",
"key",
".",
"A",
"found",
"value",
"is",
"loaded",
"into",
"the",
"current",
"context",
".",
"The",
"method",
"returns",
"whether",
"the",
"value",
"was",
"found",
"or",
"not",
"or",
"even",
"if",
"the",
"cache",
"loader",
"was",
"checked",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/impl/CacheLoaderInterceptor.java#L342-L348 |
Subsets and Splits