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
|
---|---|---|---|---|---|---|---|---|---|---|
akquinet/androlog | androlog/src/main/java/de/akquinet/android/androlog/LogHelper.java | LogHelper.println | public static int println(int priority, String tag, String msg) {
"""
Low-level logging call.
@param priority
The priority/type of this log message
@param tag
Used to identify the source of a log message. It usually
identifies the class or activity where the log call occurs.
@param msg
The message you would like logged.
@return The number of bytes written.
"""
return android.util.Log.println(priority, tag, msg);
} | java | public static int println(int priority, String tag, String msg) {
return android.util.Log.println(priority, tag, msg);
} | [
"public",
"static",
"int",
"println",
"(",
"int",
"priority",
",",
"String",
"tag",
",",
"String",
"msg",
")",
"{",
"return",
"android",
".",
"util",
".",
"Log",
".",
"println",
"(",
"priority",
",",
"tag",
",",
"msg",
")",
";",
"}"
] | Low-level logging call.
@param priority
The priority/type of this log message
@param tag
Used to identify the source of a log message. It usually
identifies the class or activity where the log call occurs.
@param msg
The message you would like logged.
@return The number of bytes written. | [
"Low",
"-",
"level",
"logging",
"call",
"."
] | train | https://github.com/akquinet/androlog/blob/82fa81354c01c9b1d1928062b634ba21f14be560/androlog/src/main/java/de/akquinet/android/androlog/LogHelper.java#L183-L185 |
elastic/elasticsearch-hadoop | mr/src/main/java/org/elasticsearch/hadoop/serialization/dto/mapping/FieldParser.java | FieldParser.parseMappings | public static MappingSet parseMappings(Map<String, Object> content, boolean includeTypeName) {
"""
Convert the deserialized mapping request body into an object
@param content entire mapping request body for all indices and types
@param includeTypeName true if the given content to be parsed includes type names within the structure,
or false if it is in the typeless format
@return MappingSet for that response.
"""
Iterator<Map.Entry<String, Object>> indices = content.entrySet().iterator();
List<Mapping> indexMappings = new ArrayList<Mapping>();
while(indices.hasNext()) {
// These mappings are ordered by index, then optionally type.
parseIndexMappings(indices.next(), indexMappings, includeTypeName);
}
return new MappingSet(indexMappings);
} | java | public static MappingSet parseMappings(Map<String, Object> content, boolean includeTypeName) {
Iterator<Map.Entry<String, Object>> indices = content.entrySet().iterator();
List<Mapping> indexMappings = new ArrayList<Mapping>();
while(indices.hasNext()) {
// These mappings are ordered by index, then optionally type.
parseIndexMappings(indices.next(), indexMappings, includeTypeName);
}
return new MappingSet(indexMappings);
} | [
"public",
"static",
"MappingSet",
"parseMappings",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"content",
",",
"boolean",
"includeTypeName",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
">",
"indices",
"=",
"content",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"List",
"<",
"Mapping",
">",
"indexMappings",
"=",
"new",
"ArrayList",
"<",
"Mapping",
">",
"(",
")",
";",
"while",
"(",
"indices",
".",
"hasNext",
"(",
")",
")",
"{",
"// These mappings are ordered by index, then optionally type.",
"parseIndexMappings",
"(",
"indices",
".",
"next",
"(",
")",
",",
"indexMappings",
",",
"includeTypeName",
")",
";",
"}",
"return",
"new",
"MappingSet",
"(",
"indexMappings",
")",
";",
"}"
] | Convert the deserialized mapping request body into an object
@param content entire mapping request body for all indices and types
@param includeTypeName true if the given content to be parsed includes type names within the structure,
or false if it is in the typeless format
@return MappingSet for that response. | [
"Convert",
"the",
"deserialized",
"mapping",
"request",
"body",
"into",
"an",
"object"
] | train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/serialization/dto/mapping/FieldParser.java#L54-L62 |
EsotericSoftware/kryo | src/com/esotericsoftware/kryo/unsafe/UnsafeOutput.java | UnsafeOutput.writeBytes | public void writeBytes (Object from, long offset, int count) throws KryoException {
"""
Write count bytes to the byte buffer, reading from the given offset inside the in-memory representation of the object.
"""
int copyCount = Math.min(capacity - position, count);
while (true) {
unsafe.copyMemory(from, offset, buffer, byteArrayBaseOffset + position, copyCount);
position += copyCount;
count -= copyCount;
if (count == 0) break;
offset += copyCount;
copyCount = Math.min(capacity, count);
require(copyCount);
}
} | java | public void writeBytes (Object from, long offset, int count) throws KryoException {
int copyCount = Math.min(capacity - position, count);
while (true) {
unsafe.copyMemory(from, offset, buffer, byteArrayBaseOffset + position, copyCount);
position += copyCount;
count -= copyCount;
if (count == 0) break;
offset += copyCount;
copyCount = Math.min(capacity, count);
require(copyCount);
}
} | [
"public",
"void",
"writeBytes",
"(",
"Object",
"from",
",",
"long",
"offset",
",",
"int",
"count",
")",
"throws",
"KryoException",
"{",
"int",
"copyCount",
"=",
"Math",
".",
"min",
"(",
"capacity",
"-",
"position",
",",
"count",
")",
";",
"while",
"(",
"true",
")",
"{",
"unsafe",
".",
"copyMemory",
"(",
"from",
",",
"offset",
",",
"buffer",
",",
"byteArrayBaseOffset",
"+",
"position",
",",
"copyCount",
")",
";",
"position",
"+=",
"copyCount",
";",
"count",
"-=",
"copyCount",
";",
"if",
"(",
"count",
"==",
"0",
")",
"break",
";",
"offset",
"+=",
"copyCount",
";",
"copyCount",
"=",
"Math",
".",
"min",
"(",
"capacity",
",",
"count",
")",
";",
"require",
"(",
"copyCount",
")",
";",
"}",
"}"
] | Write count bytes to the byte buffer, reading from the given offset inside the in-memory representation of the object. | [
"Write",
"count",
"bytes",
"to",
"the",
"byte",
"buffer",
"reading",
"from",
"the",
"given",
"offset",
"inside",
"the",
"in",
"-",
"memory",
"representation",
"of",
"the",
"object",
"."
] | train | https://github.com/EsotericSoftware/kryo/blob/a8be1ab26f347f299a3c3f7171d6447dd5390845/src/com/esotericsoftware/kryo/unsafe/UnsafeOutput.java#L170-L181 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/io/GVRGearCursorController.java | GVRGearCursorController.setPosition | @Override
public void setPosition(float x, float y, float z) {
"""
Set the position of the pick ray.
This function is used internally to update the
pick ray with the new controller position.
@param x the x value of the position.
@param y the y value of the position.
@param z the z value of the position.
"""
position.set(x, y, z);
pickDir.set(x, y, z);
pickDir.normalize();
invalidate();
} | java | @Override
public void setPosition(float x, float y, float z)
{
position.set(x, y, z);
pickDir.set(x, y, z);
pickDir.normalize();
invalidate();
} | [
"@",
"Override",
"public",
"void",
"setPosition",
"(",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"position",
".",
"set",
"(",
"x",
",",
"y",
",",
"z",
")",
";",
"pickDir",
".",
"set",
"(",
"x",
",",
"y",
",",
"z",
")",
";",
"pickDir",
".",
"normalize",
"(",
")",
";",
"invalidate",
"(",
")",
";",
"}"
] | Set the position of the pick ray.
This function is used internally to update the
pick ray with the new controller position.
@param x the x value of the position.
@param y the y value of the position.
@param z the z value of the position. | [
"Set",
"the",
"position",
"of",
"the",
"pick",
"ray",
".",
"This",
"function",
"is",
"used",
"internally",
"to",
"update",
"the",
"pick",
"ray",
"with",
"the",
"new",
"controller",
"position",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/io/GVRGearCursorController.java#L338-L345 |
contentful/contentful.java | src/main/java/com/contentful/java/cda/image/ImageOption.java | ImageOption.backgroundColorOf | public static ImageOption backgroundColorOf(int color) {
"""
Define a background color.
<p>
The color value must be a hexadecimal value, i.e. 0xFF0000 means red.
@param color the color in hex to be used.
@return an image option for manipulating a given url.
@throws IllegalArgumentException if the color is less then zero or greater then 0xFFFFFF.
"""
if (color < 0 || color > 0xFFFFFF) {
throw new IllegalArgumentException("Color must be in rgb hex range of 0x0 to 0xFFFFFF.");
}
return new ImageOption("bg", "rgb:" + format(Locale.getDefault(), "%06X", color));
} | java | public static ImageOption backgroundColorOf(int color) {
if (color < 0 || color > 0xFFFFFF) {
throw new IllegalArgumentException("Color must be in rgb hex range of 0x0 to 0xFFFFFF.");
}
return new ImageOption("bg", "rgb:" + format(Locale.getDefault(), "%06X", color));
} | [
"public",
"static",
"ImageOption",
"backgroundColorOf",
"(",
"int",
"color",
")",
"{",
"if",
"(",
"color",
"<",
"0",
"||",
"color",
">",
"0xFFFFFF",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Color must be in rgb hex range of 0x0 to 0xFFFFFF.\"",
")",
";",
"}",
"return",
"new",
"ImageOption",
"(",
"\"bg\"",
",",
"\"rgb:\"",
"+",
"format",
"(",
"Locale",
".",
"getDefault",
"(",
")",
",",
"\"%06X\"",
",",
"color",
")",
")",
";",
"}"
] | Define a background color.
<p>
The color value must be a hexadecimal value, i.e. 0xFF0000 means red.
@param color the color in hex to be used.
@return an image option for manipulating a given url.
@throws IllegalArgumentException if the color is less then zero or greater then 0xFFFFFF. | [
"Define",
"a",
"background",
"color",
".",
"<p",
">",
"The",
"color",
"value",
"must",
"be",
"a",
"hexadecimal",
"value",
"i",
".",
"e",
".",
"0xFF0000",
"means",
"red",
"."
] | train | https://github.com/contentful/contentful.java/blob/6ecc2ace454c674b218b99489dc50697b1dbffcb/src/main/java/com/contentful/java/cda/image/ImageOption.java#L244-L249 |
maguro/aunit | junit/src/main/java/com/toolazydogs/aunit/Assert.java | Assert.refuteParse | public static void refuteParse(SelectedRule rule, LexerResults lexerResults) {
"""
To "refute" a parse means that the scan cannot be parsed with the
specified rule.
<p/>
<pre>
refuteParse("program", myTester.scanInput("5 / * 8"));
</pre>
@param rule the rule to apply from the parser.
@param lexerResults the result of scanning input with the tester.
"""
try
{
lexerResults.parseAs(rule);
fail("parsed as " + rule);
}
catch (AssertionError e)
{
if (checkMessage(e.getMessage()))
{
// things are good
}
else
{
throw e;
}
}
} | java | public static void refuteParse(SelectedRule rule, LexerResults lexerResults)
{
try
{
lexerResults.parseAs(rule);
fail("parsed as " + rule);
}
catch (AssertionError e)
{
if (checkMessage(e.getMessage()))
{
// things are good
}
else
{
throw e;
}
}
} | [
"public",
"static",
"void",
"refuteParse",
"(",
"SelectedRule",
"rule",
",",
"LexerResults",
"lexerResults",
")",
"{",
"try",
"{",
"lexerResults",
".",
"parseAs",
"(",
"rule",
")",
";",
"fail",
"(",
"\"parsed as \"",
"+",
"rule",
")",
";",
"}",
"catch",
"(",
"AssertionError",
"e",
")",
"{",
"if",
"(",
"checkMessage",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"// things are good",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"}"
] | To "refute" a parse means that the scan cannot be parsed with the
specified rule.
<p/>
<pre>
refuteParse("program", myTester.scanInput("5 / * 8"));
</pre>
@param rule the rule to apply from the parser.
@param lexerResults the result of scanning input with the tester. | [
"To",
"refute",
"a",
"parse",
"means",
"that",
"the",
"scan",
"cannot",
"be",
"parsed",
"with",
"the",
"specified",
"rule",
".",
"<p",
"/",
">",
"<pre",
">",
"refuteParse",
"(",
""",
";",
"program"",
";",
"myTester",
".",
"scanInput",
"(",
""",
";",
"5",
"/",
"*",
"8"",
";",
"))",
";",
"<",
"/",
"pre",
">"
] | train | https://github.com/maguro/aunit/blob/1f972e35b28327e5e2e7881befc928df0546d74c/junit/src/main/java/com/toolazydogs/aunit/Assert.java#L196-L214 |
aws/aws-sdk-java | aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java | ValidationContext.assertIsPositiveIfPresent | public void assertIsPositiveIfPresent(Integer integer, String propertyName) {
"""
Asserts the integer is either null or positive, reporting to {@link ProblemReporter} with this context if it is.
@param integer Value to assert on.
@param propertyName Name of property.
"""
if (integer != null && integer <= 0) {
problemReporter.report(new Problem(this, String.format("%s must be positive", propertyName)));
}
} | java | public void assertIsPositiveIfPresent(Integer integer, String propertyName) {
if (integer != null && integer <= 0) {
problemReporter.report(new Problem(this, String.format("%s must be positive", propertyName)));
}
} | [
"public",
"void",
"assertIsPositiveIfPresent",
"(",
"Integer",
"integer",
",",
"String",
"propertyName",
")",
"{",
"if",
"(",
"integer",
"!=",
"null",
"&&",
"integer",
"<=",
"0",
")",
"{",
"problemReporter",
".",
"report",
"(",
"new",
"Problem",
"(",
"this",
",",
"String",
".",
"format",
"(",
"\"%s must be positive\"",
",",
"propertyName",
")",
")",
")",
";",
"}",
"}"
] | Asserts the integer is either null or positive, reporting to {@link ProblemReporter} with this context if it is.
@param integer Value to assert on.
@param propertyName Name of property. | [
"Asserts",
"the",
"integer",
"is",
"either",
"null",
"or",
"positive",
"reporting",
"to",
"{",
"@link",
"ProblemReporter",
"}",
"with",
"this",
"context",
"if",
"it",
"is",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java#L114-L118 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/mock/MockRequest.java | MockRequest.setParameter | public void setParameter(final String key, final String value) {
"""
Sets a parameter.
@param key the parameter key.
@param value the parameter value.
"""
parameters.put(key, new String[]{value});
} | java | public void setParameter(final String key, final String value) {
parameters.put(key, new String[]{value});
} | [
"public",
"void",
"setParameter",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"parameters",
".",
"put",
"(",
"key",
",",
"new",
"String",
"[",
"]",
"{",
"value",
"}",
")",
";",
"}"
] | Sets a parameter.
@param key the parameter key.
@param value the parameter value. | [
"Sets",
"a",
"parameter",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/mock/MockRequest.java#L70-L72 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/webapp/FacesInitializerFactory.java | FacesInitializerFactory._getFacesInitializerFromInitParam | private static FacesInitializer _getFacesInitializerFromInitParam(ServletContext context) {
"""
Gets a FacesInitializer from the web.xml config param.
@param context
@return
"""
String initializerClassName = context.getInitParameter(FACES_INITIALIZER_PARAM);
if (initializerClassName != null)
{
try
{
// get Class object
Class<?> clazz = ClassUtils.classForName(initializerClassName);
if (!FacesInitializer.class.isAssignableFrom(clazz))
{
throw new FacesException("Class " + clazz
+ " does not implement FacesInitializer");
}
// create instance and return it
return (FacesInitializer) ClassUtils.newInstance(clazz);
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException("Could not find class of specified FacesInitializer", cnfe);
}
}
return null;
} | java | private static FacesInitializer _getFacesInitializerFromInitParam(ServletContext context)
{
String initializerClassName = context.getInitParameter(FACES_INITIALIZER_PARAM);
if (initializerClassName != null)
{
try
{
// get Class object
Class<?> clazz = ClassUtils.classForName(initializerClassName);
if (!FacesInitializer.class.isAssignableFrom(clazz))
{
throw new FacesException("Class " + clazz
+ " does not implement FacesInitializer");
}
// create instance and return it
return (FacesInitializer) ClassUtils.newInstance(clazz);
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException("Could not find class of specified FacesInitializer", cnfe);
}
}
return null;
} | [
"private",
"static",
"FacesInitializer",
"_getFacesInitializerFromInitParam",
"(",
"ServletContext",
"context",
")",
"{",
"String",
"initializerClassName",
"=",
"context",
".",
"getInitParameter",
"(",
"FACES_INITIALIZER_PARAM",
")",
";",
"if",
"(",
"initializerClassName",
"!=",
"null",
")",
"{",
"try",
"{",
"// get Class object",
"Class",
"<",
"?",
">",
"clazz",
"=",
"ClassUtils",
".",
"classForName",
"(",
"initializerClassName",
")",
";",
"if",
"(",
"!",
"FacesInitializer",
".",
"class",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"throw",
"new",
"FacesException",
"(",
"\"Class \"",
"+",
"clazz",
"+",
"\" does not implement FacesInitializer\"",
")",
";",
"}",
"// create instance and return it",
"return",
"(",
"FacesInitializer",
")",
"ClassUtils",
".",
"newInstance",
"(",
"clazz",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"cnfe",
")",
"{",
"throw",
"new",
"FacesException",
"(",
"\"Could not find class of specified FacesInitializer\"",
",",
"cnfe",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Gets a FacesInitializer from the web.xml config param.
@param context
@return | [
"Gets",
"a",
"FacesInitializer",
"from",
"the",
"web",
".",
"xml",
"config",
"param",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/webapp/FacesInitializerFactory.java#L70-L94 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/forms/Utilities.java | Utilities.formsRootFromSectionsMap | public static JSONArray formsRootFromSectionsMap( HashMap<String, JSONObject> sectionsMap ) {
"""
Create the forms root json object from the map of sections json objects.
@param sectionsMap the json sections map.
@return the root object that can be dumped to file through the toString method.
"""
JSONArray rootArray = new JSONArray();
Collection<JSONObject> objects = sectionsMap.values();
for( JSONObject jsonObject : objects ) {
rootArray.put(jsonObject);
}
return rootArray;
} | java | public static JSONArray formsRootFromSectionsMap( HashMap<String, JSONObject> sectionsMap ) {
JSONArray rootArray = new JSONArray();
Collection<JSONObject> objects = sectionsMap.values();
for( JSONObject jsonObject : objects ) {
rootArray.put(jsonObject);
}
return rootArray;
} | [
"public",
"static",
"JSONArray",
"formsRootFromSectionsMap",
"(",
"HashMap",
"<",
"String",
",",
"JSONObject",
">",
"sectionsMap",
")",
"{",
"JSONArray",
"rootArray",
"=",
"new",
"JSONArray",
"(",
")",
";",
"Collection",
"<",
"JSONObject",
">",
"objects",
"=",
"sectionsMap",
".",
"values",
"(",
")",
";",
"for",
"(",
"JSONObject",
"jsonObject",
":",
"objects",
")",
"{",
"rootArray",
".",
"put",
"(",
"jsonObject",
")",
";",
"}",
"return",
"rootArray",
";",
"}"
] | Create the forms root json object from the map of sections json objects.
@param sectionsMap the json sections map.
@return the root object that can be dumped to file through the toString method. | [
"Create",
"the",
"forms",
"root",
"json",
"object",
"from",
"the",
"map",
"of",
"sections",
"json",
"objects",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/forms/Utilities.java#L333-L340 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java | ConstantOverflow.longFix | private Fix longFix(ExpressionTree expr, VisitorState state) {
"""
If the left operand of an int binary expression is an int literal, suggest making it a long.
"""
BinaryTree binExpr = null;
while (expr instanceof BinaryTree) {
binExpr = (BinaryTree) expr;
expr = binExpr.getLeftOperand();
}
if (!(expr instanceof LiteralTree) || expr.getKind() != Kind.INT_LITERAL) {
return null;
}
Type intType = state.getSymtab().intType;
if (!isSameType(getType(binExpr), intType, state)) {
return null;
}
SuggestedFix.Builder fix = SuggestedFix.builder().postfixWith(expr, "L");
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof VariableTree && isSameType(getType(parent), intType, state)) {
fix.replace(((VariableTree) parent).getType(), "long");
}
return fix.build();
} | java | private Fix longFix(ExpressionTree expr, VisitorState state) {
BinaryTree binExpr = null;
while (expr instanceof BinaryTree) {
binExpr = (BinaryTree) expr;
expr = binExpr.getLeftOperand();
}
if (!(expr instanceof LiteralTree) || expr.getKind() != Kind.INT_LITERAL) {
return null;
}
Type intType = state.getSymtab().intType;
if (!isSameType(getType(binExpr), intType, state)) {
return null;
}
SuggestedFix.Builder fix = SuggestedFix.builder().postfixWith(expr, "L");
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent instanceof VariableTree && isSameType(getType(parent), intType, state)) {
fix.replace(((VariableTree) parent).getType(), "long");
}
return fix.build();
} | [
"private",
"Fix",
"longFix",
"(",
"ExpressionTree",
"expr",
",",
"VisitorState",
"state",
")",
"{",
"BinaryTree",
"binExpr",
"=",
"null",
";",
"while",
"(",
"expr",
"instanceof",
"BinaryTree",
")",
"{",
"binExpr",
"=",
"(",
"BinaryTree",
")",
"expr",
";",
"expr",
"=",
"binExpr",
".",
"getLeftOperand",
"(",
")",
";",
"}",
"if",
"(",
"!",
"(",
"expr",
"instanceof",
"LiteralTree",
")",
"||",
"expr",
".",
"getKind",
"(",
")",
"!=",
"Kind",
".",
"INT_LITERAL",
")",
"{",
"return",
"null",
";",
"}",
"Type",
"intType",
"=",
"state",
".",
"getSymtab",
"(",
")",
".",
"intType",
";",
"if",
"(",
"!",
"isSameType",
"(",
"getType",
"(",
"binExpr",
")",
",",
"intType",
",",
"state",
")",
")",
"{",
"return",
"null",
";",
"}",
"SuggestedFix",
".",
"Builder",
"fix",
"=",
"SuggestedFix",
".",
"builder",
"(",
")",
".",
"postfixWith",
"(",
"expr",
",",
"\"L\"",
")",
";",
"Tree",
"parent",
"=",
"state",
".",
"getPath",
"(",
")",
".",
"getParentPath",
"(",
")",
".",
"getLeaf",
"(",
")",
";",
"if",
"(",
"parent",
"instanceof",
"VariableTree",
"&&",
"isSameType",
"(",
"getType",
"(",
"parent",
")",
",",
"intType",
",",
"state",
")",
")",
"{",
"fix",
".",
"replace",
"(",
"(",
"(",
"VariableTree",
")",
"parent",
")",
".",
"getType",
"(",
")",
",",
"\"long\"",
")",
";",
"}",
"return",
"fix",
".",
"build",
"(",
")",
";",
"}"
] | If the left operand of an int binary expression is an int literal, suggest making it a long. | [
"If",
"the",
"left",
"operand",
"of",
"an",
"int",
"binary",
"expression",
"is",
"an",
"int",
"literal",
"suggest",
"making",
"it",
"a",
"long",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ConstantOverflow.java#L86-L105 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java | Dater.setClock | public Dater setClock(int hour, int minute, int second) {
"""
Sets the hour, minute, second to the delegate date
@param hour
@param minute
@param second
@return
"""
return set().hours(hour).minutes(minute).second(second);
} | java | public Dater setClock(int hour, int minute, int second) {
return set().hours(hour).minutes(minute).second(second);
} | [
"public",
"Dater",
"setClock",
"(",
"int",
"hour",
",",
"int",
"minute",
",",
"int",
"second",
")",
"{",
"return",
"set",
"(",
")",
".",
"hours",
"(",
"hour",
")",
".",
"minutes",
"(",
"minute",
")",
".",
"second",
"(",
"second",
")",
";",
"}"
] | Sets the hour, minute, second to the delegate date
@param hour
@param minute
@param second
@return | [
"Sets",
"the",
"hour",
"minute",
"second",
"to",
"the",
"delegate",
"date"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java#L524-L526 |
google/closure-compiler | src/com/google/javascript/jscomp/AstFactory.java | AstFactory.getVarNameType | private JSType getVarNameType(Scope scope, String name) {
"""
Look up the correct type for the given name in the given scope.
<p>Returns the unknown type if no type can be found
"""
Var var = scope.getVar(name);
JSType type = null;
if (var != null) {
Node nameDefinitionNode = var.getNode();
if (nameDefinitionNode != null) {
type = nameDefinitionNode.getJSType();
}
}
if (type == null) {
// TODO(bradfordcsmith): Consider throwing an error if the type cannot be found.
type = unknownType;
}
return type;
} | java | private JSType getVarNameType(Scope scope, String name) {
Var var = scope.getVar(name);
JSType type = null;
if (var != null) {
Node nameDefinitionNode = var.getNode();
if (nameDefinitionNode != null) {
type = nameDefinitionNode.getJSType();
}
}
if (type == null) {
// TODO(bradfordcsmith): Consider throwing an error if the type cannot be found.
type = unknownType;
}
return type;
} | [
"private",
"JSType",
"getVarNameType",
"(",
"Scope",
"scope",
",",
"String",
"name",
")",
"{",
"Var",
"var",
"=",
"scope",
".",
"getVar",
"(",
"name",
")",
";",
"JSType",
"type",
"=",
"null",
";",
"if",
"(",
"var",
"!=",
"null",
")",
"{",
"Node",
"nameDefinitionNode",
"=",
"var",
".",
"getNode",
"(",
")",
";",
"if",
"(",
"nameDefinitionNode",
"!=",
"null",
")",
"{",
"type",
"=",
"nameDefinitionNode",
".",
"getJSType",
"(",
")",
";",
"}",
"}",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"// TODO(bradfordcsmith): Consider throwing an error if the type cannot be found.",
"type",
"=",
"unknownType",
";",
"}",
"return",
"type",
";",
"}"
] | Look up the correct type for the given name in the given scope.
<p>Returns the unknown type if no type can be found | [
"Look",
"up",
"the",
"correct",
"type",
"for",
"the",
"given",
"name",
"in",
"the",
"given",
"scope",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L978-L992 |
atteo/classindex | classindex/src/main/java/org/atteo/classindex/processor/ClassIndexProcessor.java | ClassIndexProcessor.indexSupertypes | private void indexSupertypes(TypeElement rootElement, TypeElement element) throws IOException {
"""
Index super types for {@link IndexSubclasses} and any {@link IndexAnnotated}
additionally accompanied by {@link Inherited}.
"""
for (TypeMirror mirror : types.directSupertypes(element.asType())) {
if (mirror.getKind() != TypeKind.DECLARED) {
continue;
}
DeclaredType superType = (DeclaredType) mirror;
TypeElement superTypeElement = (TypeElement) superType.asElement();
storeSubclass(superTypeElement, rootElement);
for (AnnotationMirror annotationMirror : superTypeElement.getAnnotationMirrors()) {
TypeElement annotationElement = (TypeElement) annotationMirror.getAnnotationType()
.asElement();
if (hasAnnotation(annotationElement, Inherited.class)) {
storeAnnotation(annotationElement, rootElement);
}
}
indexSupertypes(rootElement, superTypeElement);
}
} | java | private void indexSupertypes(TypeElement rootElement, TypeElement element) throws IOException {
for (TypeMirror mirror : types.directSupertypes(element.asType())) {
if (mirror.getKind() != TypeKind.DECLARED) {
continue;
}
DeclaredType superType = (DeclaredType) mirror;
TypeElement superTypeElement = (TypeElement) superType.asElement();
storeSubclass(superTypeElement, rootElement);
for (AnnotationMirror annotationMirror : superTypeElement.getAnnotationMirrors()) {
TypeElement annotationElement = (TypeElement) annotationMirror.getAnnotationType()
.asElement();
if (hasAnnotation(annotationElement, Inherited.class)) {
storeAnnotation(annotationElement, rootElement);
}
}
indexSupertypes(rootElement, superTypeElement);
}
} | [
"private",
"void",
"indexSupertypes",
"(",
"TypeElement",
"rootElement",
",",
"TypeElement",
"element",
")",
"throws",
"IOException",
"{",
"for",
"(",
"TypeMirror",
"mirror",
":",
"types",
".",
"directSupertypes",
"(",
"element",
".",
"asType",
"(",
")",
")",
")",
"{",
"if",
"(",
"mirror",
".",
"getKind",
"(",
")",
"!=",
"TypeKind",
".",
"DECLARED",
")",
"{",
"continue",
";",
"}",
"DeclaredType",
"superType",
"=",
"(",
"DeclaredType",
")",
"mirror",
";",
"TypeElement",
"superTypeElement",
"=",
"(",
"TypeElement",
")",
"superType",
".",
"asElement",
"(",
")",
";",
"storeSubclass",
"(",
"superTypeElement",
",",
"rootElement",
")",
";",
"for",
"(",
"AnnotationMirror",
"annotationMirror",
":",
"superTypeElement",
".",
"getAnnotationMirrors",
"(",
")",
")",
"{",
"TypeElement",
"annotationElement",
"=",
"(",
"TypeElement",
")",
"annotationMirror",
".",
"getAnnotationType",
"(",
")",
".",
"asElement",
"(",
")",
";",
"if",
"(",
"hasAnnotation",
"(",
"annotationElement",
",",
"Inherited",
".",
"class",
")",
")",
"{",
"storeAnnotation",
"(",
"annotationElement",
",",
"rootElement",
")",
";",
"}",
"}",
"indexSupertypes",
"(",
"rootElement",
",",
"superTypeElement",
")",
";",
"}",
"}"
] | Index super types for {@link IndexSubclasses} and any {@link IndexAnnotated}
additionally accompanied by {@link Inherited}. | [
"Index",
"super",
"types",
"for",
"{"
] | train | https://github.com/atteo/classindex/blob/ad76c6bd8b4e84c594d94e48f466a095ffe2306a/classindex/src/main/java/org/atteo/classindex/processor/ClassIndexProcessor.java#L309-L331 |
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseCsrilu0Ex | public static int cusparseCsrilu0Ex(
cusparseHandle handle,
int trans,
int m,
cusparseMatDescr descrA,
Pointer csrSortedValA_ValM,
int csrSortedValA_ValMtype,
/** matrix A values are updated inplace
to be the preconditioner M values */
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
cusparseSolveAnalysisInfo info,
int executiontype) {
"""
<pre>
Description: Compute the incomplete-LU factorization with 0 fill-in (ILU0)
of the matrix A stored in CSR format based on the information in the opaque
structure info that was obtained from the analysis phase (csrsv_analysis).
This routine implements algorithm 1 for this problem.
</pre>
"""
return checkResult(cusparseCsrilu0ExNative(handle, trans, m, descrA, csrSortedValA_ValM, csrSortedValA_ValMtype, csrSortedRowPtrA, csrSortedColIndA, info, executiontype));
} | java | public static int cusparseCsrilu0Ex(
cusparseHandle handle,
int trans,
int m,
cusparseMatDescr descrA,
Pointer csrSortedValA_ValM,
int csrSortedValA_ValMtype,
/** matrix A values are updated inplace
to be the preconditioner M values */
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
cusparseSolveAnalysisInfo info,
int executiontype)
{
return checkResult(cusparseCsrilu0ExNative(handle, trans, m, descrA, csrSortedValA_ValM, csrSortedValA_ValMtype, csrSortedRowPtrA, csrSortedColIndA, info, executiontype));
} | [
"public",
"static",
"int",
"cusparseCsrilu0Ex",
"(",
"cusparseHandle",
"handle",
",",
"int",
"trans",
",",
"int",
"m",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"csrSortedValA_ValM",
",",
"int",
"csrSortedValA_ValMtype",
",",
"/** matrix A values are updated inplace \r\n to be the preconditioner M values */",
"Pointer",
"csrSortedRowPtrA",
",",
"Pointer",
"csrSortedColIndA",
",",
"cusparseSolveAnalysisInfo",
"info",
",",
"int",
"executiontype",
")",
"{",
"return",
"checkResult",
"(",
"cusparseCsrilu0ExNative",
"(",
"handle",
",",
"trans",
",",
"m",
",",
"descrA",
",",
"csrSortedValA_ValM",
",",
"csrSortedValA_ValMtype",
",",
"csrSortedRowPtrA",
",",
"csrSortedColIndA",
",",
"info",
",",
"executiontype",
")",
")",
";",
"}"
] | <pre>
Description: Compute the incomplete-LU factorization with 0 fill-in (ILU0)
of the matrix A stored in CSR format based on the information in the opaque
structure info that was obtained from the analysis phase (csrsv_analysis).
This routine implements algorithm 1 for this problem.
</pre> | [
"<pre",
">",
"Description",
":",
"Compute",
"the",
"incomplete",
"-",
"LU",
"factorization",
"with",
"0",
"fill",
"-",
"in",
"(",
"ILU0",
")",
"of",
"the",
"matrix",
"A",
"stored",
"in",
"CSR",
"format",
"based",
"on",
"the",
"information",
"in",
"the",
"opaque",
"structure",
"info",
"that",
"was",
"obtained",
"from",
"the",
"analysis",
"phase",
"(",
"csrsv_analysis",
")",
".",
"This",
"routine",
"implements",
"algorithm",
"1",
"for",
"this",
"problem",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L5709-L5724 |
Ekryd/sortpom | sorter/src/main/java/sortpom/XmlOutputGenerator.java | XmlOutputGenerator.getSortedXml | public String getSortedXml(Document newDocument) {
"""
Returns the sorted xml as an OutputStream.
@return the sorted xml
"""
try (ByteArrayOutputStream sortedXml = new ByteArrayOutputStream()) {
BufferedLineSeparatorOutputStream bufferedLineOutputStream =
new BufferedLineSeparatorOutputStream(lineSeparatorUtil.toString(), sortedXml);
XMLOutputter xmlOutputter = new PatchedXMLOutputter(bufferedLineOutputStream, indentBlankLines);
xmlOutputter.setFormat(createPrettyFormat());
xmlOutputter.output(newDocument, bufferedLineOutputStream);
bufferedLineOutputStream.close();
return sortedXml.toString(encoding);
} catch (IOException ioex) {
throw new FailureException("Could not format pom files content", ioex);
}
} | java | public String getSortedXml(Document newDocument) {
try (ByteArrayOutputStream sortedXml = new ByteArrayOutputStream()) {
BufferedLineSeparatorOutputStream bufferedLineOutputStream =
new BufferedLineSeparatorOutputStream(lineSeparatorUtil.toString(), sortedXml);
XMLOutputter xmlOutputter = new PatchedXMLOutputter(bufferedLineOutputStream, indentBlankLines);
xmlOutputter.setFormat(createPrettyFormat());
xmlOutputter.output(newDocument, bufferedLineOutputStream);
bufferedLineOutputStream.close();
return sortedXml.toString(encoding);
} catch (IOException ioex) {
throw new FailureException("Could not format pom files content", ioex);
}
} | [
"public",
"String",
"getSortedXml",
"(",
"Document",
"newDocument",
")",
"{",
"try",
"(",
"ByteArrayOutputStream",
"sortedXml",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
")",
"{",
"BufferedLineSeparatorOutputStream",
"bufferedLineOutputStream",
"=",
"new",
"BufferedLineSeparatorOutputStream",
"(",
"lineSeparatorUtil",
".",
"toString",
"(",
")",
",",
"sortedXml",
")",
";",
"XMLOutputter",
"xmlOutputter",
"=",
"new",
"PatchedXMLOutputter",
"(",
"bufferedLineOutputStream",
",",
"indentBlankLines",
")",
";",
"xmlOutputter",
".",
"setFormat",
"(",
"createPrettyFormat",
"(",
")",
")",
";",
"xmlOutputter",
".",
"output",
"(",
"newDocument",
",",
"bufferedLineOutputStream",
")",
";",
"bufferedLineOutputStream",
".",
"close",
"(",
")",
";",
"return",
"sortedXml",
".",
"toString",
"(",
"encoding",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioex",
")",
"{",
"throw",
"new",
"FailureException",
"(",
"\"Could not format pom files content\"",
",",
"ioex",
")",
";",
"}",
"}"
] | Returns the sorted xml as an OutputStream.
@return the sorted xml | [
"Returns",
"the",
"sorted",
"xml",
"as",
"an",
"OutputStream",
"."
] | train | https://github.com/Ekryd/sortpom/blob/27056420803ed04001e4149b04a719fbac774c5d/sorter/src/main/java/sortpom/XmlOutputGenerator.java#L41-L55 |
liyiorg/weixin-popular | src/main/java/com/qq/weixin/mp/aes/XMLParse.java | XMLParse.generate | public static String generate(String encrypt, String signature, String timestamp, String nonce) {
"""
生成xml消息
@param encrypt 加密后的消息密文
@param signature 安全签名
@param timestamp 时间戳
@param nonce 随机字符串
@return 生成的xml字符串
"""
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
} | java | public static String generate(String encrypt, String signature, String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
} | [
"public",
"static",
"String",
"generate",
"(",
"String",
"encrypt",
",",
"String",
"signature",
",",
"String",
"timestamp",
",",
"String",
"nonce",
")",
"{",
"String",
"format",
"=",
"\"<xml>\\n\"",
"+",
"\"<Encrypt><![CDATA[%1$s]]></Encrypt>\\n\"",
"+",
"\"<MsgSignature><![CDATA[%2$s]]></MsgSignature>\\n\"",
"+",
"\"<TimeStamp>%3$s</TimeStamp>\\n\"",
"+",
"\"<Nonce><![CDATA[%4$s]]></Nonce>\\n\"",
"+",
"\"</xml>\"",
";",
"return",
"String",
".",
"format",
"(",
"format",
",",
"encrypt",
",",
"signature",
",",
"timestamp",
",",
"nonce",
")",
";",
"}"
] | 生成xml消息
@param encrypt 加密后的消息密文
@param signature 安全签名
@param timestamp 时间戳
@param nonce 随机字符串
@return 生成的xml字符串 | [
"生成xml消息"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/com/qq/weixin/mp/aes/XMLParse.java#L82-L89 |
google/closure-compiler | src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java | DestructuringGlobalNameExtractor.addAfter | private static void addAfter(Node originalLvalue, Node newLvalue, Node newRvalue) {
"""
Adds the new assign or name declaration after the original assign or name declaration
"""
Node parent = originalLvalue.getParent();
if (parent.isAssign()) {
// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
Node newComma = new Node(Token.COMMA, newAssign);
parent.replaceWith(newComma);
newComma.addChildToFront(parent);
return;
}
// This must have been in a var/let/const.
if (newLvalue.isDestructuringPattern()) {
newLvalue = new Node(Token.DESTRUCTURING_LHS, newLvalue, newRvalue).srcref(parent);
} else {
newLvalue.addChildToBack(newRvalue);
}
Node declaration = parent.isDestructuringLhs() ? originalLvalue.getGrandparent() : parent;
checkState(NodeUtil.isNameDeclaration(declaration), declaration);
if (NodeUtil.isStatementParent(declaration.getParent())) {
// `const {} = originalRvalue; const newLvalue = newRvalue;`
// create an entirely new statement
Node newDeclaration = new Node(declaration.getToken()).srcref(declaration);
newDeclaration.addChildToBack(newLvalue);
declaration.getParent().addChildAfter(newDeclaration, declaration);
} else {
// `const {} = originalRvalue, newLvalue = newRvalue;`
// The Normalize pass tries to ensure name declarations are always in statement blocks, but
// currently has not implemented normalization for `for (let x = 0; ...`
// so we can't add a new statement
declaration.addChildToBack(newLvalue);
}
} | java | private static void addAfter(Node originalLvalue, Node newLvalue, Node newRvalue) {
Node parent = originalLvalue.getParent();
if (parent.isAssign()) {
// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`
Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent);
Node newComma = new Node(Token.COMMA, newAssign);
parent.replaceWith(newComma);
newComma.addChildToFront(parent);
return;
}
// This must have been in a var/let/const.
if (newLvalue.isDestructuringPattern()) {
newLvalue = new Node(Token.DESTRUCTURING_LHS, newLvalue, newRvalue).srcref(parent);
} else {
newLvalue.addChildToBack(newRvalue);
}
Node declaration = parent.isDestructuringLhs() ? originalLvalue.getGrandparent() : parent;
checkState(NodeUtil.isNameDeclaration(declaration), declaration);
if (NodeUtil.isStatementParent(declaration.getParent())) {
// `const {} = originalRvalue; const newLvalue = newRvalue;`
// create an entirely new statement
Node newDeclaration = new Node(declaration.getToken()).srcref(declaration);
newDeclaration.addChildToBack(newLvalue);
declaration.getParent().addChildAfter(newDeclaration, declaration);
} else {
// `const {} = originalRvalue, newLvalue = newRvalue;`
// The Normalize pass tries to ensure name declarations are always in statement blocks, but
// currently has not implemented normalization for `for (let x = 0; ...`
// so we can't add a new statement
declaration.addChildToBack(newLvalue);
}
} | [
"private",
"static",
"void",
"addAfter",
"(",
"Node",
"originalLvalue",
",",
"Node",
"newLvalue",
",",
"Node",
"newRvalue",
")",
"{",
"Node",
"parent",
"=",
"originalLvalue",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
"isAssign",
"(",
")",
")",
"{",
"// create `(<originalLvalue = ...>, <newLvalue = newRvalue>)`",
"Node",
"newAssign",
"=",
"IR",
".",
"assign",
"(",
"newLvalue",
",",
"newRvalue",
")",
".",
"srcref",
"(",
"parent",
")",
";",
"Node",
"newComma",
"=",
"new",
"Node",
"(",
"Token",
".",
"COMMA",
",",
"newAssign",
")",
";",
"parent",
".",
"replaceWith",
"(",
"newComma",
")",
";",
"newComma",
".",
"addChildToFront",
"(",
"parent",
")",
";",
"return",
";",
"}",
"// This must have been in a var/let/const.",
"if",
"(",
"newLvalue",
".",
"isDestructuringPattern",
"(",
")",
")",
"{",
"newLvalue",
"=",
"new",
"Node",
"(",
"Token",
".",
"DESTRUCTURING_LHS",
",",
"newLvalue",
",",
"newRvalue",
")",
".",
"srcref",
"(",
"parent",
")",
";",
"}",
"else",
"{",
"newLvalue",
".",
"addChildToBack",
"(",
"newRvalue",
")",
";",
"}",
"Node",
"declaration",
"=",
"parent",
".",
"isDestructuringLhs",
"(",
")",
"?",
"originalLvalue",
".",
"getGrandparent",
"(",
")",
":",
"parent",
";",
"checkState",
"(",
"NodeUtil",
".",
"isNameDeclaration",
"(",
"declaration",
")",
",",
"declaration",
")",
";",
"if",
"(",
"NodeUtil",
".",
"isStatementParent",
"(",
"declaration",
".",
"getParent",
"(",
")",
")",
")",
"{",
"// `const {} = originalRvalue; const newLvalue = newRvalue;`",
"// create an entirely new statement",
"Node",
"newDeclaration",
"=",
"new",
"Node",
"(",
"declaration",
".",
"getToken",
"(",
")",
")",
".",
"srcref",
"(",
"declaration",
")",
";",
"newDeclaration",
".",
"addChildToBack",
"(",
"newLvalue",
")",
";",
"declaration",
".",
"getParent",
"(",
")",
".",
"addChildAfter",
"(",
"newDeclaration",
",",
"declaration",
")",
";",
"}",
"else",
"{",
"// `const {} = originalRvalue, newLvalue = newRvalue;`",
"// The Normalize pass tries to ensure name declarations are always in statement blocks, but",
"// currently has not implemented normalization for `for (let x = 0; ...`",
"// so we can't add a new statement",
"declaration",
".",
"addChildToBack",
"(",
"newLvalue",
")",
";",
"}",
"}"
] | Adds the new assign or name declaration after the original assign or name declaration | [
"Adds",
"the",
"new",
"assign",
"or",
"name",
"declaration",
"after",
"the",
"original",
"assign",
"or",
"name",
"declaration"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L115-L146 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/StorageUtil.java | StorageUtil.toTime | public Time toTime(Config config, Element el, String attributeName) {
"""
reads a XML Element Attribute ans cast it to a Time Object
@param config
@param el XML Element to read Attribute from it
@param attributeName Name of the Attribute to read
@return Attribute Value
"""
DateTime dt = toDateTime(config, el, attributeName);
if (dt == null) return null;
return new TimeImpl(dt);
} | java | public Time toTime(Config config, Element el, String attributeName) {
DateTime dt = toDateTime(config, el, attributeName);
if (dt == null) return null;
return new TimeImpl(dt);
} | [
"public",
"Time",
"toTime",
"(",
"Config",
"config",
",",
"Element",
"el",
",",
"String",
"attributeName",
")",
"{",
"DateTime",
"dt",
"=",
"toDateTime",
"(",
"config",
",",
"el",
",",
"attributeName",
")",
";",
"if",
"(",
"dt",
"==",
"null",
")",
"return",
"null",
";",
"return",
"new",
"TimeImpl",
"(",
"dt",
")",
";",
"}"
] | reads a XML Element Attribute ans cast it to a Time Object
@param config
@param el XML Element to read Attribute from it
@param attributeName Name of the Attribute to read
@return Attribute Value | [
"reads",
"a",
"XML",
"Element",
"Attribute",
"ans",
"cast",
"it",
"to",
"a",
"Time",
"Object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L299-L303 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/searchindex/CmsSearchIndexSourceList.java | CmsSearchIndexSourceList.fillDetailDocTypes | private void fillDetailDocTypes(CmsListItem item, String detailId) {
"""
Fills details about document types of the index source into the given item. <p>
@param item the list item to fill
@param detailId the id for the detail to fill
"""
CmsSearchManager searchManager = OpenCms.getSearchManager();
StringBuffer html = new StringBuffer();
// search for the corresponding CmsSearchIndexSource:
String idxSourceName = (String)item.get(LIST_COLUMN_NAME);
CmsSearchIndexSource idxSource = searchManager.getIndexSource(idxSourceName);
// get the index sources doc types
List<String> docTypes = idxSource.getDocumentTypes();
// output of found index sources
Iterator<String> itDocTypes = docTypes.iterator();
CmsSearchDocumentType docType;
html.append("<ul>\n");
while (itDocTypes.hasNext()) {
// get the instance (instead of plain name) for more detail in future...
docType = searchManager.getDocumentTypeConfig(itDocTypes.next());
// harden against unconfigured doctypes that are refferred to by indexsource nodes
if (docType != null) {
html.append(" <li>\n").append(" ").append(docType.getName()).append("\n");
html.append(" </li>");
}
}
html.append("</ul>\n");
item.set(detailId, html.toString());
} | java | private void fillDetailDocTypes(CmsListItem item, String detailId) {
CmsSearchManager searchManager = OpenCms.getSearchManager();
StringBuffer html = new StringBuffer();
// search for the corresponding CmsSearchIndexSource:
String idxSourceName = (String)item.get(LIST_COLUMN_NAME);
CmsSearchIndexSource idxSource = searchManager.getIndexSource(idxSourceName);
// get the index sources doc types
List<String> docTypes = idxSource.getDocumentTypes();
// output of found index sources
Iterator<String> itDocTypes = docTypes.iterator();
CmsSearchDocumentType docType;
html.append("<ul>\n");
while (itDocTypes.hasNext()) {
// get the instance (instead of plain name) for more detail in future...
docType = searchManager.getDocumentTypeConfig(itDocTypes.next());
// harden against unconfigured doctypes that are refferred to by indexsource nodes
if (docType != null) {
html.append(" <li>\n").append(" ").append(docType.getName()).append("\n");
html.append(" </li>");
}
}
html.append("</ul>\n");
item.set(detailId, html.toString());
} | [
"private",
"void",
"fillDetailDocTypes",
"(",
"CmsListItem",
"item",
",",
"String",
"detailId",
")",
"{",
"CmsSearchManager",
"searchManager",
"=",
"OpenCms",
".",
"getSearchManager",
"(",
")",
";",
"StringBuffer",
"html",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"// search for the corresponding CmsSearchIndexSource:",
"String",
"idxSourceName",
"=",
"(",
"String",
")",
"item",
".",
"get",
"(",
"LIST_COLUMN_NAME",
")",
";",
"CmsSearchIndexSource",
"idxSource",
"=",
"searchManager",
".",
"getIndexSource",
"(",
"idxSourceName",
")",
";",
"// get the index sources doc types",
"List",
"<",
"String",
">",
"docTypes",
"=",
"idxSource",
".",
"getDocumentTypes",
"(",
")",
";",
"// output of found index sources",
"Iterator",
"<",
"String",
">",
"itDocTypes",
"=",
"docTypes",
".",
"iterator",
"(",
")",
";",
"CmsSearchDocumentType",
"docType",
";",
"html",
".",
"append",
"(",
"\"<ul>\\n\"",
")",
";",
"while",
"(",
"itDocTypes",
".",
"hasNext",
"(",
")",
")",
"{",
"// get the instance (instead of plain name) for more detail in future...",
"docType",
"=",
"searchManager",
".",
"getDocumentTypeConfig",
"(",
"itDocTypes",
".",
"next",
"(",
")",
")",
";",
"// harden against unconfigured doctypes that are refferred to by indexsource nodes",
"if",
"(",
"docType",
"!=",
"null",
")",
"{",
"html",
".",
"append",
"(",
"\" <li>\\n\"",
")",
".",
"append",
"(",
"\" \"",
")",
".",
"append",
"(",
"docType",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"html",
".",
"append",
"(",
"\" </li>\"",
")",
";",
"}",
"}",
"html",
".",
"append",
"(",
"\"</ul>\\n\"",
")",
";",
"item",
".",
"set",
"(",
"detailId",
",",
"html",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Fills details about document types of the index source into the given item. <p>
@param item the list item to fill
@param detailId the id for the detail to fill | [
"Fills",
"details",
"about",
"document",
"types",
"of",
"the",
"index",
"source",
"into",
"the",
"given",
"item",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/searchindex/CmsSearchIndexSourceList.java#L402-L430 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java | ZipUtil.zip | private static void zip(File file, String srcRootDir, ZipOutputStream out) throws UtilException {
"""
递归压缩文件夹<br>
srcRootDir决定了路径截取的位置,例如:<br>
file的路径为d:/a/b/c/d.txt,srcRootDir为d:/a/b,则压缩后的文件与目录为结构为c/d.txt
@param out 压缩文件存储对象
@param srcRootDir 被压缩的文件夹根目录
@param file 当前递归压缩的文件或目录对象
@throws UtilException IO异常
"""
if (file == null) {
return;
}
final String subPath = FileUtil.subPath(srcRootDir, file); // 获取文件相对于压缩文件夹根目录的子路径
if (file.isDirectory()) {// 如果是目录,则压缩压缩目录中的文件或子目录
final File[] files = file.listFiles();
if (ArrayUtil.isEmpty(files) && StrUtil.isNotEmpty(subPath)) {
// 加入目录,只有空目录时才加入目录,非空时会在创建文件时自动添加父级目录
addDir(subPath, out);
}
// 压缩目录下的子文件或目录
for (File childFile : files) {
zip(childFile, srcRootDir, out);
}
} else {// 如果是文件或其它符号,则直接压缩该文件
addFile(file, subPath, out);
}
} | java | private static void zip(File file, String srcRootDir, ZipOutputStream out) throws UtilException {
if (file == null) {
return;
}
final String subPath = FileUtil.subPath(srcRootDir, file); // 获取文件相对于压缩文件夹根目录的子路径
if (file.isDirectory()) {// 如果是目录,则压缩压缩目录中的文件或子目录
final File[] files = file.listFiles();
if (ArrayUtil.isEmpty(files) && StrUtil.isNotEmpty(subPath)) {
// 加入目录,只有空目录时才加入目录,非空时会在创建文件时自动添加父级目录
addDir(subPath, out);
}
// 压缩目录下的子文件或目录
for (File childFile : files) {
zip(childFile, srcRootDir, out);
}
} else {// 如果是文件或其它符号,则直接压缩该文件
addFile(file, subPath, out);
}
} | [
"private",
"static",
"void",
"zip",
"(",
"File",
"file",
",",
"String",
"srcRootDir",
",",
"ZipOutputStream",
"out",
")",
"throws",
"UtilException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"String",
"subPath",
"=",
"FileUtil",
".",
"subPath",
"(",
"srcRootDir",
",",
"file",
")",
";",
"// 获取文件相对于压缩文件夹根目录的子路径\r",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"// 如果是目录,则压缩压缩目录中的文件或子目录\r",
"final",
"File",
"[",
"]",
"files",
"=",
"file",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"ArrayUtil",
".",
"isEmpty",
"(",
"files",
")",
"&&",
"StrUtil",
".",
"isNotEmpty",
"(",
"subPath",
")",
")",
"{",
"// 加入目录,只有空目录时才加入目录,非空时会在创建文件时自动添加父级目录\r",
"addDir",
"(",
"subPath",
",",
"out",
")",
";",
"}",
"// 压缩目录下的子文件或目录\r",
"for",
"(",
"File",
"childFile",
":",
"files",
")",
"{",
"zip",
"(",
"childFile",
",",
"srcRootDir",
",",
"out",
")",
";",
"}",
"}",
"else",
"{",
"// 如果是文件或其它符号,则直接压缩该文件\r",
"addFile",
"(",
"file",
",",
"subPath",
",",
"out",
")",
";",
"}",
"}"
] | 递归压缩文件夹<br>
srcRootDir决定了路径截取的位置,例如:<br>
file的路径为d:/a/b/c/d.txt,srcRootDir为d:/a/b,则压缩后的文件与目录为结构为c/d.txt
@param out 压缩文件存储对象
@param srcRootDir 被压缩的文件夹根目录
@param file 当前递归压缩的文件或目录对象
@throws UtilException IO异常 | [
"递归压缩文件夹<br",
">",
"srcRootDir决定了路径截取的位置,例如:<br",
">",
"file的路径为d",
":",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"d",
".",
"txt,srcRootDir为d",
":",
"/",
"a",
"/",
"b,则压缩后的文件与目录为结构为c",
"/",
"d",
".",
"txt"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L772-L791 |
belaban/JGroups | src/org/jgroups/conf/ConfiguratorFactory.java | ConfiguratorFactory.getStackConfigurator | public static ProtocolStackConfigurator getStackConfigurator(String properties) throws Exception {
"""
Returns a protocol stack configurator based on the provided properties string.
@param properties a string representing a system resource containing a JGroups XML configuration, a URL pointing
to a JGroups XML configuration or a string representing a file name that contains a JGroups
XML configuration.
"""
if(properties == null)
properties=Global.DEFAULT_PROTOCOL_STACK;
// Attempt to treat the properties string as a pointer to an XML configuration.
XmlConfigurator configurator = null;
checkForNullConfiguration(properties);
configurator=getXmlConfigurator(properties);
if(configurator != null) // did the properties string point to a JGroups XML configuration ?
return configurator;
throw new IllegalStateException(String.format("configuration %s not found or invalid", properties));
} | java | public static ProtocolStackConfigurator getStackConfigurator(String properties) throws Exception {
if(properties == null)
properties=Global.DEFAULT_PROTOCOL_STACK;
// Attempt to treat the properties string as a pointer to an XML configuration.
XmlConfigurator configurator = null;
checkForNullConfiguration(properties);
configurator=getXmlConfigurator(properties);
if(configurator != null) // did the properties string point to a JGroups XML configuration ?
return configurator;
throw new IllegalStateException(String.format("configuration %s not found or invalid", properties));
} | [
"public",
"static",
"ProtocolStackConfigurator",
"getStackConfigurator",
"(",
"String",
"properties",
")",
"throws",
"Exception",
"{",
"if",
"(",
"properties",
"==",
"null",
")",
"properties",
"=",
"Global",
".",
"DEFAULT_PROTOCOL_STACK",
";",
"// Attempt to treat the properties string as a pointer to an XML configuration.",
"XmlConfigurator",
"configurator",
"=",
"null",
";",
"checkForNullConfiguration",
"(",
"properties",
")",
";",
"configurator",
"=",
"getXmlConfigurator",
"(",
"properties",
")",
";",
"if",
"(",
"configurator",
"!=",
"null",
")",
"// did the properties string point to a JGroups XML configuration ?",
"return",
"configurator",
";",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"configuration %s not found or invalid\"",
",",
"properties",
")",
")",
";",
"}"
] | Returns a protocol stack configurator based on the provided properties string.
@param properties a string representing a system resource containing a JGroups XML configuration, a URL pointing
to a JGroups XML configuration or a string representing a file name that contains a JGroups
XML configuration. | [
"Returns",
"a",
"protocol",
"stack",
"configurator",
"based",
"on",
"the",
"provided",
"properties",
"string",
"."
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/conf/ConfiguratorFactory.java#L83-L96 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteTablesInner.java | RouteTablesInner.beginDelete | public void beginDelete(String resourceGroupName, String routeTableName) {
"""
Deletes the specified route table.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@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
"""
beginDeleteWithServiceResponseAsync(resourceGroupName, routeTableName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String routeTableName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, routeTableName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeTableName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"routeTableName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Deletes the specified route table.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@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 | [
"Deletes",
"the",
"specified",
"route",
"table",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteTablesInner.java#L191-L193 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.common.jsonwebkey/src/com/ibm/ws/security/common/jwk/impl/Jose4jRsaJWK.java | Jose4jRsaJWK.getInstance | public static Jose4jRsaJWK getInstance(int size, String alg, String use, String type) {
"""
generate a new JWK with the specified parameters
@param size
@param alg
@param use
@param type
@return
"""
String kid = RandomUtils.getRandomAlphaNumeric(KID_LENGTH);
KeyPairGenerator keyGenerator = null;
try {
keyGenerator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// This should not happen, since we hardcoded as "RSA"
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught unexpected exception: " + e.getLocalizedMessage(), e);
}
return null;
}
keyGenerator.initialize(size);
KeyPair keypair = keyGenerator.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keypair.getPrivate();
Jose4jRsaJWK jwk = new Jose4jRsaJWK(pubKey);
jwk.setPrivateKey(priKey);
jwk.setAlgorithm(alg);
jwk.setKeyId(kid);
jwk.setUse((use == null) ? JwkConstants.sig : use);
return jwk;
} | java | public static Jose4jRsaJWK getInstance(int size, String alg, String use, String type) {
String kid = RandomUtils.getRandomAlphaNumeric(KID_LENGTH);
KeyPairGenerator keyGenerator = null;
try {
keyGenerator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// This should not happen, since we hardcoded as "RSA"
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught unexpected exception: " + e.getLocalizedMessage(), e);
}
return null;
}
keyGenerator.initialize(size);
KeyPair keypair = keyGenerator.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keypair.getPrivate();
Jose4jRsaJWK jwk = new Jose4jRsaJWK(pubKey);
jwk.setPrivateKey(priKey);
jwk.setAlgorithm(alg);
jwk.setKeyId(kid);
jwk.setUse((use == null) ? JwkConstants.sig : use);
return jwk;
} | [
"public",
"static",
"Jose4jRsaJWK",
"getInstance",
"(",
"int",
"size",
",",
"String",
"alg",
",",
"String",
"use",
",",
"String",
"type",
")",
"{",
"String",
"kid",
"=",
"RandomUtils",
".",
"getRandomAlphaNumeric",
"(",
"KID_LENGTH",
")",
";",
"KeyPairGenerator",
"keyGenerator",
"=",
"null",
";",
"try",
"{",
"keyGenerator",
"=",
"KeyPairGenerator",
".",
"getInstance",
"(",
"\"RSA\"",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"e",
")",
"{",
"// This should not happen, since we hardcoded as \"RSA\"",
"if",
"(",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"Caught unexpected exception: \"",
"+",
"e",
".",
"getLocalizedMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"return",
"null",
";",
"}",
"keyGenerator",
".",
"initialize",
"(",
"size",
")",
";",
"KeyPair",
"keypair",
"=",
"keyGenerator",
".",
"generateKeyPair",
"(",
")",
";",
"RSAPublicKey",
"pubKey",
"=",
"(",
"RSAPublicKey",
")",
"keypair",
".",
"getPublic",
"(",
")",
";",
"RSAPrivateKey",
"priKey",
"=",
"(",
"RSAPrivateKey",
")",
"keypair",
".",
"getPrivate",
"(",
")",
";",
"Jose4jRsaJWK",
"jwk",
"=",
"new",
"Jose4jRsaJWK",
"(",
"pubKey",
")",
";",
"jwk",
".",
"setPrivateKey",
"(",
"priKey",
")",
";",
"jwk",
".",
"setAlgorithm",
"(",
"alg",
")",
";",
"jwk",
".",
"setKeyId",
"(",
"kid",
")",
";",
"jwk",
".",
"setUse",
"(",
"(",
"use",
"==",
"null",
")",
"?",
"JwkConstants",
".",
"sig",
":",
"use",
")",
";",
"return",
"jwk",
";",
"}"
] | generate a new JWK with the specified parameters
@param size
@param alg
@param use
@param type
@return | [
"generate",
"a",
"new",
"JWK",
"with",
"the",
"specified",
"parameters"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.common.jsonwebkey/src/com/ibm/ws/security/common/jwk/impl/Jose4jRsaJWK.java#L60-L87 |
LAW-Unimi/BUbiNG | src/it/unimi/di/law/warc/records/WarcHeader.java | WarcHeader.getFirstHeader | public static Header getFirstHeader(final HeaderGroup headers, final WarcHeader.Name name) {
"""
Returns the first header of given name.
@param headers the headers to search from.
@param name the name of the header to lookup.
@return the header.
"""
return headers.getFirstHeader(name.value);
} | java | public static Header getFirstHeader(final HeaderGroup headers, final WarcHeader.Name name) {
return headers.getFirstHeader(name.value);
} | [
"public",
"static",
"Header",
"getFirstHeader",
"(",
"final",
"HeaderGroup",
"headers",
",",
"final",
"WarcHeader",
".",
"Name",
"name",
")",
"{",
"return",
"headers",
".",
"getFirstHeader",
"(",
"name",
".",
"value",
")",
";",
"}"
] | Returns the first header of given name.
@param headers the headers to search from.
@param name the name of the header to lookup.
@return the header. | [
"Returns",
"the",
"first",
"header",
"of",
"given",
"name",
"."
] | train | https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/warc/records/WarcHeader.java#L123-L125 |
Netflix/ndbench | ndbench-dyno-plugins/src/main/java/com/netflix/ndbench/plugin/dyno/DynoJedisUtils.java | DynoJedisUtils.pipelineWriteHMSET | public String pipelineWriteHMSET(String key, DataGenerator dataGenerator, String hm_key_prefix) {
"""
writes with an pipelined HMSET
@param key
@return the keys of the hash that was stored.
"""
Map<String, String> map = new HashMap<>();
String hmKey = hm_key_prefix + key;
map.put((hmKey + "__1"), (key + "__" + dataGenerator.getRandomValue() + "__" + key));
map.put((hmKey + "__2"), (key + "__" + dataGenerator.getRandomValue() + "__" + key));
DynoJedisPipeline pipeline = jedisClient.get().pipelined();
pipeline.hmset(hmKey, map);
pipeline.expire(hmKey, 3600);
pipeline.sync();
return "HMSET:" + hmKey;
} | java | public String pipelineWriteHMSET(String key, DataGenerator dataGenerator, String hm_key_prefix) {
Map<String, String> map = new HashMap<>();
String hmKey = hm_key_prefix + key;
map.put((hmKey + "__1"), (key + "__" + dataGenerator.getRandomValue() + "__" + key));
map.put((hmKey + "__2"), (key + "__" + dataGenerator.getRandomValue() + "__" + key));
DynoJedisPipeline pipeline = jedisClient.get().pipelined();
pipeline.hmset(hmKey, map);
pipeline.expire(hmKey, 3600);
pipeline.sync();
return "HMSET:" + hmKey;
} | [
"public",
"String",
"pipelineWriteHMSET",
"(",
"String",
"key",
",",
"DataGenerator",
"dataGenerator",
",",
"String",
"hm_key_prefix",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"String",
"hmKey",
"=",
"hm_key_prefix",
"+",
"key",
";",
"map",
".",
"put",
"(",
"(",
"hmKey",
"+",
"\"__1\"",
")",
",",
"(",
"key",
"+",
"\"__\"",
"+",
"dataGenerator",
".",
"getRandomValue",
"(",
")",
"+",
"\"__\"",
"+",
"key",
")",
")",
";",
"map",
".",
"put",
"(",
"(",
"hmKey",
"+",
"\"__2\"",
")",
",",
"(",
"key",
"+",
"\"__\"",
"+",
"dataGenerator",
".",
"getRandomValue",
"(",
")",
"+",
"\"__\"",
"+",
"key",
")",
")",
";",
"DynoJedisPipeline",
"pipeline",
"=",
"jedisClient",
".",
"get",
"(",
")",
".",
"pipelined",
"(",
")",
";",
"pipeline",
".",
"hmset",
"(",
"hmKey",
",",
"map",
")",
";",
"pipeline",
".",
"expire",
"(",
"hmKey",
",",
"3600",
")",
";",
"pipeline",
".",
"sync",
"(",
")",
";",
"return",
"\"HMSET:\"",
"+",
"hmKey",
";",
"}"
] | writes with an pipelined HMSET
@param key
@return the keys of the hash that was stored. | [
"writes",
"with",
"an",
"pipelined",
"HMSET"
] | train | https://github.com/Netflix/ndbench/blob/8d664244b5f9d01395248a296b86a3c822e6d764/ndbench-dyno-plugins/src/main/java/com/netflix/ndbench/plugin/dyno/DynoJedisUtils.java#L217-L229 |
graknlabs/grakn | server/src/server/exception/TransactionException.java | TransactionException.invalidAttributeValue | public static TransactionException invalidAttributeValue(Object object, AttributeType.DataType dataType) {
"""
Thrown when creating an Attribute whose value Object does not match attribute data type
"""
return create(ErrorMessage.INVALID_DATATYPE.getMessage(object, object.getClass().getSimpleName(), dataType.name()));
} | java | public static TransactionException invalidAttributeValue(Object object, AttributeType.DataType dataType) {
return create(ErrorMessage.INVALID_DATATYPE.getMessage(object, object.getClass().getSimpleName(), dataType.name()));
} | [
"public",
"static",
"TransactionException",
"invalidAttributeValue",
"(",
"Object",
"object",
",",
"AttributeType",
".",
"DataType",
"dataType",
")",
"{",
"return",
"create",
"(",
"ErrorMessage",
".",
"INVALID_DATATYPE",
".",
"getMessage",
"(",
"object",
",",
"object",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
",",
"dataType",
".",
"name",
"(",
")",
")",
")",
";",
"}"
] | Thrown when creating an Attribute whose value Object does not match attribute data type | [
"Thrown",
"when",
"creating",
"an",
"Attribute",
"whose",
"value",
"Object",
"does",
"not",
"match",
"attribute",
"data",
"type"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L150-L152 |
microfocus-idol/java-configuration-impl | src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java | ConfigurationUtils.mergeConfiguration | public static <F extends ConfigurationComponent<F>> F mergeConfiguration(final F local, final F defaults, final Supplier<F> merge) {
"""
Merges (nullable) local configuration with (nullable) default configuration for a given custom merge function
@param local local configuration object
@param defaults default configuration object
@param merge the merge function
@param <F> the configuration object type
@return the merged configuration
"""
return Optional.ofNullable(defaults).map(v -> merge.get()).orElse(local);
} | java | public static <F extends ConfigurationComponent<F>> F mergeConfiguration(final F local, final F defaults, final Supplier<F> merge) {
return Optional.ofNullable(defaults).map(v -> merge.get()).orElse(local);
} | [
"public",
"static",
"<",
"F",
"extends",
"ConfigurationComponent",
"<",
"F",
">",
">",
"F",
"mergeConfiguration",
"(",
"final",
"F",
"local",
",",
"final",
"F",
"defaults",
",",
"final",
"Supplier",
"<",
"F",
">",
"merge",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"defaults",
")",
".",
"map",
"(",
"v",
"->",
"merge",
".",
"get",
"(",
")",
")",
".",
"orElse",
"(",
"local",
")",
";",
"}"
] | Merges (nullable) local configuration with (nullable) default configuration for a given custom merge function
@param local local configuration object
@param defaults default configuration object
@param merge the merge function
@param <F> the configuration object type
@return the merged configuration | [
"Merges",
"(",
"nullable",
")",
"local",
"configuration",
"with",
"(",
"nullable",
")",
"default",
"configuration",
"for",
"a",
"given",
"custom",
"merge",
"function"
] | train | https://github.com/microfocus-idol/java-configuration-impl/blob/cd9d744cacfaaae3c76cacc211e65742bbc7b00a/src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java#L30-L32 |
wildfly/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/RemoteDomainConnectionService.java | RemoteDomainConnectionService.applyRemoteDomainModel | private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {
"""
Apply the remote domain model to the local host controller.
@param bootOperations the result of the remote read-domain-model op
@return {@code true} if the model was applied successfully, {@code false} otherwise
"""
try {
HostControllerLogger.ROOT_LOGGER.debug("Applying domain level boot operations provided by master");
SyncModelParameters parameters =
new SyncModelParameters(domainController, ignoredDomainResourceRegistry,
hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);
final SyncDomainModelOperationHandler handler =
new SyncDomainModelOperationHandler(hostInfo, parameters);
final ModelNode operation = APPLY_DOMAIN_MODEL.clone();
operation.get(DOMAIN_MODEL).set(bootOperations);
final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);
final String outcome = result.get(OUTCOME).asString();
final boolean success = SUCCESS.equals(outcome);
// check if anything we synced triggered reload-required or restart-required.
// if they did we log a warning on the synced slave.
if (result.has(RESPONSE_HEADERS)) {
final ModelNode headers = result.get(RESPONSE_HEADERS);
if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {
HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();
}
if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {
HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();
}
}
if (!success) {
ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();
HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);
return false;
} else {
return true;
}
} catch (Exception e) {
HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);
return false;
}
} | java | private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {
try {
HostControllerLogger.ROOT_LOGGER.debug("Applying domain level boot operations provided by master");
SyncModelParameters parameters =
new SyncModelParameters(domainController, ignoredDomainResourceRegistry,
hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);
final SyncDomainModelOperationHandler handler =
new SyncDomainModelOperationHandler(hostInfo, parameters);
final ModelNode operation = APPLY_DOMAIN_MODEL.clone();
operation.get(DOMAIN_MODEL).set(bootOperations);
final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);
final String outcome = result.get(OUTCOME).asString();
final boolean success = SUCCESS.equals(outcome);
// check if anything we synced triggered reload-required or restart-required.
// if they did we log a warning on the synced slave.
if (result.has(RESPONSE_HEADERS)) {
final ModelNode headers = result.get(RESPONSE_HEADERS);
if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {
HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();
}
if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {
HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();
}
}
if (!success) {
ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();
HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);
return false;
} else {
return true;
}
} catch (Exception e) {
HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);
return false;
}
} | [
"private",
"boolean",
"applyRemoteDomainModel",
"(",
"final",
"List",
"<",
"ModelNode",
">",
"bootOperations",
",",
"final",
"HostInfo",
"hostInfo",
")",
"{",
"try",
"{",
"HostControllerLogger",
".",
"ROOT_LOGGER",
".",
"debug",
"(",
"\"Applying domain level boot operations provided by master\"",
")",
";",
"SyncModelParameters",
"parameters",
"=",
"new",
"SyncModelParameters",
"(",
"domainController",
",",
"ignoredDomainResourceRegistry",
",",
"hostControllerEnvironment",
",",
"extensionRegistry",
",",
"operationExecutor",
",",
"true",
",",
"serverProxies",
",",
"remoteFileRepository",
",",
"contentRepository",
")",
";",
"final",
"SyncDomainModelOperationHandler",
"handler",
"=",
"new",
"SyncDomainModelOperationHandler",
"(",
"hostInfo",
",",
"parameters",
")",
";",
"final",
"ModelNode",
"operation",
"=",
"APPLY_DOMAIN_MODEL",
".",
"clone",
"(",
")",
";",
"operation",
".",
"get",
"(",
"DOMAIN_MODEL",
")",
".",
"set",
"(",
"bootOperations",
")",
";",
"final",
"ModelNode",
"result",
"=",
"operationExecutor",
".",
"execute",
"(",
"OperationBuilder",
".",
"create",
"(",
"operation",
")",
".",
"build",
"(",
")",
",",
"OperationMessageHandler",
".",
"DISCARD",
",",
"ModelController",
".",
"OperationTransactionControl",
".",
"COMMIT",
",",
"handler",
")",
";",
"final",
"String",
"outcome",
"=",
"result",
".",
"get",
"(",
"OUTCOME",
")",
".",
"asString",
"(",
")",
";",
"final",
"boolean",
"success",
"=",
"SUCCESS",
".",
"equals",
"(",
"outcome",
")",
";",
"// check if anything we synced triggered reload-required or restart-required.",
"// if they did we log a warning on the synced slave.",
"if",
"(",
"result",
".",
"has",
"(",
"RESPONSE_HEADERS",
")",
")",
"{",
"final",
"ModelNode",
"headers",
"=",
"result",
".",
"get",
"(",
"RESPONSE_HEADERS",
")",
";",
"if",
"(",
"headers",
".",
"hasDefined",
"(",
"OPERATION_REQUIRES_RELOAD",
")",
"&&",
"headers",
".",
"get",
"(",
"OPERATION_REQUIRES_RELOAD",
")",
".",
"asBoolean",
"(",
")",
")",
"{",
"HostControllerLogger",
".",
"ROOT_LOGGER",
".",
"domainModelAppliedButReloadIsRequired",
"(",
")",
";",
"}",
"if",
"(",
"headers",
".",
"hasDefined",
"(",
"OPERATION_REQUIRES_RESTART",
")",
"&&",
"headers",
".",
"get",
"(",
"OPERATION_REQUIRES_RESTART",
")",
".",
"asBoolean",
"(",
")",
")",
"{",
"HostControllerLogger",
".",
"ROOT_LOGGER",
".",
"domainModelAppliedButRestartIsRequired",
"(",
")",
";",
"}",
"}",
"if",
"(",
"!",
"success",
")",
"{",
"ModelNode",
"failureDesc",
"=",
"result",
".",
"hasDefined",
"(",
"FAILURE_DESCRIPTION",
")",
"?",
"result",
".",
"get",
"(",
"FAILURE_DESCRIPTION",
")",
":",
"new",
"ModelNode",
"(",
")",
";",
"HostControllerLogger",
".",
"ROOT_LOGGER",
".",
"failedToApplyDomainConfig",
"(",
"outcome",
",",
"failureDesc",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"HostControllerLogger",
".",
"ROOT_LOGGER",
".",
"failedToApplyDomainConfig",
"(",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Apply the remote domain model to the local host controller.
@param bootOperations the result of the remote read-domain-model op
@return {@code true} if the model was applied successfully, {@code false} otherwise | [
"Apply",
"the",
"remote",
"domain",
"model",
"to",
"the",
"local",
"host",
"controller",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/RemoteDomainConnectionService.java#L592-L630 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java | TypeHandlerUtils.convertArray | public static Object convertArray(Connection conn, Collection<?> array) throws SQLException {
"""
Converts Collection into sql.Array
@param conn connection for which sql.Array object would be created
@param array Collection
@return sql.Array from Collection
@throws SQLException
"""
return convertArray(conn, array.toArray());
} | java | public static Object convertArray(Connection conn, Collection<?> array) throws SQLException {
return convertArray(conn, array.toArray());
} | [
"public",
"static",
"Object",
"convertArray",
"(",
"Connection",
"conn",
",",
"Collection",
"<",
"?",
">",
"array",
")",
"throws",
"SQLException",
"{",
"return",
"convertArray",
"(",
"conn",
",",
"array",
".",
"toArray",
"(",
")",
")",
";",
"}"
] | Converts Collection into sql.Array
@param conn connection for which sql.Array object would be created
@param array Collection
@return sql.Array from Collection
@throws SQLException | [
"Converts",
"Collection",
"into",
"sql",
".",
"Array"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java#L67-L69 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTask.java | HttpRemoteTask.doRemoveRemoteSource | private void doRemoveRemoteSource(RequestErrorTracker errorTracker, Request request, SettableFuture<?> future) {
"""
/ This method may call itself recursively when retrying for failures
"""
errorTracker.startRequest();
FutureCallback<StatusResponse> callback = new FutureCallback<StatusResponse>() {
@Override
public void onSuccess(@Nullable StatusResponse response)
{
if (response == null) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with null response");
}
if (response.getStatusCode() != OK.code()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with HTTP status " + response.getStatusCode());
}
future.set(null);
}
@Override
public void onFailure(Throwable failedReason)
{
if (failedReason instanceof RejectedExecutionException && httpClient.isClosed()) {
log.error("Unable to destroy exchange source at %s. HTTP client is closed", request.getUri());
future.setException(failedReason);
return;
}
// record failure
try {
errorTracker.requestFailed(failedReason);
}
catch (PrestoException e) {
future.setException(e);
return;
}
// if throttled due to error, asynchronously wait for timeout and try again
ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit();
if (errorRateLimit.isDone()) {
doRemoveRemoteSource(errorTracker, request, future);
}
else {
errorRateLimit.addListener(() -> doRemoveRemoteSource(errorTracker, request, future), errorScheduledExecutor);
}
}
};
addCallback(httpClient.executeAsync(request, createStatusResponseHandler()), callback, directExecutor());
} | java | private void doRemoveRemoteSource(RequestErrorTracker errorTracker, Request request, SettableFuture<?> future)
{
errorTracker.startRequest();
FutureCallback<StatusResponse> callback = new FutureCallback<StatusResponse>() {
@Override
public void onSuccess(@Nullable StatusResponse response)
{
if (response == null) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with null response");
}
if (response.getStatusCode() != OK.code()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Request failed with HTTP status " + response.getStatusCode());
}
future.set(null);
}
@Override
public void onFailure(Throwable failedReason)
{
if (failedReason instanceof RejectedExecutionException && httpClient.isClosed()) {
log.error("Unable to destroy exchange source at %s. HTTP client is closed", request.getUri());
future.setException(failedReason);
return;
}
// record failure
try {
errorTracker.requestFailed(failedReason);
}
catch (PrestoException e) {
future.setException(e);
return;
}
// if throttled due to error, asynchronously wait for timeout and try again
ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit();
if (errorRateLimit.isDone()) {
doRemoveRemoteSource(errorTracker, request, future);
}
else {
errorRateLimit.addListener(() -> doRemoveRemoteSource(errorTracker, request, future), errorScheduledExecutor);
}
}
};
addCallback(httpClient.executeAsync(request, createStatusResponseHandler()), callback, directExecutor());
} | [
"private",
"void",
"doRemoveRemoteSource",
"(",
"RequestErrorTracker",
"errorTracker",
",",
"Request",
"request",
",",
"SettableFuture",
"<",
"?",
">",
"future",
")",
"{",
"errorTracker",
".",
"startRequest",
"(",
")",
";",
"FutureCallback",
"<",
"StatusResponse",
">",
"callback",
"=",
"new",
"FutureCallback",
"<",
"StatusResponse",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"@",
"Nullable",
"StatusResponse",
"response",
")",
"{",
"if",
"(",
"response",
"==",
"null",
")",
"{",
"throw",
"new",
"PrestoException",
"(",
"GENERIC_INTERNAL_ERROR",
",",
"\"Request failed with null response\"",
")",
";",
"}",
"if",
"(",
"response",
".",
"getStatusCode",
"(",
")",
"!=",
"OK",
".",
"code",
"(",
")",
")",
"{",
"throw",
"new",
"PrestoException",
"(",
"GENERIC_INTERNAL_ERROR",
",",
"\"Request failed with HTTP status \"",
"+",
"response",
".",
"getStatusCode",
"(",
")",
")",
";",
"}",
"future",
".",
"set",
"(",
"null",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"Throwable",
"failedReason",
")",
"{",
"if",
"(",
"failedReason",
"instanceof",
"RejectedExecutionException",
"&&",
"httpClient",
".",
"isClosed",
"(",
")",
")",
"{",
"log",
".",
"error",
"(",
"\"Unable to destroy exchange source at %s. HTTP client is closed\"",
",",
"request",
".",
"getUri",
"(",
")",
")",
";",
"future",
".",
"setException",
"(",
"failedReason",
")",
";",
"return",
";",
"}",
"// record failure",
"try",
"{",
"errorTracker",
".",
"requestFailed",
"(",
"failedReason",
")",
";",
"}",
"catch",
"(",
"PrestoException",
"e",
")",
"{",
"future",
".",
"setException",
"(",
"e",
")",
";",
"return",
";",
"}",
"// if throttled due to error, asynchronously wait for timeout and try again",
"ListenableFuture",
"<",
"?",
">",
"errorRateLimit",
"=",
"errorTracker",
".",
"acquireRequestPermit",
"(",
")",
";",
"if",
"(",
"errorRateLimit",
".",
"isDone",
"(",
")",
")",
"{",
"doRemoveRemoteSource",
"(",
"errorTracker",
",",
"request",
",",
"future",
")",
";",
"}",
"else",
"{",
"errorRateLimit",
".",
"addListener",
"(",
"(",
")",
"->",
"doRemoveRemoteSource",
"(",
"errorTracker",
",",
"request",
",",
"future",
")",
",",
"errorScheduledExecutor",
")",
";",
"}",
"}",
"}",
";",
"addCallback",
"(",
"httpClient",
".",
"executeAsync",
"(",
"request",
",",
"createStatusResponseHandler",
"(",
")",
")",
",",
"callback",
",",
"directExecutor",
"(",
")",
")",
";",
"}"
] | / This method may call itself recursively when retrying for failures | [
"/",
"This",
"method",
"may",
"call",
"itself",
"recursively",
"when",
"retrying",
"for",
"failures"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTask.java#L423-L468 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.getBlock | public SceneBlock getBlock (int tx, int ty) {
"""
Returns the resolved block that contains the specified tile coordinate or null if no block
is resolved for that coordinate.
"""
int bx = MathUtil.floorDiv(tx, _metrics.blockwid);
int by = MathUtil.floorDiv(ty, _metrics.blockhei);
return _blocks.get(compose(bx, by));
} | java | public SceneBlock getBlock (int tx, int ty)
{
int bx = MathUtil.floorDiv(tx, _metrics.blockwid);
int by = MathUtil.floorDiv(ty, _metrics.blockhei);
return _blocks.get(compose(bx, by));
} | [
"public",
"SceneBlock",
"getBlock",
"(",
"int",
"tx",
",",
"int",
"ty",
")",
"{",
"int",
"bx",
"=",
"MathUtil",
".",
"floorDiv",
"(",
"tx",
",",
"_metrics",
".",
"blockwid",
")",
";",
"int",
"by",
"=",
"MathUtil",
".",
"floorDiv",
"(",
"ty",
",",
"_metrics",
".",
"blockhei",
")",
";",
"return",
"_blocks",
".",
"get",
"(",
"compose",
"(",
"bx",
",",
"by",
")",
")",
";",
"}"
] | Returns the resolved block that contains the specified tile coordinate or null if no block
is resolved for that coordinate. | [
"Returns",
"the",
"resolved",
"block",
"that",
"contains",
"the",
"specified",
"tile",
"coordinate",
"or",
"null",
"if",
"no",
"block",
"is",
"resolved",
"for",
"that",
"coordinate",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L265-L270 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java | Director.uninstallFeaturesByProductId | public void uninstallFeaturesByProductId(String productId, boolean exceptPlatformFeatures) throws InstallException {
"""
Calls below method to uninstall features by product id
@param productId product id to uninstall
@param exceptPlatformFeatures If platform features should be ignored
@throws InstallException
"""
String[] productIds = new String[1];
productIds[0] = productId;
uninstallFeaturesByProductId(productIds, exceptPlatformFeatures);
} | java | public void uninstallFeaturesByProductId(String productId, boolean exceptPlatformFeatures) throws InstallException {
String[] productIds = new String[1];
productIds[0] = productId;
uninstallFeaturesByProductId(productIds, exceptPlatformFeatures);
} | [
"public",
"void",
"uninstallFeaturesByProductId",
"(",
"String",
"productId",
",",
"boolean",
"exceptPlatformFeatures",
")",
"throws",
"InstallException",
"{",
"String",
"[",
"]",
"productIds",
"=",
"new",
"String",
"[",
"1",
"]",
";",
"productIds",
"[",
"0",
"]",
"=",
"productId",
";",
"uninstallFeaturesByProductId",
"(",
"productIds",
",",
"exceptPlatformFeatures",
")",
";",
"}"
] | Calls below method to uninstall features by product id
@param productId product id to uninstall
@param exceptPlatformFeatures If platform features should be ignored
@throws InstallException | [
"Calls",
"below",
"method",
"to",
"uninstall",
"features",
"by",
"product",
"id"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java#L1907-L1911 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/LongTermRetentionBackupsInner.java | LongTermRetentionBackupsInner.deleteAsync | public Observable<Void> deleteAsync(String locationName, String longTermRetentionServerName, String longTermRetentionDatabaseName, String backupName) {
"""
Deletes a long term retention backup.
@param locationName The location of the database
@param longTermRetentionServerName the String value
@param longTermRetentionDatabaseName the String value
@param backupName The backup name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return deleteWithServiceResponseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> deleteAsync(String locationName, String longTermRetentionServerName, String longTermRetentionDatabaseName, String backupName) {
return deleteWithServiceResponseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"deleteAsync",
"(",
"String",
"locationName",
",",
"String",
"longTermRetentionServerName",
",",
"String",
"longTermRetentionDatabaseName",
",",
"String",
"backupName",
")",
"{",
"return",
"deleteWithServiceResponseAsync",
"(",
"locationName",
",",
"longTermRetentionServerName",
",",
"longTermRetentionDatabaseName",
",",
"backupName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Void",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponse",
"<",
"Void",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Deletes a long term retention backup.
@param locationName The location of the database
@param longTermRetentionServerName the String value
@param longTermRetentionDatabaseName the String value
@param backupName The backup name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Deletes",
"a",
"long",
"term",
"retention",
"backup",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/LongTermRetentionBackupsInner.java#L240-L247 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/LinearEquationSystem.java | LinearEquationSystem.equationsToString | public String equationsToString(String prefix, NumberFormat nf) {
"""
Returns a string representation of this equation system.
@param prefix the prefix of each line
@param nf the number format
@return a string representation of this equation system
"""
if((coeff == null) || (rhs == null) || (row == null) || (col == null)) {
throw new NullPointerException();
}
int[] coeffDigits = maxIntegerDigits(coeff);
int rhsDigits = maxIntegerDigits(rhs);
StringBuilder buffer = new StringBuilder();
buffer.append(prefix).append('\n').append(prefix);
for(int i = 0; i < coeff.length; i++) {
for(int j = 0; j < coeff[row[0]].length; j++) {
format(nf, buffer, coeff[row[i]][col[j]], coeffDigits[col[j]]);
buffer.append(" * x_").append(col[j]);
}
buffer.append(" =");
format(nf, buffer, rhs[row[i]], rhsDigits);
if(i < coeff.length - 1) {
buffer.append('\n').append(prefix);
}
else {
buffer.append('\n').append(prefix);
}
}
return buffer.toString();
} | java | public String equationsToString(String prefix, NumberFormat nf) {
if((coeff == null) || (rhs == null) || (row == null) || (col == null)) {
throw new NullPointerException();
}
int[] coeffDigits = maxIntegerDigits(coeff);
int rhsDigits = maxIntegerDigits(rhs);
StringBuilder buffer = new StringBuilder();
buffer.append(prefix).append('\n').append(prefix);
for(int i = 0; i < coeff.length; i++) {
for(int j = 0; j < coeff[row[0]].length; j++) {
format(nf, buffer, coeff[row[i]][col[j]], coeffDigits[col[j]]);
buffer.append(" * x_").append(col[j]);
}
buffer.append(" =");
format(nf, buffer, rhs[row[i]], rhsDigits);
if(i < coeff.length - 1) {
buffer.append('\n').append(prefix);
}
else {
buffer.append('\n').append(prefix);
}
}
return buffer.toString();
} | [
"public",
"String",
"equationsToString",
"(",
"String",
"prefix",
",",
"NumberFormat",
"nf",
")",
"{",
"if",
"(",
"(",
"coeff",
"==",
"null",
")",
"||",
"(",
"rhs",
"==",
"null",
")",
"||",
"(",
"row",
"==",
"null",
")",
"||",
"(",
"col",
"==",
"null",
")",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
")",
";",
"}",
"int",
"[",
"]",
"coeffDigits",
"=",
"maxIntegerDigits",
"(",
"coeff",
")",
";",
"int",
"rhsDigits",
"=",
"maxIntegerDigits",
"(",
"rhs",
")",
";",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buffer",
".",
"append",
"(",
"prefix",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"prefix",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"coeff",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"coeff",
"[",
"row",
"[",
"0",
"]",
"]",
".",
"length",
";",
"j",
"++",
")",
"{",
"format",
"(",
"nf",
",",
"buffer",
",",
"coeff",
"[",
"row",
"[",
"i",
"]",
"]",
"[",
"col",
"[",
"j",
"]",
"]",
",",
"coeffDigits",
"[",
"col",
"[",
"j",
"]",
"]",
")",
";",
"buffer",
".",
"append",
"(",
"\" * x_\"",
")",
".",
"append",
"(",
"col",
"[",
"j",
"]",
")",
";",
"}",
"buffer",
".",
"append",
"(",
"\" =\"",
")",
";",
"format",
"(",
"nf",
",",
"buffer",
",",
"rhs",
"[",
"row",
"[",
"i",
"]",
"]",
",",
"rhsDigits",
")",
";",
"if",
"(",
"i",
"<",
"coeff",
".",
"length",
"-",
"1",
")",
"{",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"prefix",
")",
";",
"}",
"else",
"{",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"prefix",
")",
";",
"}",
"}",
"return",
"buffer",
".",
"toString",
"(",
")",
";",
"}"
] | Returns a string representation of this equation system.
@param prefix the prefix of each line
@param nf the number format
@return a string representation of this equation system | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"equation",
"system",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/LinearEquationSystem.java#L292-L318 |
EdwardRaff/JSAT | JSAT/src/jsat/datatransform/NumericalToHistogram.java | NumericalToHistogram.guessNumberOfBins | public static Distribution guessNumberOfBins(DataSet data) {
"""
Attempts to guess the number of bins to use
@param data the dataset to be transforms
@return a distribution of the guess
"""
if(data.size() < 20)
return new UniformDiscrete(2, data.size()-1);
else if(data.size() >= 1000000)
return new LogUniform(50, 1000);
int sqrt = (int) Math.sqrt(data.size());
return new UniformDiscrete(Math.max(sqrt/3, 2), Math.min(sqrt*3, data.size()-1));
} | java | public static Distribution guessNumberOfBins(DataSet data)
{
if(data.size() < 20)
return new UniformDiscrete(2, data.size()-1);
else if(data.size() >= 1000000)
return new LogUniform(50, 1000);
int sqrt = (int) Math.sqrt(data.size());
return new UniformDiscrete(Math.max(sqrt/3, 2), Math.min(sqrt*3, data.size()-1));
} | [
"public",
"static",
"Distribution",
"guessNumberOfBins",
"(",
"DataSet",
"data",
")",
"{",
"if",
"(",
"data",
".",
"size",
"(",
")",
"<",
"20",
")",
"return",
"new",
"UniformDiscrete",
"(",
"2",
",",
"data",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"else",
"if",
"(",
"data",
".",
"size",
"(",
")",
">=",
"1000000",
")",
"return",
"new",
"LogUniform",
"(",
"50",
",",
"1000",
")",
";",
"int",
"sqrt",
"=",
"(",
"int",
")",
"Math",
".",
"sqrt",
"(",
"data",
".",
"size",
"(",
")",
")",
";",
"return",
"new",
"UniformDiscrete",
"(",
"Math",
".",
"max",
"(",
"sqrt",
"/",
"3",
",",
"2",
")",
",",
"Math",
".",
"min",
"(",
"sqrt",
"*",
"3",
",",
"data",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"}"
] | Attempts to guess the number of bins to use
@param data the dataset to be transforms
@return a distribution of the guess | [
"Attempts",
"to",
"guess",
"the",
"number",
"of",
"bins",
"to",
"use"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/datatransform/NumericalToHistogram.java#L138-L146 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java | DownloadChemCompProvider.getLocalFileName | public static String getLocalFileName(String recordName) {
"""
Returns the file name that contains the definition for this {@link ChemComp}
@param recordName the ID of the {@link ChemComp}
@return full path to the file
"""
if ( protectedIDs.contains(recordName)){
recordName = "_" + recordName;
}
File f = new File(getPath(), CHEM_COMP_CACHE_DIRECTORY);
if (! f.exists()){
logger.info("Creating directory " + f);
boolean success = f.mkdir();
// we've checked in initPath that path is writable, so there's no need to check if it succeeds
// in the unlikely case that in the meantime it isn't writable at least we log an error
if (!success)
logger.error("Directory {} could not be created",f);
}
File theFile = new File(f,recordName + ".cif.gz");
return theFile.toString();
} | java | public static String getLocalFileName(String recordName){
if ( protectedIDs.contains(recordName)){
recordName = "_" + recordName;
}
File f = new File(getPath(), CHEM_COMP_CACHE_DIRECTORY);
if (! f.exists()){
logger.info("Creating directory " + f);
boolean success = f.mkdir();
// we've checked in initPath that path is writable, so there's no need to check if it succeeds
// in the unlikely case that in the meantime it isn't writable at least we log an error
if (!success)
logger.error("Directory {} could not be created",f);
}
File theFile = new File(f,recordName + ".cif.gz");
return theFile.toString();
} | [
"public",
"static",
"String",
"getLocalFileName",
"(",
"String",
"recordName",
")",
"{",
"if",
"(",
"protectedIDs",
".",
"contains",
"(",
"recordName",
")",
")",
"{",
"recordName",
"=",
"\"_\"",
"+",
"recordName",
";",
"}",
"File",
"f",
"=",
"new",
"File",
"(",
"getPath",
"(",
")",
",",
"CHEM_COMP_CACHE_DIRECTORY",
")",
";",
"if",
"(",
"!",
"f",
".",
"exists",
"(",
")",
")",
"{",
"logger",
".",
"info",
"(",
"\"Creating directory \"",
"+",
"f",
")",
";",
"boolean",
"success",
"=",
"f",
".",
"mkdir",
"(",
")",
";",
"// we've checked in initPath that path is writable, so there's no need to check if it succeeds",
"// in the unlikely case that in the meantime it isn't writable at least we log an error",
"if",
"(",
"!",
"success",
")",
"logger",
".",
"error",
"(",
"\"Directory {} could not be created\"",
",",
"f",
")",
";",
"}",
"File",
"theFile",
"=",
"new",
"File",
"(",
"f",
",",
"recordName",
"+",
"\".cif.gz\"",
")",
";",
"return",
"theFile",
".",
"toString",
"(",
")",
";",
"}"
] | Returns the file name that contains the definition for this {@link ChemComp}
@param recordName the ID of the {@link ChemComp}
@return full path to the file | [
"Returns",
"the",
"file",
"name",
"that",
"contains",
"the",
"definition",
"for",
"this",
"{",
"@link",
"ChemComp",
"}"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java#L332-L353 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FileUtil.java | FileUtil.tryGzipInput | public static InputStream tryGzipInput(InputStream in) throws IOException {
"""
Try to open a stream as gzip, if it starts with the gzip magic.
@param in original input stream
@return old input stream or a {@link GZIPInputStream} if appropriate.
@throws IOException on IO error
"""
// try autodetecting gzip compression.
if(!in.markSupported()) {
PushbackInputStream pb = new PushbackInputStream(in, 16);
// read a magic from the file header, and push it back
byte[] magic = { 0, 0 };
int r = pb.read(magic);
pb.unread(magic, 0, r);
return (magic[0] == 31 && magic[1] == -117) ? new GZIPInputStream(pb) : pb;
}
// Mark is supported.
in.mark(16);
boolean isgzip = ((in.read() << 8) | in.read()) == GZIPInputStream.GZIP_MAGIC;
in.reset(); // Rewind
return isgzip ? new GZIPInputStream(in) : in;
} | java | public static InputStream tryGzipInput(InputStream in) throws IOException {
// try autodetecting gzip compression.
if(!in.markSupported()) {
PushbackInputStream pb = new PushbackInputStream(in, 16);
// read a magic from the file header, and push it back
byte[] magic = { 0, 0 };
int r = pb.read(magic);
pb.unread(magic, 0, r);
return (magic[0] == 31 && magic[1] == -117) ? new GZIPInputStream(pb) : pb;
}
// Mark is supported.
in.mark(16);
boolean isgzip = ((in.read() << 8) | in.read()) == GZIPInputStream.GZIP_MAGIC;
in.reset(); // Rewind
return isgzip ? new GZIPInputStream(in) : in;
} | [
"public",
"static",
"InputStream",
"tryGzipInput",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"// try autodetecting gzip compression.",
"if",
"(",
"!",
"in",
".",
"markSupported",
"(",
")",
")",
"{",
"PushbackInputStream",
"pb",
"=",
"new",
"PushbackInputStream",
"(",
"in",
",",
"16",
")",
";",
"// read a magic from the file header, and push it back",
"byte",
"[",
"]",
"magic",
"=",
"{",
"0",
",",
"0",
"}",
";",
"int",
"r",
"=",
"pb",
".",
"read",
"(",
"magic",
")",
";",
"pb",
".",
"unread",
"(",
"magic",
",",
"0",
",",
"r",
")",
";",
"return",
"(",
"magic",
"[",
"0",
"]",
"==",
"31",
"&&",
"magic",
"[",
"1",
"]",
"==",
"-",
"117",
")",
"?",
"new",
"GZIPInputStream",
"(",
"pb",
")",
":",
"pb",
";",
"}",
"// Mark is supported.",
"in",
".",
"mark",
"(",
"16",
")",
";",
"boolean",
"isgzip",
"=",
"(",
"(",
"in",
".",
"read",
"(",
")",
"<<",
"8",
")",
"|",
"in",
".",
"read",
"(",
")",
")",
"==",
"GZIPInputStream",
".",
"GZIP_MAGIC",
";",
"in",
".",
"reset",
"(",
")",
";",
"// Rewind",
"return",
"isgzip",
"?",
"new",
"GZIPInputStream",
"(",
"in",
")",
":",
"in",
";",
"}"
] | Try to open a stream as gzip, if it starts with the gzip magic.
@param in original input stream
@return old input stream or a {@link GZIPInputStream} if appropriate.
@throws IOException on IO error | [
"Try",
"to",
"open",
"a",
"stream",
"as",
"gzip",
"if",
"it",
"starts",
"with",
"the",
"gzip",
"magic",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FileUtil.java#L124-L139 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java | DataService.populateQueryResultsInCDC | private void populateQueryResultsInCDC(Map<String, QueryResult> queryResults, QueryResult queryResult) {
"""
Method to populate the QueryResults hash map by reading the key from QueryResult entities
@param queryResults
the queryResults hash map to be populated
@param queryResult
the QueryResult object
"""
if (queryResult != null) {
List<? extends IEntity> entities = queryResult.getEntities();
if (entities != null && !entities.isEmpty()) {
IEntity entity = entities.get(0);
String entityName = entity.getClass().getSimpleName();
queryResults.put(entityName, queryResult);
}
}
} | java | private void populateQueryResultsInCDC(Map<String, QueryResult> queryResults, QueryResult queryResult) {
if (queryResult != null) {
List<? extends IEntity> entities = queryResult.getEntities();
if (entities != null && !entities.isEmpty()) {
IEntity entity = entities.get(0);
String entityName = entity.getClass().getSimpleName();
queryResults.put(entityName, queryResult);
}
}
} | [
"private",
"void",
"populateQueryResultsInCDC",
"(",
"Map",
"<",
"String",
",",
"QueryResult",
">",
"queryResults",
",",
"QueryResult",
"queryResult",
")",
"{",
"if",
"(",
"queryResult",
"!=",
"null",
")",
"{",
"List",
"<",
"?",
"extends",
"IEntity",
">",
"entities",
"=",
"queryResult",
".",
"getEntities",
"(",
")",
";",
"if",
"(",
"entities",
"!=",
"null",
"&&",
"!",
"entities",
".",
"isEmpty",
"(",
")",
")",
"{",
"IEntity",
"entity",
"=",
"entities",
".",
"get",
"(",
"0",
")",
";",
"String",
"entityName",
"=",
"entity",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
";",
"queryResults",
".",
"put",
"(",
"entityName",
",",
"queryResult",
")",
";",
"}",
"}",
"}"
] | Method to populate the QueryResults hash map by reading the key from QueryResult entities
@param queryResults
the queryResults hash map to be populated
@param queryResult
the QueryResult object | [
"Method",
"to",
"populate",
"the",
"QueryResults",
"hash",
"map",
"by",
"reading",
"the",
"key",
"from",
"QueryResult",
"entities"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java#L1699-L1708 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java | PackageSummaryBuilder.buildPackageDescription | public void buildPackageDescription(XMLNode node, Content packageContentTree) {
"""
Build the description of the summary.
@param node the XML element that specifies which components to document
@param packageContentTree the tree to which the package description will
be added
"""
if (configuration.nocomment) {
return;
}
packageWriter.addPackageDescription(packageContentTree);
} | java | public void buildPackageDescription(XMLNode node, Content packageContentTree) {
if (configuration.nocomment) {
return;
}
packageWriter.addPackageDescription(packageContentTree);
} | [
"public",
"void",
"buildPackageDescription",
"(",
"XMLNode",
"node",
",",
"Content",
"packageContentTree",
")",
"{",
"if",
"(",
"configuration",
".",
"nocomment",
")",
"{",
"return",
";",
"}",
"packageWriter",
".",
"addPackageDescription",
"(",
"packageContentTree",
")",
";",
"}"
] | Build the description of the summary.
@param node the XML element that specifies which components to document
@param packageContentTree the tree to which the package description will
be added | [
"Build",
"the",
"description",
"of",
"the",
"summary",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java#L334-L339 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java | MatrixFeatures_DDRM.isZeros | public static boolean isZeros(DMatrixD1 m , double tol ) {
"""
Checks to see all the elements in the matrix are zeros
@param m A matrix. Not modified.
@return True if all elements are zeros or false if not
"""
int length = m.getNumElements();
for( int i = 0; i < length; i++ ) {
if( Math.abs(m.get(i)) > tol )
return false;
}
return true;
} | java | public static boolean isZeros(DMatrixD1 m , double tol )
{
int length = m.getNumElements();
for( int i = 0; i < length; i++ ) {
if( Math.abs(m.get(i)) > tol )
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"isZeros",
"(",
"DMatrixD1",
"m",
",",
"double",
"tol",
")",
"{",
"int",
"length",
"=",
"m",
".",
"getNumElements",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"m",
".",
"get",
"(",
"i",
")",
")",
">",
"tol",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Checks to see all the elements in the matrix are zeros
@param m A matrix. Not modified.
@return True if all elements are zeros or false if not | [
"Checks",
"to",
"see",
"all",
"the",
"elements",
"in",
"the",
"matrix",
"are",
"zeros"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java#L87-L96 |
roboconf/roboconf-platform | core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/RandomMngrImpl.java | RandomMngrImpl.acknowledgePort | private boolean acknowledgePort( Application application, Instance instance, String exportedVariableName ) {
"""
If the instance already has a value (overridden export) for a random variable, then use it.
<p>
Basically, we do not have to define an overridden export.
We only have to update the cache to not pick up the same port later.
</p>
@param application the application
@param instance the instance
@param exportedVariableName the name of the exported variable
@return
"""
boolean acknowledged = false;
String value = instance.overriddenExports.get( exportedVariableName );
if( value != null ) {
// If there is an overridden value, use it
this.logger.fine( "Acknowledging random port value for " + exportedVariableName + " in instance " + instance + " of " + application );
Integer portValue = Integer.parseInt( value );
InstanceContext ctx = findAgentContext( application, instance );
List<Integer> associatedPorts = this.agentToRandomPorts.get( ctx );
if( associatedPorts == null ) {
associatedPorts = new ArrayList<> ();
this.agentToRandomPorts.put( ctx, associatedPorts );
}
// Verify it is not already used.
// And cache it so that we do not pick it up later.
if( associatedPorts.contains( portValue )) {
this.logger.warning( "Random port already used! Failed to acknowledge/restore " + exportedVariableName + " in instance " + instance + " of " + application );
acknowledged = false;
} else {
associatedPorts.add( portValue );
acknowledged = true;
}
}
return acknowledged;
} | java | private boolean acknowledgePort( Application application, Instance instance, String exportedVariableName ) {
boolean acknowledged = false;
String value = instance.overriddenExports.get( exportedVariableName );
if( value != null ) {
// If there is an overridden value, use it
this.logger.fine( "Acknowledging random port value for " + exportedVariableName + " in instance " + instance + " of " + application );
Integer portValue = Integer.parseInt( value );
InstanceContext ctx = findAgentContext( application, instance );
List<Integer> associatedPorts = this.agentToRandomPorts.get( ctx );
if( associatedPorts == null ) {
associatedPorts = new ArrayList<> ();
this.agentToRandomPorts.put( ctx, associatedPorts );
}
// Verify it is not already used.
// And cache it so that we do not pick it up later.
if( associatedPorts.contains( portValue )) {
this.logger.warning( "Random port already used! Failed to acknowledge/restore " + exportedVariableName + " in instance " + instance + " of " + application );
acknowledged = false;
} else {
associatedPorts.add( portValue );
acknowledged = true;
}
}
return acknowledged;
} | [
"private",
"boolean",
"acknowledgePort",
"(",
"Application",
"application",
",",
"Instance",
"instance",
",",
"String",
"exportedVariableName",
")",
"{",
"boolean",
"acknowledged",
"=",
"false",
";",
"String",
"value",
"=",
"instance",
".",
"overriddenExports",
".",
"get",
"(",
"exportedVariableName",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"// If there is an overridden value, use it",
"this",
".",
"logger",
".",
"fine",
"(",
"\"Acknowledging random port value for \"",
"+",
"exportedVariableName",
"+",
"\" in instance \"",
"+",
"instance",
"+",
"\" of \"",
"+",
"application",
")",
";",
"Integer",
"portValue",
"=",
"Integer",
".",
"parseInt",
"(",
"value",
")",
";",
"InstanceContext",
"ctx",
"=",
"findAgentContext",
"(",
"application",
",",
"instance",
")",
";",
"List",
"<",
"Integer",
">",
"associatedPorts",
"=",
"this",
".",
"agentToRandomPorts",
".",
"get",
"(",
"ctx",
")",
";",
"if",
"(",
"associatedPorts",
"==",
"null",
")",
"{",
"associatedPorts",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"this",
".",
"agentToRandomPorts",
".",
"put",
"(",
"ctx",
",",
"associatedPorts",
")",
";",
"}",
"// Verify it is not already used.",
"// And cache it so that we do not pick it up later.",
"if",
"(",
"associatedPorts",
".",
"contains",
"(",
"portValue",
")",
")",
"{",
"this",
".",
"logger",
".",
"warning",
"(",
"\"Random port already used! Failed to acknowledge/restore \"",
"+",
"exportedVariableName",
"+",
"\" in instance \"",
"+",
"instance",
"+",
"\" of \"",
"+",
"application",
")",
";",
"acknowledged",
"=",
"false",
";",
"}",
"else",
"{",
"associatedPorts",
".",
"add",
"(",
"portValue",
")",
";",
"acknowledged",
"=",
"true",
";",
"}",
"}",
"return",
"acknowledged",
";",
"}"
] | If the instance already has a value (overridden export) for a random variable, then use it.
<p>
Basically, we do not have to define an overridden export.
We only have to update the cache to not pick up the same port later.
</p>
@param application the application
@param instance the instance
@param exportedVariableName the name of the exported variable
@return | [
"If",
"the",
"instance",
"already",
"has",
"a",
"value",
"(",
"overridden",
"export",
")",
"for",
"a",
"random",
"variable",
"then",
"use",
"it",
".",
"<p",
">",
"Basically",
"we",
"do",
"not",
"have",
"to",
"define",
"an",
"overridden",
"export",
".",
"We",
"only",
"have",
"to",
"update",
"the",
"cache",
"to",
"not",
"pick",
"up",
"the",
"same",
"port",
"later",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/RandomMngrImpl.java#L264-L294 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/model/workflow/Process.java | Process.getTransition | public Transition getTransition(Long fromId, Integer eventType, String completionCode) {
"""
Finds one work transition for this process matching the specified parameters
@param fromId
@param eventType
@param completionCode
@return the work transition value object (or null if not found)
"""
Transition ret = null;
for (Transition transition : getTransitions()) {
if (transition.getFromId().equals(fromId)
&& transition.match(eventType, completionCode)) {
if (ret == null) ret = transition;
else {
throw new IllegalStateException("Multiple matching work transitions when one expected:\n"
+ " processId: " + getId() + " fromId: " + fromId + " eventType: "
+ eventType + "compCode: " + completionCode);
}
}
}
return ret;
} | java | public Transition getTransition(Long fromId, Integer eventType, String completionCode) {
Transition ret = null;
for (Transition transition : getTransitions()) {
if (transition.getFromId().equals(fromId)
&& transition.match(eventType, completionCode)) {
if (ret == null) ret = transition;
else {
throw new IllegalStateException("Multiple matching work transitions when one expected:\n"
+ " processId: " + getId() + " fromId: " + fromId + " eventType: "
+ eventType + "compCode: " + completionCode);
}
}
}
return ret;
} | [
"public",
"Transition",
"getTransition",
"(",
"Long",
"fromId",
",",
"Integer",
"eventType",
",",
"String",
"completionCode",
")",
"{",
"Transition",
"ret",
"=",
"null",
";",
"for",
"(",
"Transition",
"transition",
":",
"getTransitions",
"(",
")",
")",
"{",
"if",
"(",
"transition",
".",
"getFromId",
"(",
")",
".",
"equals",
"(",
"fromId",
")",
"&&",
"transition",
".",
"match",
"(",
"eventType",
",",
"completionCode",
")",
")",
"{",
"if",
"(",
"ret",
"==",
"null",
")",
"ret",
"=",
"transition",
";",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Multiple matching work transitions when one expected:\\n\"",
"+",
"\" processId: \"",
"+",
"getId",
"(",
")",
"+",
"\" fromId: \"",
"+",
"fromId",
"+",
"\" eventType: \"",
"+",
"eventType",
"+",
"\"compCode: \"",
"+",
"completionCode",
")",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
] | Finds one work transition for this process matching the specified parameters
@param fromId
@param eventType
@param completionCode
@return the work transition value object (or null if not found) | [
"Finds",
"one",
"work",
"transition",
"for",
"this",
"process",
"matching",
"the",
"specified",
"parameters"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/workflow/Process.java#L313-L327 |
alkacon/opencms-core | src/org/opencms/module/CmsModuleManager.java | CmsModuleManager.deleteModule | public synchronized void deleteModule(CmsObject cms, String moduleName, boolean replace, I_CmsReport report)
throws CmsRoleViolationException, CmsConfigurationException, CmsLockException {
"""
Deletes a module from the configuration.<p>
@param cms must be initialized with "Admin" permissions
@param moduleName the name of the module to delete
@param replace indicates if the module is replaced (true) or finally deleted (false)
@param report the report to print progress messages to
@throws CmsRoleViolationException if the required module manager role permissions are not available
@throws CmsConfigurationException if a module with this name is not available for deleting
@throws CmsLockException if the module resources can not be locked
"""
deleteModule(cms, moduleName, replace, false, report);
} | java | public synchronized void deleteModule(CmsObject cms, String moduleName, boolean replace, I_CmsReport report)
throws CmsRoleViolationException, CmsConfigurationException, CmsLockException {
deleteModule(cms, moduleName, replace, false, report);
} | [
"public",
"synchronized",
"void",
"deleteModule",
"(",
"CmsObject",
"cms",
",",
"String",
"moduleName",
",",
"boolean",
"replace",
",",
"I_CmsReport",
"report",
")",
"throws",
"CmsRoleViolationException",
",",
"CmsConfigurationException",
",",
"CmsLockException",
"{",
"deleteModule",
"(",
"cms",
",",
"moduleName",
",",
"replace",
",",
"false",
",",
"report",
")",
";",
"}"
] | Deletes a module from the configuration.<p>
@param cms must be initialized with "Admin" permissions
@param moduleName the name of the module to delete
@param replace indicates if the module is replaced (true) or finally deleted (false)
@param report the report to print progress messages to
@throws CmsRoleViolationException if the required module manager role permissions are not available
@throws CmsConfigurationException if a module with this name is not available for deleting
@throws CmsLockException if the module resources can not be locked | [
"Deletes",
"a",
"module",
"from",
"the",
"configuration",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleManager.java#L747-L751 |
GCRC/nunaliit | nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java | Files.getDescendantPathNames | static public Set<String> getDescendantPathNames(File dir, boolean includeDirectories) {
"""
Given a directory, returns a set of strings which are the paths to all elements
within the directory. This process recurses through all sub-directories.
@param dir The directory to be traversed
@param includeDirectories If set, the name of the paths to directories are included
in the result.
@return A set of paths to all elements in the given directory
"""
Set<String> paths = new HashSet<String>();
if( dir.exists() && dir.isDirectory() ) {
String[] names = dir.list();
for(String name : names){
File child = new File(dir,name);
getPathNames(child, paths, null, includeDirectories);
}
}
return paths;
} | java | static public Set<String> getDescendantPathNames(File dir, boolean includeDirectories) {
Set<String> paths = new HashSet<String>();
if( dir.exists() && dir.isDirectory() ) {
String[] names = dir.list();
for(String name : names){
File child = new File(dir,name);
getPathNames(child, paths, null, includeDirectories);
}
}
return paths;
} | [
"static",
"public",
"Set",
"<",
"String",
">",
"getDescendantPathNames",
"(",
"File",
"dir",
",",
"boolean",
"includeDirectories",
")",
"{",
"Set",
"<",
"String",
">",
"paths",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"dir",
".",
"exists",
"(",
")",
"&&",
"dir",
".",
"isDirectory",
"(",
")",
")",
"{",
"String",
"[",
"]",
"names",
"=",
"dir",
".",
"list",
"(",
")",
";",
"for",
"(",
"String",
"name",
":",
"names",
")",
"{",
"File",
"child",
"=",
"new",
"File",
"(",
"dir",
",",
"name",
")",
";",
"getPathNames",
"(",
"child",
",",
"paths",
",",
"null",
",",
"includeDirectories",
")",
";",
"}",
"}",
"return",
"paths",
";",
"}"
] | Given a directory, returns a set of strings which are the paths to all elements
within the directory. This process recurses through all sub-directories.
@param dir The directory to be traversed
@param includeDirectories If set, the name of the paths to directories are included
in the result.
@return A set of paths to all elements in the given directory | [
"Given",
"a",
"directory",
"returns",
"a",
"set",
"of",
"strings",
"which",
"are",
"the",
"paths",
"to",
"all",
"elements",
"within",
"the",
"directory",
".",
"This",
"process",
"recurses",
"through",
"all",
"sub",
"-",
"directories",
"."
] | train | https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java#L85-L95 |
indeedeng/util | io/src/main/java/com/indeed/util/io/Files.java | Files.writeObjectIfChanged | @Deprecated
public static boolean writeObjectIfChanged(Object obj, String filepath) {
"""
Writes an object to a file only if it is different from the current
contents of the file, or if the file does not exist. Note that you must
have enough heap to contain the entire contents of the object graph.
@return true if the file was actually written, false otherwise
@deprecated use {@link #writeObjectIfChangedOrDie(Object, String, org.apache.log4j.Logger)} instead
"""
try {
return writeObjectIfChangedOrDie(obj, filepath, LOGGER);
} catch (Exception e) {
LOGGER.error(e.getClass() + ": writeObjectIfChanged(" + filepath + ") encountered exception: " + e.getMessage(), e);
return false;
}
} | java | @Deprecated
public static boolean writeObjectIfChanged(Object obj, String filepath) {
try {
return writeObjectIfChangedOrDie(obj, filepath, LOGGER);
} catch (Exception e) {
LOGGER.error(e.getClass() + ": writeObjectIfChanged(" + filepath + ") encountered exception: " + e.getMessage(), e);
return false;
}
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"writeObjectIfChanged",
"(",
"Object",
"obj",
",",
"String",
"filepath",
")",
"{",
"try",
"{",
"return",
"writeObjectIfChangedOrDie",
"(",
"obj",
",",
"filepath",
",",
"LOGGER",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"e",
".",
"getClass",
"(",
")",
"+",
"\": writeObjectIfChanged(\"",
"+",
"filepath",
"+",
"\") encountered exception: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Writes an object to a file only if it is different from the current
contents of the file, or if the file does not exist. Note that you must
have enough heap to contain the entire contents of the object graph.
@return true if the file was actually written, false otherwise
@deprecated use {@link #writeObjectIfChangedOrDie(Object, String, org.apache.log4j.Logger)} instead | [
"Writes",
"an",
"object",
"to",
"a",
"file",
"only",
"if",
"it",
"is",
"different",
"from",
"the",
"current",
"contents",
"of",
"the",
"file",
"or",
"if",
"the",
"file",
"does",
"not",
"exist",
".",
"Note",
"that",
"you",
"must",
"have",
"enough",
"heap",
"to",
"contain",
"the",
"entire",
"contents",
"of",
"the",
"object",
"graph",
"."
] | train | https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/io/src/main/java/com/indeed/util/io/Files.java#L354-L362 |
jmrozanec/cron-utils | src/main/java/com/cronutils/descriptor/DescriptionStrategyFactory.java | DescriptionStrategyFactory.plainInstance | public static DescriptionStrategy plainInstance(final ResourceBundle bundle, final FieldExpression expression) {
"""
Creates nominal description strategy.
@param bundle - locale
@param expression - CronFieldExpression
@return - DescriptionStrategy instance, never null
"""
return new NominalDescriptionStrategy(bundle, null, expression);
} | java | public static DescriptionStrategy plainInstance(final ResourceBundle bundle, final FieldExpression expression) {
return new NominalDescriptionStrategy(bundle, null, expression);
} | [
"public",
"static",
"DescriptionStrategy",
"plainInstance",
"(",
"final",
"ResourceBundle",
"bundle",
",",
"final",
"FieldExpression",
"expression",
")",
"{",
"return",
"new",
"NominalDescriptionStrategy",
"(",
"bundle",
",",
"null",
",",
"expression",
")",
";",
"}"
] | Creates nominal description strategy.
@param bundle - locale
@param expression - CronFieldExpression
@return - DescriptionStrategy instance, never null | [
"Creates",
"nominal",
"description",
"strategy",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/descriptor/DescriptionStrategyFactory.java#L115-L117 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLocalizationPersistenceImpl.java | CPDefinitionLocalizationPersistenceImpl.findByCPDefinitionId | @Override
public List<CPDefinitionLocalization> findByCPDefinitionId(
long CPDefinitionId, int start, int end) {
"""
Returns a range of all the cp definition localizations where CPDefinitionId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionLocalizationModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CPDefinitionId the cp definition ID
@param start the lower bound of the range of cp definition localizations
@param end the upper bound of the range of cp definition localizations (not inclusive)
@return the range of matching cp definition localizations
"""
return findByCPDefinitionId(CPDefinitionId, start, end, null);
} | java | @Override
public List<CPDefinitionLocalization> findByCPDefinitionId(
long CPDefinitionId, int start, int end) {
return findByCPDefinitionId(CPDefinitionId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionLocalization",
">",
"findByCPDefinitionId",
"(",
"long",
"CPDefinitionId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCPDefinitionId",
"(",
"CPDefinitionId",
",",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the cp definition localizations where CPDefinitionId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionLocalizationModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CPDefinitionId the cp definition ID
@param start the lower bound of the range of cp definition localizations
@param end the upper bound of the range of cp definition localizations (not inclusive)
@return the range of matching cp definition localizations | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"definition",
"localizations",
"where",
"CPDefinitionId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLocalizationPersistenceImpl.java#L139-L143 |
pressgang-ccms/PressGangCCMSContentSpecProcessor | src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java | ContentSpecParser.isMetaDataLine | protected boolean isMetaDataLine(ParserData parserData, String line) {
"""
Checks to see if a line is represents a Content Specifications Meta Data.
@param parserData
@param line The line to be checked.
@return True if the line is meta data, otherwise false.
"""
return parserData.getCurrentLevel().getLevelType() == LevelType.BASE && line.trim().matches("^\\w[\\w\\.\\s-]+=.*");
} | java | protected boolean isMetaDataLine(ParserData parserData, String line) {
return parserData.getCurrentLevel().getLevelType() == LevelType.BASE && line.trim().matches("^\\w[\\w\\.\\s-]+=.*");
} | [
"protected",
"boolean",
"isMetaDataLine",
"(",
"ParserData",
"parserData",
",",
"String",
"line",
")",
"{",
"return",
"parserData",
".",
"getCurrentLevel",
"(",
")",
".",
"getLevelType",
"(",
")",
"==",
"LevelType",
".",
"BASE",
"&&",
"line",
".",
"trim",
"(",
")",
".",
"matches",
"(",
"\"^\\\\w[\\\\w\\\\.\\\\s-]+=.*\"",
")",
";",
"}"
] | Checks to see if a line is represents a Content Specifications Meta Data.
@param parserData
@param line The line to be checked.
@return True if the line is meta data, otherwise false. | [
"Checks",
"to",
"see",
"if",
"a",
"line",
"is",
"represents",
"a",
"Content",
"Specifications",
"Meta",
"Data",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java#L518-L520 |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/url/PortalUrlProviderImpl.java | PortalUrlProviderImpl.getLayoutNodeType | protected LayoutNodeType getLayoutNodeType(HttpServletRequest request, String folderNodeId) {
"""
Verify the requested node exists in the user's layout. Also if the node exists see if it is a
portlet node and if it is return the {@link IPortletWindowId} of the corresponding portlet.
"""
final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
final IUserPreferencesManager preferencesManager = userInstance.getPreferencesManager();
final IUserLayoutManager userLayoutManager = preferencesManager.getUserLayoutManager();
final IUserLayoutNodeDescription node = userLayoutManager.getNode(folderNodeId);
if (node == null) {
return null;
}
return node.getType();
} | java | protected LayoutNodeType getLayoutNodeType(HttpServletRequest request, String folderNodeId) {
final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
final IUserPreferencesManager preferencesManager = userInstance.getPreferencesManager();
final IUserLayoutManager userLayoutManager = preferencesManager.getUserLayoutManager();
final IUserLayoutNodeDescription node = userLayoutManager.getNode(folderNodeId);
if (node == null) {
return null;
}
return node.getType();
} | [
"protected",
"LayoutNodeType",
"getLayoutNodeType",
"(",
"HttpServletRequest",
"request",
",",
"String",
"folderNodeId",
")",
"{",
"final",
"IUserInstance",
"userInstance",
"=",
"this",
".",
"userInstanceManager",
".",
"getUserInstance",
"(",
"request",
")",
";",
"final",
"IUserPreferencesManager",
"preferencesManager",
"=",
"userInstance",
".",
"getPreferencesManager",
"(",
")",
";",
"final",
"IUserLayoutManager",
"userLayoutManager",
"=",
"preferencesManager",
".",
"getUserLayoutManager",
"(",
")",
";",
"final",
"IUserLayoutNodeDescription",
"node",
"=",
"userLayoutManager",
".",
"getNode",
"(",
"folderNodeId",
")",
";",
"if",
"(",
"node",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"node",
".",
"getType",
"(",
")",
";",
"}"
] | Verify the requested node exists in the user's layout. Also if the node exists see if it is a
portlet node and if it is return the {@link IPortletWindowId} of the corresponding portlet. | [
"Verify",
"the",
"requested",
"node",
"exists",
"in",
"the",
"user",
"s",
"layout",
".",
"Also",
"if",
"the",
"node",
"exists",
"see",
"if",
"it",
"is",
"a",
"portlet",
"node",
"and",
"if",
"it",
"is",
"return",
"the",
"{"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/url/PortalUrlProviderImpl.java#L247-L258 |
davidmoten/rxjava2-extras | src/main/java/com/github/davidmoten/rx2/Strings.java | Strings.toInputStream | public static InputStream toInputStream(Publisher<String> publisher, Charset charset) {
"""
Returns an {@link InputStream} that offers the concatenated String data
emitted by a subscription to the given publisher using the given character set.
@param publisher the source of the String data
@param charset the character set of the bytes to be read in the InputStream
@return offers the concatenated String data emitted by a subscription to
the given publisher using the given character set
"""
return FlowableStringInputStream.createInputStream(publisher, charset);
} | java | public static InputStream toInputStream(Publisher<String> publisher, Charset charset) {
return FlowableStringInputStream.createInputStream(publisher, charset);
} | [
"public",
"static",
"InputStream",
"toInputStream",
"(",
"Publisher",
"<",
"String",
">",
"publisher",
",",
"Charset",
"charset",
")",
"{",
"return",
"FlowableStringInputStream",
".",
"createInputStream",
"(",
"publisher",
",",
"charset",
")",
";",
"}"
] | Returns an {@link InputStream} that offers the concatenated String data
emitted by a subscription to the given publisher using the given character set.
@param publisher the source of the String data
@param charset the character set of the bytes to be read in the InputStream
@return offers the concatenated String data emitted by a subscription to
the given publisher using the given character set | [
"Returns",
"an",
"{",
"@link",
"InputStream",
"}",
"that",
"offers",
"the",
"concatenated",
"String",
"data",
"emitted",
"by",
"a",
"subscription",
"to",
"the",
"given",
"publisher",
"using",
"the",
"given",
"character",
"set",
"."
] | train | https://github.com/davidmoten/rxjava2-extras/blob/bf5ece3f97191f29a81957a6529bc3cfa4d7b328/src/main/java/com/github/davidmoten/rx2/Strings.java#L380-L382 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/file/FileHelper.java | FileHelper.readFile | public static InputStream readFile(String filename, ClassLoader classLoader) throws IOException {
"""
Read file according to the follow precedence:
- From directory specified by system property mdw.config.location
- From fully qualified file name if mdw.config.location is null
- From etc/ directory relative to java startup dir
- From META-INF/mdw using the designated class loader
"""
// first option: specified through system property
String configDir = System.getProperty(PropertyManager.MDW_CONFIG_LOCATION);
File file;
if (configDir == null)
file = new File(filename); // maybe fully-qualified file name
else if (configDir.endsWith("/"))
file = new File(configDir + filename);
else
file = new File(configDir + "/" + filename);
// next option: etc directory
if (!file.exists())
file = new File("etc/" + filename);
if (file.exists())
return new FileInputStream(file);
// not overridden so load from bundle classpath
String path = BUNDLE_CLASSPATH_BASE + "/" + filename;
return classLoader.getResourceAsStream(path);
} | java | public static InputStream readFile(String filename, ClassLoader classLoader) throws IOException {
// first option: specified through system property
String configDir = System.getProperty(PropertyManager.MDW_CONFIG_LOCATION);
File file;
if (configDir == null)
file = new File(filename); // maybe fully-qualified file name
else if (configDir.endsWith("/"))
file = new File(configDir + filename);
else
file = new File(configDir + "/" + filename);
// next option: etc directory
if (!file.exists())
file = new File("etc/" + filename);
if (file.exists())
return new FileInputStream(file);
// not overridden so load from bundle classpath
String path = BUNDLE_CLASSPATH_BASE + "/" + filename;
return classLoader.getResourceAsStream(path);
} | [
"public",
"static",
"InputStream",
"readFile",
"(",
"String",
"filename",
",",
"ClassLoader",
"classLoader",
")",
"throws",
"IOException",
"{",
"// first option: specified through system property",
"String",
"configDir",
"=",
"System",
".",
"getProperty",
"(",
"PropertyManager",
".",
"MDW_CONFIG_LOCATION",
")",
";",
"File",
"file",
";",
"if",
"(",
"configDir",
"==",
"null",
")",
"file",
"=",
"new",
"File",
"(",
"filename",
")",
";",
"// maybe fully-qualified file name",
"else",
"if",
"(",
"configDir",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"file",
"=",
"new",
"File",
"(",
"configDir",
"+",
"filename",
")",
";",
"else",
"file",
"=",
"new",
"File",
"(",
"configDir",
"+",
"\"/\"",
"+",
"filename",
")",
";",
"// next option: etc directory",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"file",
"=",
"new",
"File",
"(",
"\"etc/\"",
"+",
"filename",
")",
";",
"if",
"(",
"file",
".",
"exists",
"(",
")",
")",
"return",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"// not overridden so load from bundle classpath",
"String",
"path",
"=",
"BUNDLE_CLASSPATH_BASE",
"+",
"\"/\"",
"+",
"filename",
";",
"return",
"classLoader",
".",
"getResourceAsStream",
"(",
"path",
")",
";",
"}"
] | Read file according to the follow precedence:
- From directory specified by system property mdw.config.location
- From fully qualified file name if mdw.config.location is null
- From etc/ directory relative to java startup dir
- From META-INF/mdw using the designated class loader | [
"Read",
"file",
"according",
"to",
"the",
"follow",
"precedence",
":",
"-",
"From",
"directory",
"specified",
"by",
"system",
"property",
"mdw",
".",
"config",
".",
"location",
"-",
"From",
"fully",
"qualified",
"file",
"name",
"if",
"mdw",
".",
"config",
".",
"location",
"is",
"null",
"-",
"From",
"etc",
"/",
"directory",
"relative",
"to",
"java",
"startup",
"dir",
"-",
"From",
"META",
"-",
"INF",
"/",
"mdw",
"using",
"the",
"designated",
"class",
"loader"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/file/FileHelper.java#L372-L393 |
junit-team/junit4 | src/main/java/org/junit/rules/ErrorCollector.java | ErrorCollector.checkThrows | public void checkThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) {
"""
Adds a failure to the table if {@code runnable} does not throw an
exception of type {@code expectedThrowable} when executed.
Execution continues, but the test will fail at the end if the runnable
does not throw an exception, or if it throws a different exception.
@param expectedThrowable the expected type of the exception
@param runnable a function that is expected to throw an exception when executed
@since 4.13
"""
try {
assertThrows(expectedThrowable, runnable);
} catch (AssertionError e) {
addError(e);
}
} | java | public void checkThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) {
try {
assertThrows(expectedThrowable, runnable);
} catch (AssertionError e) {
addError(e);
}
} | [
"public",
"void",
"checkThrows",
"(",
"Class",
"<",
"?",
"extends",
"Throwable",
">",
"expectedThrowable",
",",
"ThrowingRunnable",
"runnable",
")",
"{",
"try",
"{",
"assertThrows",
"(",
"expectedThrowable",
",",
"runnable",
")",
";",
"}",
"catch",
"(",
"AssertionError",
"e",
")",
"{",
"addError",
"(",
"e",
")",
";",
"}",
"}"
] | Adds a failure to the table if {@code runnable} does not throw an
exception of type {@code expectedThrowable} when executed.
Execution continues, but the test will fail at the end if the runnable
does not throw an exception, or if it throws a different exception.
@param expectedThrowable the expected type of the exception
@param runnable a function that is expected to throw an exception when executed
@since 4.13 | [
"Adds",
"a",
"failure",
"to",
"the",
"table",
"if",
"{",
"@code",
"runnable",
"}",
"does",
"not",
"throw",
"an",
"exception",
"of",
"type",
"{",
"@code",
"expectedThrowable",
"}",
"when",
"executed",
".",
"Execution",
"continues",
"but",
"the",
"test",
"will",
"fail",
"at",
"the",
"end",
"if",
"the",
"runnable",
"does",
"not",
"throw",
"an",
"exception",
"or",
"if",
"it",
"throws",
"a",
"different",
"exception",
"."
] | train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/rules/ErrorCollector.java#L118-L124 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/AttachmentVersioningResourcesImpl.java | AttachmentVersioningResourcesImpl.attachNewVersion | private Attachment attachNewVersion (long sheetId, long attachmentId, InputStream inputStream, String contentType, long contentLength, String attachmentName)
throws SmartsheetException {
"""
Attach a new version of an attachment.
It mirrors to the following Smartsheet REST API method: POST /attachment/{id}/versions
@param sheetId the id of the sheet
@param attachmentId the id of the object
@param inputStream the {@link InputStream} of the file to attach
@param contentType the content type of the file
@param contentLength the size of the file in bytes.
@param attachmentName the name of the file.
@return the created attachment
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation
"""
return super.attachFile("sheets/"+ sheetId + "/attachments/"+ attachmentId +"/versions", inputStream, contentType, contentLength, attachmentName);
} | java | private Attachment attachNewVersion (long sheetId, long attachmentId, InputStream inputStream, String contentType, long contentLength, String attachmentName)
throws SmartsheetException {
return super.attachFile("sheets/"+ sheetId + "/attachments/"+ attachmentId +"/versions", inputStream, contentType, contentLength, attachmentName);
} | [
"private",
"Attachment",
"attachNewVersion",
"(",
"long",
"sheetId",
",",
"long",
"attachmentId",
",",
"InputStream",
"inputStream",
",",
"String",
"contentType",
",",
"long",
"contentLength",
",",
"String",
"attachmentName",
")",
"throws",
"SmartsheetException",
"{",
"return",
"super",
".",
"attachFile",
"(",
"\"sheets/\"",
"+",
"sheetId",
"+",
"\"/attachments/\"",
"+",
"attachmentId",
"+",
"\"/versions\"",
",",
"inputStream",
",",
"contentType",
",",
"contentLength",
",",
"attachmentName",
")",
";",
"}"
] | Attach a new version of an attachment.
It mirrors to the following Smartsheet REST API method: POST /attachment/{id}/versions
@param sheetId the id of the sheet
@param attachmentId the id of the object
@param inputStream the {@link InputStream} of the file to attach
@param contentType the content type of the file
@param contentLength the size of the file in bytes.
@param attachmentName the name of the file.
@return the created attachment
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | [
"Attach",
"a",
"new",
"version",
"of",
"an",
"attachment",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/AttachmentVersioningResourcesImpl.java#L139-L142 |
lucee/Lucee | core/src/main/java/lucee/transformer/util/SourceCode.java | SourceCode.forwardIfCurrent | public boolean forwardIfCurrent(String first, char second) {
"""
Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn
ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt.
@param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
@param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
@return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
"""
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = forwardIfCurrent(second);
if (!rtn) pos = start;
return rtn;
} | java | public boolean forwardIfCurrent(String first, char second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = forwardIfCurrent(second);
if (!rtn) pos = start;
return rtn;
} | [
"public",
"boolean",
"forwardIfCurrent",
"(",
"String",
"first",
",",
"char",
"second",
")",
"{",
"int",
"start",
"=",
"pos",
";",
"if",
"(",
"!",
"forwardIfCurrent",
"(",
"first",
")",
")",
"return",
"false",
";",
"removeSpace",
"(",
")",
";",
"boolean",
"rtn",
"=",
"forwardIfCurrent",
"(",
"second",
")",
";",
"if",
"(",
"!",
"rtn",
")",
"pos",
"=",
"start",
";",
"return",
"rtn",
";",
"}"
] | Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn
ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt.
@param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
@param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
@return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht. | [
"Gibt",
"zurueck",
"ob",
"first",
"den",
"folgenden",
"Zeichen",
"entspricht",
"gefolgt",
"von",
"Leerzeichen",
"und",
"second",
"wenn",
"ja",
"wird",
"der",
"Zeiger",
"um",
"die",
"Laenge",
"der",
"uebereinstimmung",
"nach",
"vorne",
"gestellt",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/util/SourceCode.java#L350-L357 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/SignOneSample.java | SignOneSample.getPvalue | public static double getPvalue(FlatDataCollection flatDataCollection, double median) {
"""
Calculates the p-value of null Hypothesis.
@param flatDataCollection
@param median
@return
"""
int n=flatDataCollection.size();
if(n<=0) {
throw new IllegalArgumentException("The provided collection can't be empty.");
}
int Tplus=0;
Iterator<Double> it = flatDataCollection.iteratorDouble();
while(it.hasNext()) {
double v = it.next();
if(Math.abs(v-median) < 0.0000001) {
continue; //don't count it at all
}
if(v>median) {
++Tplus;
}
}
double pvalue= scoreToPvalue(Tplus, n);
return pvalue;
} | java | public static double getPvalue(FlatDataCollection flatDataCollection, double median) {
int n=flatDataCollection.size();
if(n<=0) {
throw new IllegalArgumentException("The provided collection can't be empty.");
}
int Tplus=0;
Iterator<Double> it = flatDataCollection.iteratorDouble();
while(it.hasNext()) {
double v = it.next();
if(Math.abs(v-median) < 0.0000001) {
continue; //don't count it at all
}
if(v>median) {
++Tplus;
}
}
double pvalue= scoreToPvalue(Tplus, n);
return pvalue;
} | [
"public",
"static",
"double",
"getPvalue",
"(",
"FlatDataCollection",
"flatDataCollection",
",",
"double",
"median",
")",
"{",
"int",
"n",
"=",
"flatDataCollection",
".",
"size",
"(",
")",
";",
"if",
"(",
"n",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The provided collection can't be empty.\"",
")",
";",
"}",
"int",
"Tplus",
"=",
"0",
";",
"Iterator",
"<",
"Double",
">",
"it",
"=",
"flatDataCollection",
".",
"iteratorDouble",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"double",
"v",
"=",
"it",
".",
"next",
"(",
")",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"v",
"-",
"median",
")",
"<",
"0.0000001",
")",
"{",
"continue",
";",
"//don't count it at all",
"}",
"if",
"(",
"v",
">",
"median",
")",
"{",
"++",
"Tplus",
";",
"}",
"}",
"double",
"pvalue",
"=",
"scoreToPvalue",
"(",
"Tplus",
",",
"n",
")",
";",
"return",
"pvalue",
";",
"}"
] | Calculates the p-value of null Hypothesis.
@param flatDataCollection
@param median
@return | [
"Calculates",
"the",
"p",
"-",
"value",
"of",
"null",
"Hypothesis",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/SignOneSample.java#L37-L59 |
lamarios/sherdog-parser | src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java | ParserUtils.getDateFromStringToZoneId | static ZonedDateTime getDateFromStringToZoneId(String date, ZoneId zoneId, DateTimeFormatter formatter) throws DateTimeParseException {
"""
Converts a String to the given timezone.
@param date Date to format
@param zoneId Zone id to convert from sherdog's time
@param formatter Formatter for exotic date format
@return the converted zonedatetime
"""
try {
//noticed that date not parsed with non-US locale. For me this fix is helpful
LocalDate localDate = LocalDate.parse(date, formatter);
ZonedDateTime usDate = localDate.atStartOfDay(zoneId);
return usDate.withZoneSameInstant(zoneId);
} catch (Exception e) {
//In case the parsing fail, we try without time
try {
ZonedDateTime usDate = LocalDate.parse(date, formatter).atStartOfDay(ZoneId.of(Constants.SHERDOG_TIME_ZONE));
return usDate.withZoneSameInstant(zoneId);
} catch (DateTimeParseException e2) {
return null;
}
}
} | java | static ZonedDateTime getDateFromStringToZoneId(String date, ZoneId zoneId, DateTimeFormatter formatter) throws DateTimeParseException {
try {
//noticed that date not parsed with non-US locale. For me this fix is helpful
LocalDate localDate = LocalDate.parse(date, formatter);
ZonedDateTime usDate = localDate.atStartOfDay(zoneId);
return usDate.withZoneSameInstant(zoneId);
} catch (Exception e) {
//In case the parsing fail, we try without time
try {
ZonedDateTime usDate = LocalDate.parse(date, formatter).atStartOfDay(ZoneId.of(Constants.SHERDOG_TIME_ZONE));
return usDate.withZoneSameInstant(zoneId);
} catch (DateTimeParseException e2) {
return null;
}
}
} | [
"static",
"ZonedDateTime",
"getDateFromStringToZoneId",
"(",
"String",
"date",
",",
"ZoneId",
"zoneId",
",",
"DateTimeFormatter",
"formatter",
")",
"throws",
"DateTimeParseException",
"{",
"try",
"{",
"//noticed that date not parsed with non-US locale. For me this fix is helpful",
"LocalDate",
"localDate",
"=",
"LocalDate",
".",
"parse",
"(",
"date",
",",
"formatter",
")",
";",
"ZonedDateTime",
"usDate",
"=",
"localDate",
".",
"atStartOfDay",
"(",
"zoneId",
")",
";",
"return",
"usDate",
".",
"withZoneSameInstant",
"(",
"zoneId",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"//In case the parsing fail, we try without time",
"try",
"{",
"ZonedDateTime",
"usDate",
"=",
"LocalDate",
".",
"parse",
"(",
"date",
",",
"formatter",
")",
".",
"atStartOfDay",
"(",
"ZoneId",
".",
"of",
"(",
"Constants",
".",
"SHERDOG_TIME_ZONE",
")",
")",
";",
"return",
"usDate",
".",
"withZoneSameInstant",
"(",
"zoneId",
")",
";",
"}",
"catch",
"(",
"DateTimeParseException",
"e2",
")",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] | Converts a String to the given timezone.
@param date Date to format
@param zoneId Zone id to convert from sherdog's time
@param formatter Formatter for exotic date format
@return the converted zonedatetime | [
"Converts",
"a",
"String",
"to",
"the",
"given",
"timezone",
"."
] | train | https://github.com/lamarios/sherdog-parser/blob/7cdb36280317caeaaa54db77c04dc4b4e1db053e/src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java#L91-L106 |
PistoiaHELM/HELM2NotationToolkit | src/main/java/org/helm/notation2/wsadapter/WSAdapterUtils.java | WSAdapterUtils.putResource | protected static CloseableHttpResponse putResource(String json, String fullURL) throws ClientProtocolException,
IOException, URISyntaxException {
"""
Calls a PUT routine with given JSON on given resource URL.
@param json the input JSON
@param fullURL the resource URL
@return Response
@throws ClientProtocolException if an error exists in the HTTP protocol
@throws IOException IO Error
@throws URISyntaxException url is not valid
"""
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// There is no need to provide user credentials
// HttpClient will attempt to access current user security context
// through Windows platform specific methods via JNI.
HttpPut httpput = new HttpPut(new URIBuilder(fullURL).build());
httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
httpput.setEntity(new StringEntity(json, "UTF-8"));
LOG.debug("Executing request " + httpput.getRequestLine());
return httpclient.execute(httpput);
}
} | java | protected static CloseableHttpResponse putResource(String json, String fullURL) throws ClientProtocolException,
IOException, URISyntaxException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// There is no need to provide user credentials
// HttpClient will attempt to access current user security context
// through Windows platform specific methods via JNI.
HttpPut httpput = new HttpPut(new URIBuilder(fullURL).build());
httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
httpput.setEntity(new StringEntity(json, "UTF-8"));
LOG.debug("Executing request " + httpput.getRequestLine());
return httpclient.execute(httpput);
}
} | [
"protected",
"static",
"CloseableHttpResponse",
"putResource",
"(",
"String",
"json",
",",
"String",
"fullURL",
")",
"throws",
"ClientProtocolException",
",",
"IOException",
",",
"URISyntaxException",
"{",
"try",
"(",
"CloseableHttpClient",
"httpclient",
"=",
"HttpClients",
".",
"createDefault",
"(",
")",
")",
"{",
"// There is no need to provide user credentials\r",
"// HttpClient will attempt to access current user security context\r",
"// through Windows platform specific methods via JNI.\r",
"HttpPut",
"httpput",
"=",
"new",
"HttpPut",
"(",
"new",
"URIBuilder",
"(",
"fullURL",
")",
".",
"build",
"(",
")",
")",
";",
"httpput",
".",
"setHeader",
"(",
"\"Content-Type\"",
",",
"\"application/json;charset=UTF-8\"",
")",
";",
"httpput",
".",
"setEntity",
"(",
"new",
"StringEntity",
"(",
"json",
",",
"\"UTF-8\"",
")",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Executing request \"",
"+",
"httpput",
".",
"getRequestLine",
"(",
")",
")",
";",
"return",
"httpclient",
".",
"execute",
"(",
"httpput",
")",
";",
"}",
"}"
] | Calls a PUT routine with given JSON on given resource URL.
@param json the input JSON
@param fullURL the resource URL
@return Response
@throws ClientProtocolException if an error exists in the HTTP protocol
@throws IOException IO Error
@throws URISyntaxException url is not valid | [
"Calls",
"a",
"PUT",
"routine",
"with",
"given",
"JSON",
"on",
"given",
"resource",
"URL",
"."
] | train | https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/wsadapter/WSAdapterUtils.java#L46-L60 |
js-lib-com/commons | src/main/java/js/util/Files.java | Files.replaceExtension | public static String replaceExtension(String path, String newExtension) throws IllegalArgumentException {
"""
Replace extension on given file path and return resulting path. Is legal for new extension parameter to start with
dot extension separator, but is not mandatory.
@param path file path to replace extension,
@param newExtension newly extension, with optional dot separator prefix.
@return newly created file path.
@throws IllegalArgumentException if path or new extension parameter is null.
"""
Params.notNull(path, "Path");
Params.notNull(newExtension, "New extension");
if(newExtension.charAt(0) == '.') {
newExtension = newExtension.substring(1);
}
int extensionDotIndex = path.lastIndexOf('.') + 1;
if(extensionDotIndex == 0) {
extensionDotIndex = path.length();
}
StringBuilder sb = new StringBuilder(path.length());
sb.append(path.substring(0, extensionDotIndex));
sb.append(newExtension);
return sb.toString();
} | java | public static String replaceExtension(String path, String newExtension) throws IllegalArgumentException
{
Params.notNull(path, "Path");
Params.notNull(newExtension, "New extension");
if(newExtension.charAt(0) == '.') {
newExtension = newExtension.substring(1);
}
int extensionDotIndex = path.lastIndexOf('.') + 1;
if(extensionDotIndex == 0) {
extensionDotIndex = path.length();
}
StringBuilder sb = new StringBuilder(path.length());
sb.append(path.substring(0, extensionDotIndex));
sb.append(newExtension);
return sb.toString();
} | [
"public",
"static",
"String",
"replaceExtension",
"(",
"String",
"path",
",",
"String",
"newExtension",
")",
"throws",
"IllegalArgumentException",
"{",
"Params",
".",
"notNull",
"(",
"path",
",",
"\"Path\"",
")",
";",
"Params",
".",
"notNull",
"(",
"newExtension",
",",
"\"New extension\"",
")",
";",
"if",
"(",
"newExtension",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
")",
"{",
"newExtension",
"=",
"newExtension",
".",
"substring",
"(",
"1",
")",
";",
"}",
"int",
"extensionDotIndex",
"=",
"path",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
"+",
"1",
";",
"if",
"(",
"extensionDotIndex",
"==",
"0",
")",
"{",
"extensionDotIndex",
"=",
"path",
".",
"length",
"(",
")",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"path",
".",
"length",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"path",
".",
"substring",
"(",
"0",
",",
"extensionDotIndex",
")",
")",
";",
"sb",
".",
"append",
"(",
"newExtension",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Replace extension on given file path and return resulting path. Is legal for new extension parameter to start with
dot extension separator, but is not mandatory.
@param path file path to replace extension,
@param newExtension newly extension, with optional dot separator prefix.
@return newly created file path.
@throws IllegalArgumentException if path or new extension parameter is null. | [
"Replace",
"extension",
"on",
"given",
"file",
"path",
"and",
"return",
"resulting",
"path",
".",
"Is",
"legal",
"for",
"new",
"extension",
"parameter",
"to",
"start",
"with",
"dot",
"extension",
"separator",
"but",
"is",
"not",
"mandatory",
"."
] | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Files.java#L649-L666 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java | ConfigurationReader.parseCacheConfig | private void parseCacheConfig(final Node node, final ConfigSettings config) {
"""
Parses the cache parameter section.
@param node
Reference to the current used xml node
@param config
Reference to the ConfigSettings
"""
String name;
Long lValue;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_LIMIT_TASK_SIZE_REVISIONS)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_TASK_SIZE_REVISIONS, lValue);
}
else if (name.equals(KEY_LIMIT_TASK_SIZE_DIFFS)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_TASK_SIZE_DIFFS, lValue);
}
else if (name.equals(KEY_LIMIT_SQLSERVER_MAX_ALLOWED_PACKET)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_SQLSERVER_MAX_ALLOWED_PACKET,
lValue);
}
}
} | java | private void parseCacheConfig(final Node node, final ConfigSettings config)
{
String name;
Long lValue;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_LIMIT_TASK_SIZE_REVISIONS)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_TASK_SIZE_REVISIONS, lValue);
}
else if (name.equals(KEY_LIMIT_TASK_SIZE_DIFFS)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_TASK_SIZE_DIFFS, lValue);
}
else if (name.equals(KEY_LIMIT_SQLSERVER_MAX_ALLOWED_PACKET)) {
lValue = Long.parseLong(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.LIMIT_SQLSERVER_MAX_ALLOWED_PACKET,
lValue);
}
}
} | [
"private",
"void",
"parseCacheConfig",
"(",
"final",
"Node",
"node",
",",
"final",
"ConfigSettings",
"config",
")",
"{",
"String",
"name",
";",
"Long",
"lValue",
";",
"Node",
"nnode",
";",
"NodeList",
"list",
"=",
"node",
".",
"getChildNodes",
"(",
")",
";",
"int",
"length",
"=",
"list",
".",
"getLength",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"nnode",
"=",
"list",
".",
"item",
"(",
"i",
")",
";",
"name",
"=",
"nnode",
".",
"getNodeName",
"(",
")",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"name",
".",
"equals",
"(",
"KEY_LIMIT_TASK_SIZE_REVISIONS",
")",
")",
"{",
"lValue",
"=",
"Long",
".",
"parseLong",
"(",
"nnode",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
".",
"getNodeValue",
"(",
")",
")",
";",
"config",
".",
"setConfigParameter",
"(",
"ConfigurationKeys",
".",
"LIMIT_TASK_SIZE_REVISIONS",
",",
"lValue",
")",
";",
"}",
"else",
"if",
"(",
"name",
".",
"equals",
"(",
"KEY_LIMIT_TASK_SIZE_DIFFS",
")",
")",
"{",
"lValue",
"=",
"Long",
".",
"parseLong",
"(",
"nnode",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
".",
"getNodeValue",
"(",
")",
")",
";",
"config",
".",
"setConfigParameter",
"(",
"ConfigurationKeys",
".",
"LIMIT_TASK_SIZE_DIFFS",
",",
"lValue",
")",
";",
"}",
"else",
"if",
"(",
"name",
".",
"equals",
"(",
"KEY_LIMIT_SQLSERVER_MAX_ALLOWED_PACKET",
")",
")",
"{",
"lValue",
"=",
"Long",
".",
"parseLong",
"(",
"nnode",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
".",
"getNodeValue",
"(",
")",
")",
";",
"config",
".",
"setConfigParameter",
"(",
"ConfigurationKeys",
".",
"LIMIT_SQLSERVER_MAX_ALLOWED_PACKET",
",",
"lValue",
")",
";",
"}",
"}",
"}"
] | Parses the cache parameter section.
@param node
Reference to the current used xml node
@param config
Reference to the ConfigSettings | [
"Parses",
"the",
"cache",
"parameter",
"section",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java#L635-L674 |
auth0/auth0-java | src/main/java/com/auth0/json/mgmt/guardian/TwilioFactorProvider.java | TwilioFactorProvider.setMessagingServiceSID | @Deprecated
@JsonProperty("messaging_service_sid")
public void setMessagingServiceSID(String messagingServiceSID) throws IllegalArgumentException {
"""
Setter for the Twilio Messaging Service SID.
@param messagingServiceSID the messaging service SID.
@throws IllegalArgumentException when both `from` and `messagingServiceSID` are set
@deprecated use the constructor instead
"""
if (from != null) {
throw new IllegalArgumentException("You must specify either `from` or `messagingServiceSID`, but not both");
}
this.messagingServiceSID = messagingServiceSID;
} | java | @Deprecated
@JsonProperty("messaging_service_sid")
public void setMessagingServiceSID(String messagingServiceSID) throws IllegalArgumentException {
if (from != null) {
throw new IllegalArgumentException("You must specify either `from` or `messagingServiceSID`, but not both");
}
this.messagingServiceSID = messagingServiceSID;
} | [
"@",
"Deprecated",
"@",
"JsonProperty",
"(",
"\"messaging_service_sid\"",
")",
"public",
"void",
"setMessagingServiceSID",
"(",
"String",
"messagingServiceSID",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"from",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"You must specify either `from` or `messagingServiceSID`, but not both\"",
")",
";",
"}",
"this",
".",
"messagingServiceSID",
"=",
"messagingServiceSID",
";",
"}"
] | Setter for the Twilio Messaging Service SID.
@param messagingServiceSID the messaging service SID.
@throws IllegalArgumentException when both `from` and `messagingServiceSID` are set
@deprecated use the constructor instead | [
"Setter",
"for",
"the",
"Twilio",
"Messaging",
"Service",
"SID",
"."
] | train | https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/json/mgmt/guardian/TwilioFactorProvider.java#L101-L108 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/DateTimeField.java | DateTimeField.setValue | public int setValue(double value, boolean bDisplayOption, int iMoveMode) {
"""
Set the Value of this field as a double.
@param value The value of this field.
@param iDisplayOption If true, display the new field.
@param iMoveMove The move mode.
@return An error code (NORMAL_RETURN for success).
""" // Set this field's value
java.util.Date dateTemp = new java.util.Date((long)value);
int iErrorCode = this.setData(dateTemp, bDisplayOption, iMoveMode);
return iErrorCode;
} | java | public int setValue(double value, boolean bDisplayOption, int iMoveMode)
{ // Set this field's value
java.util.Date dateTemp = new java.util.Date((long)value);
int iErrorCode = this.setData(dateTemp, bDisplayOption, iMoveMode);
return iErrorCode;
} | [
"public",
"int",
"setValue",
"(",
"double",
"value",
",",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"{",
"// Set this field's value",
"java",
".",
"util",
".",
"Date",
"dateTemp",
"=",
"new",
"java",
".",
"util",
".",
"Date",
"(",
"(",
"long",
")",
"value",
")",
";",
"int",
"iErrorCode",
"=",
"this",
".",
"setData",
"(",
"dateTemp",
",",
"bDisplayOption",
",",
"iMoveMode",
")",
";",
"return",
"iErrorCode",
";",
"}"
] | Set the Value of this field as a double.
@param value The value of this field.
@param iDisplayOption If true, display the new field.
@param iMoveMove The move mode.
@return An error code (NORMAL_RETURN for success). | [
"Set",
"the",
"Value",
"of",
"this",
"field",
"as",
"a",
"double",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/DateTimeField.java#L251-L256 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java | NodeIndexer.addLongValue | protected void addLongValue(Document doc, String fieldName, Object internalValue) {
"""
Adds the long value to the document as the named field. The long
value is converted to an indexable string value using the {@link LongField}
class.
@param doc The document to which to add the field
@param fieldName The name of the field to add
@param internalValue The value for the field to add to the document.
"""
long longVal = ((Long)internalValue).longValue();
doc.add(createFieldWithoutNorms(fieldName, LongField.longToString(longVal), PropertyType.LONG));
} | java | protected void addLongValue(Document doc, String fieldName, Object internalValue)
{
long longVal = ((Long)internalValue).longValue();
doc.add(createFieldWithoutNorms(fieldName, LongField.longToString(longVal), PropertyType.LONG));
} | [
"protected",
"void",
"addLongValue",
"(",
"Document",
"doc",
",",
"String",
"fieldName",
",",
"Object",
"internalValue",
")",
"{",
"long",
"longVal",
"=",
"(",
"(",
"Long",
")",
"internalValue",
")",
".",
"longValue",
"(",
")",
";",
"doc",
".",
"add",
"(",
"createFieldWithoutNorms",
"(",
"fieldName",
",",
"LongField",
".",
"longToString",
"(",
"longVal",
")",
",",
"PropertyType",
".",
"LONG",
")",
")",
";",
"}"
] | Adds the long value to the document as the named field. The long
value is converted to an indexable string value using the {@link LongField}
class.
@param doc The document to which to add the field
@param fieldName The name of the field to add
@param internalValue The value for the field to add to the document. | [
"Adds",
"the",
"long",
"value",
"to",
"the",
"document",
"as",
"the",
"named",
"field",
".",
"The",
"long",
"value",
"is",
"converted",
"to",
"an",
"indexable",
"string",
"value",
"using",
"the",
"{",
"@link",
"LongField",
"}",
"class",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java#L775-L779 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/BaasDocument.java | BaasDocument.doCount | private static RequestToken doCount(String collection, BaasQuery.Criteria filter, int flags, final BaasHandler<Long> handler) {
"""
Asynchronously retrieves the number of documents readable to the user that match the <code>filter</code>
in <code>collection</code>
@param collection the collection to doCount not <code>null</code>
@param filter a {@link BaasQuery.Criteria} to apply to the request. May be <code>null</code>
@param handler a callback to be invoked with the result of the request
@return a {@link com.baasbox.android.RequestToken} to handle the asynchronous request
"""
BaasBox box = BaasBox.getDefaultChecked();
filter = filter==null?BaasQuery.builder().count(true).criteria()
:filter.buildUpon().count(true).criteria();
if (collection == null) throw new IllegalArgumentException("collection cannot be null");
Count count = new Count(box, collection, filter, flags, handler);
return box.submitAsync(count);
} | java | private static RequestToken doCount(String collection, BaasQuery.Criteria filter, int flags, final BaasHandler<Long> handler) {
BaasBox box = BaasBox.getDefaultChecked();
filter = filter==null?BaasQuery.builder().count(true).criteria()
:filter.buildUpon().count(true).criteria();
if (collection == null) throw new IllegalArgumentException("collection cannot be null");
Count count = new Count(box, collection, filter, flags, handler);
return box.submitAsync(count);
} | [
"private",
"static",
"RequestToken",
"doCount",
"(",
"String",
"collection",
",",
"BaasQuery",
".",
"Criteria",
"filter",
",",
"int",
"flags",
",",
"final",
"BaasHandler",
"<",
"Long",
">",
"handler",
")",
"{",
"BaasBox",
"box",
"=",
"BaasBox",
".",
"getDefaultChecked",
"(",
")",
";",
"filter",
"=",
"filter",
"==",
"null",
"?",
"BaasQuery",
".",
"builder",
"(",
")",
".",
"count",
"(",
"true",
")",
".",
"criteria",
"(",
")",
":",
"filter",
".",
"buildUpon",
"(",
")",
".",
"count",
"(",
"true",
")",
".",
"criteria",
"(",
")",
";",
"if",
"(",
"collection",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"collection cannot be null\"",
")",
";",
"Count",
"count",
"=",
"new",
"Count",
"(",
"box",
",",
"collection",
",",
"filter",
",",
"flags",
",",
"handler",
")",
";",
"return",
"box",
".",
"submitAsync",
"(",
"count",
")",
";",
"}"
] | Asynchronously retrieves the number of documents readable to the user that match the <code>filter</code>
in <code>collection</code>
@param collection the collection to doCount not <code>null</code>
@param filter a {@link BaasQuery.Criteria} to apply to the request. May be <code>null</code>
@param handler a callback to be invoked with the result of the request
@return a {@link com.baasbox.android.RequestToken} to handle the asynchronous request | [
"Asynchronously",
"retrieves",
"the",
"number",
"of",
"documents",
"readable",
"to",
"the",
"user",
"that",
"match",
"the",
"<code",
">",
"filter<",
"/",
"code",
">",
"in",
"<code",
">",
"collection<",
"/",
"code",
">"
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L328-L337 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java | TaskOperations.deleteTask | public void deleteTask(String jobId, String taskId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
"""
Deletes the specified task.
@param jobId
The ID of the job containing the task.
@param taskId
The ID of the task.
@param additionalBehaviors
A collection of {@link BatchClientBehavior} instances that are
applied to the Batch service request.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service.
"""
TaskDeleteOptions options = new TaskDeleteOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().tasks().delete(jobId, taskId, options);
} | java | public void deleteTask(String jobId, String taskId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
TaskDeleteOptions options = new TaskDeleteOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().tasks().delete(jobId, taskId, options);
} | [
"public",
"void",
"deleteTask",
"(",
"String",
"jobId",
",",
"String",
"taskId",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"TaskDeleteOptions",
"options",
"=",
"new",
"TaskDeleteOptions",
"(",
")",
";",
"BehaviorManager",
"bhMgr",
"=",
"new",
"BehaviorManager",
"(",
"this",
".",
"customBehaviors",
"(",
")",
",",
"additionalBehaviors",
")",
";",
"bhMgr",
".",
"applyRequestBehaviors",
"(",
"options",
")",
";",
"this",
".",
"parentBatchClient",
".",
"protocolLayer",
"(",
")",
".",
"tasks",
"(",
")",
".",
"delete",
"(",
"jobId",
",",
"taskId",
",",
"options",
")",
";",
"}"
] | Deletes the specified task.
@param jobId
The ID of the job containing the task.
@param taskId
The ID of the task.
@param additionalBehaviors
A collection of {@link BatchClientBehavior} instances that are
applied to the Batch service request.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Deletes",
"the",
"specified",
"task",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java#L573-L580 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/annotation/AnnotationHeaderParser.java | AnnotationHeaderParser.parseAnnotation | public AnnotationHeader parseAnnotation(String resourceLocation,
File annotationFile) throws IOException,
BELDataMissingPropertyException,
BELDataConversionException, BELDataInvalidPropertyException {
"""
Parses the annotation {@link File} into a {@link AnnotationHeader} object.
@param annotationFile {@link File}, the annotation file, which cannot be
null, must exist, and must be readable
@return {@link annotationHeader}, the parsed annotation header
@throws IOException Thrown if an IO error occurred reading the
<tt>annotationFile</tt>
@throws BELDataHeaderParseException Thrown if a parsing error occurred
when processing the <tt>annotationFile</tt>
@throws BELDataConversionException
@throws BELDataMissingPropertyException
@throws BELDataInvalidPropertyException
@throws InvalidArgument Thrown if the <tt>annotationFile</tt> is null,
does not exist, or cannot be read
"""
if (annotationFile == null) {
throw new InvalidArgument("annotationFile", annotationFile);
}
if (!annotationFile.exists()) {
throw new InvalidArgument("annotationFile does not exist");
}
if (!annotationFile.canRead()) {
throw new InvalidArgument("annotationFile cannot be read");
}
Map<String, Properties> blockProperties = parse(annotationFile);
AnnotationBlock annotationBlock =
AnnotationBlock.create(resourceLocation,
blockProperties.get(AnnotationBlock.BLOCK_NAME));
AuthorBlock authorblock = AuthorBlock.create(resourceLocation,
blockProperties.get(AuthorBlock.BLOCK_NAME));
CitationBlock citationBlock = CitationBlock.create(resourceLocation,
blockProperties.get(CitationBlock.BLOCK_NAME));
ProcessingBlock processingBlock = ProcessingBlock.create(
resourceLocation,
blockProperties.get(ProcessingBlock.BLOCK_NAME));
return new AnnotationHeader(annotationBlock, authorblock,
citationBlock,
processingBlock);
} | java | public AnnotationHeader parseAnnotation(String resourceLocation,
File annotationFile) throws IOException,
BELDataMissingPropertyException,
BELDataConversionException, BELDataInvalidPropertyException {
if (annotationFile == null) {
throw new InvalidArgument("annotationFile", annotationFile);
}
if (!annotationFile.exists()) {
throw new InvalidArgument("annotationFile does not exist");
}
if (!annotationFile.canRead()) {
throw new InvalidArgument("annotationFile cannot be read");
}
Map<String, Properties> blockProperties = parse(annotationFile);
AnnotationBlock annotationBlock =
AnnotationBlock.create(resourceLocation,
blockProperties.get(AnnotationBlock.BLOCK_NAME));
AuthorBlock authorblock = AuthorBlock.create(resourceLocation,
blockProperties.get(AuthorBlock.BLOCK_NAME));
CitationBlock citationBlock = CitationBlock.create(resourceLocation,
blockProperties.get(CitationBlock.BLOCK_NAME));
ProcessingBlock processingBlock = ProcessingBlock.create(
resourceLocation,
blockProperties.get(ProcessingBlock.BLOCK_NAME));
return new AnnotationHeader(annotationBlock, authorblock,
citationBlock,
processingBlock);
} | [
"public",
"AnnotationHeader",
"parseAnnotation",
"(",
"String",
"resourceLocation",
",",
"File",
"annotationFile",
")",
"throws",
"IOException",
",",
"BELDataMissingPropertyException",
",",
"BELDataConversionException",
",",
"BELDataInvalidPropertyException",
"{",
"if",
"(",
"annotationFile",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"annotationFile\"",
",",
"annotationFile",
")",
";",
"}",
"if",
"(",
"!",
"annotationFile",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"annotationFile does not exist\"",
")",
";",
"}",
"if",
"(",
"!",
"annotationFile",
".",
"canRead",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"annotationFile cannot be read\"",
")",
";",
"}",
"Map",
"<",
"String",
",",
"Properties",
">",
"blockProperties",
"=",
"parse",
"(",
"annotationFile",
")",
";",
"AnnotationBlock",
"annotationBlock",
"=",
"AnnotationBlock",
".",
"create",
"(",
"resourceLocation",
",",
"blockProperties",
".",
"get",
"(",
"AnnotationBlock",
".",
"BLOCK_NAME",
")",
")",
";",
"AuthorBlock",
"authorblock",
"=",
"AuthorBlock",
".",
"create",
"(",
"resourceLocation",
",",
"blockProperties",
".",
"get",
"(",
"AuthorBlock",
".",
"BLOCK_NAME",
")",
")",
";",
"CitationBlock",
"citationBlock",
"=",
"CitationBlock",
".",
"create",
"(",
"resourceLocation",
",",
"blockProperties",
".",
"get",
"(",
"CitationBlock",
".",
"BLOCK_NAME",
")",
")",
";",
"ProcessingBlock",
"processingBlock",
"=",
"ProcessingBlock",
".",
"create",
"(",
"resourceLocation",
",",
"blockProperties",
".",
"get",
"(",
"ProcessingBlock",
".",
"BLOCK_NAME",
")",
")",
";",
"return",
"new",
"AnnotationHeader",
"(",
"annotationBlock",
",",
"authorblock",
",",
"citationBlock",
",",
"processingBlock",
")",
";",
"}"
] | Parses the annotation {@link File} into a {@link AnnotationHeader} object.
@param annotationFile {@link File}, the annotation file, which cannot be
null, must exist, and must be readable
@return {@link annotationHeader}, the parsed annotation header
@throws IOException Thrown if an IO error occurred reading the
<tt>annotationFile</tt>
@throws BELDataHeaderParseException Thrown if a parsing error occurred
when processing the <tt>annotationFile</tt>
@throws BELDataConversionException
@throws BELDataMissingPropertyException
@throws BELDataInvalidPropertyException
@throws InvalidArgument Thrown if the <tt>annotationFile</tt> is null,
does not exist, or cannot be read | [
"Parses",
"the",
"annotation",
"{",
"@link",
"File",
"}",
"into",
"a",
"{",
"@link",
"AnnotationHeader",
"}",
"object",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/annotation/AnnotationHeaderParser.java#L70-L105 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java | JacksonDBCollection.findOneById | public T findOneById(K id, T fields) throws MongoException {
"""
Find an object by the given id
@param id The id
@return The object
@throws MongoException If an error occurred
"""
return findOneById(id, convertToBasicDbObject(fields));
} | java | public T findOneById(K id, T fields) throws MongoException {
return findOneById(id, convertToBasicDbObject(fields));
} | [
"public",
"T",
"findOneById",
"(",
"K",
"id",
",",
"T",
"fields",
")",
"throws",
"MongoException",
"{",
"return",
"findOneById",
"(",
"id",
",",
"convertToBasicDbObject",
"(",
"fields",
")",
")",
";",
"}"
] | Find an object by the given id
@param id The id
@return The object
@throws MongoException If an error occurred | [
"Find",
"an",
"object",
"by",
"the",
"given",
"id"
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java#L869-L871 |
StanKocken/EfficientAdapter | efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java | EfficientViewHolder.onBindView | public void onBindView(@Nullable T item, int position) {
"""
Method called when we need to update the view hold by this class.
@param item the object subject of this update
"""
mObject = item;
mLastBindPosition = position;
updateView(mCacheView.getView().getContext(), mObject);
} | java | public void onBindView(@Nullable T item, int position) {
mObject = item;
mLastBindPosition = position;
updateView(mCacheView.getView().getContext(), mObject);
} | [
"public",
"void",
"onBindView",
"(",
"@",
"Nullable",
"T",
"item",
",",
"int",
"position",
")",
"{",
"mObject",
"=",
"item",
";",
"mLastBindPosition",
"=",
"position",
";",
"updateView",
"(",
"mCacheView",
".",
"getView",
"(",
")",
".",
"getContext",
"(",
")",
",",
"mObject",
")",
";",
"}"
] | Method called when we need to update the view hold by this class.
@param item the object subject of this update | [
"Method",
"called",
"when",
"we",
"need",
"to",
"update",
"the",
"view",
"hold",
"by",
"this",
"class",
"."
] | train | https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java#L66-L70 |
krummas/DrizzleJDBC | src/main/java/org/drizzle/jdbc/internal/common/query/parameters/BlobStreamingParameter.java | BlobStreamingParameter.writeTo | public final int writeTo(final OutputStream os,int offset, int maxWriteSize) throws IOException {
"""
Writes the parameter to an outputstream.
@param os the outputstream to write to
@throws java.io.IOException if we cannot write to the stream
"""
int bytesToWrite = Math.min(blobReference.getBytes().length - offset, maxWriteSize);
os.write(blobReference.getBytes(), offset, blobReference.getBytes().length);
return bytesToWrite;
} | java | public final int writeTo(final OutputStream os,int offset, int maxWriteSize) throws IOException {
int bytesToWrite = Math.min(blobReference.getBytes().length - offset, maxWriteSize);
os.write(blobReference.getBytes(), offset, blobReference.getBytes().length);
return bytesToWrite;
} | [
"public",
"final",
"int",
"writeTo",
"(",
"final",
"OutputStream",
"os",
",",
"int",
"offset",
",",
"int",
"maxWriteSize",
")",
"throws",
"IOException",
"{",
"int",
"bytesToWrite",
"=",
"Math",
".",
"min",
"(",
"blobReference",
".",
"getBytes",
"(",
")",
".",
"length",
"-",
"offset",
",",
"maxWriteSize",
")",
";",
"os",
".",
"write",
"(",
"blobReference",
".",
"getBytes",
"(",
")",
",",
"offset",
",",
"blobReference",
".",
"getBytes",
"(",
")",
".",
"length",
")",
";",
"return",
"bytesToWrite",
";",
"}"
] | Writes the parameter to an outputstream.
@param os the outputstream to write to
@throws java.io.IOException if we cannot write to the stream | [
"Writes",
"the",
"parameter",
"to",
"an",
"outputstream",
"."
] | train | https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/internal/common/query/parameters/BlobStreamingParameter.java#L62-L66 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.updateDate | public void updateDate(int columnIndex, Date x) throws SQLException {
"""
<!-- start generic documentation -->
Updates the designated column with a <code>java.sql.Date</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet)
"""
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | java | public void updateDate(int columnIndex, Date x) throws SQLException {
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | [
"public",
"void",
"updateDate",
"(",
"int",
"columnIndex",
",",
"Date",
"x",
")",
"throws",
"SQLException",
"{",
"startUpdate",
"(",
"columnIndex",
")",
";",
"preparedStatement",
".",
"setParameter",
"(",
"columnIndex",
",",
"x",
")",
";",
"}"
] | <!-- start generic documentation -->
Updates the designated column with a <code>java.sql.Date</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Updates",
"the",
"designated",
"column",
"with",
"a",
"<code",
">",
"java",
".",
"sql",
".",
"Date<",
"/",
"code",
">",
"value",
".",
"The",
"updater",
"methods",
"are",
"used",
"to",
"update",
"column",
"values",
"in",
"the",
"current",
"row",
"or",
"the",
"insert",
"row",
".",
"The",
"updater",
"methods",
"do",
"not",
"update",
"the",
"underlying",
"database",
";",
"instead",
"the",
"<code",
">",
"updateRow<",
"/",
"code",
">",
"or",
"<code",
">",
"insertRow<",
"/",
"code",
">",
"methods",
"are",
"called",
"to",
"update",
"the",
"database",
".",
"<!",
"--",
"end",
"generic",
"documentation",
"--",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L2981-L2984 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java | EmbeddedNeo4jAssociationQueries.findRelationship | @Override
public Relationship findRelationship(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) {
"""
Returns the relationship corresponding to the {@link AssociationKey} and {@link RowKey}.
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param associationKey represents the association
@param rowKey represents a row in an association
@return the corresponding relationship
"""
Object[] queryValues = relationshipValues( associationKey, rowKey );
Result result = executionEngine.execute( findRelationshipQuery, params( queryValues ) );
return singleResult( result );
} | java | @Override
public Relationship findRelationship(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) {
Object[] queryValues = relationshipValues( associationKey, rowKey );
Result result = executionEngine.execute( findRelationshipQuery, params( queryValues ) );
return singleResult( result );
} | [
"@",
"Override",
"public",
"Relationship",
"findRelationship",
"(",
"GraphDatabaseService",
"executionEngine",
",",
"AssociationKey",
"associationKey",
",",
"RowKey",
"rowKey",
")",
"{",
"Object",
"[",
"]",
"queryValues",
"=",
"relationshipValues",
"(",
"associationKey",
",",
"rowKey",
")",
";",
"Result",
"result",
"=",
"executionEngine",
".",
"execute",
"(",
"findRelationshipQuery",
",",
"params",
"(",
"queryValues",
")",
")",
";",
"return",
"singleResult",
"(",
"result",
")",
";",
"}"
] | Returns the relationship corresponding to the {@link AssociationKey} and {@link RowKey}.
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param associationKey represents the association
@param rowKey represents a row in an association
@return the corresponding relationship | [
"Returns",
"the",
"relationship",
"corresponding",
"to",
"the",
"{",
"@link",
"AssociationKey",
"}",
"and",
"{",
"@link",
"RowKey",
"}",
"."
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java#L64-L69 |
kiegroup/drools | drools-model/drools-canonical-model/src/main/java/org/drools/model/bitmask/OpenBitSet.java | OpenBitSet.andNotCount | public static long andNotCount(OpenBitSet a, OpenBitSet b) {
"""
Returns the popcount or cardinality of "a and not b"
or "intersection(a, not(b))".
Neither set is modified.
"""
long tot = BitUtil.pop_andnot( a.bits, b.bits, 0, Math.min( a.wlen, b.wlen ) );
if (a.wlen > b.wlen) {
tot += BitUtil.pop_array( a.bits, b.wlen, a.wlen - b.wlen );
}
return tot;
} | java | public static long andNotCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_andnot( a.bits, b.bits, 0, Math.min( a.wlen, b.wlen ) );
if (a.wlen > b.wlen) {
tot += BitUtil.pop_array( a.bits, b.wlen, a.wlen - b.wlen );
}
return tot;
} | [
"public",
"static",
"long",
"andNotCount",
"(",
"OpenBitSet",
"a",
",",
"OpenBitSet",
"b",
")",
"{",
"long",
"tot",
"=",
"BitUtil",
".",
"pop_andnot",
"(",
"a",
".",
"bits",
",",
"b",
".",
"bits",
",",
"0",
",",
"Math",
".",
"min",
"(",
"a",
".",
"wlen",
",",
"b",
".",
"wlen",
")",
")",
";",
"if",
"(",
"a",
".",
"wlen",
">",
"b",
".",
"wlen",
")",
"{",
"tot",
"+=",
"BitUtil",
".",
"pop_array",
"(",
"a",
".",
"bits",
",",
"b",
".",
"wlen",
",",
"a",
".",
"wlen",
"-",
"b",
".",
"wlen",
")",
";",
"}",
"return",
"tot",
";",
"}"
] | Returns the popcount or cardinality of "a and not b"
or "intersection(a, not(b))".
Neither set is modified. | [
"Returns",
"the",
"popcount",
"or",
"cardinality",
"of",
"a",
"and",
"not",
"b",
"or",
"intersection",
"(",
"a",
"not",
"(",
"b",
"))",
".",
"Neither",
"set",
"is",
"modified",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-model/drools-canonical-model/src/main/java/org/drools/model/bitmask/OpenBitSet.java#L588-L594 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWorldInfo | public void getWorldInfo(int[] ids, Callback<List<World>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on World API go <a href="https://wiki.guildwars2.com/wiki/API:2/worlds">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of world id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see World world info
"""
isParamValid(new ParamChecker(ids));
gw2API.getWorldsInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getWorldInfo(int[] ids, Callback<List<World>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getWorldsInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getWorldInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"World",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getWorldsInfo",
"(",
"processIds",
"(",
"ids",
")",
",",
"GuildWars2",
".",
"lang",
".",
"getValue",
"(",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on World API go <a href="https://wiki.guildwars2.com/wiki/API:2/worlds">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of world id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see World world info | [
"For",
"more",
"info",
"on",
"World",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"worlds",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2553-L2556 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/cql/Cql.java | Cql.toStaticFilter | public static Filter toStaticFilter(String cqlExpression, Class clazz) throws ParseException {
"""
Creates an executable object filter based on the given CQL expression.
This filter is only applicable for the given class.
@param cqlExpression The CQL expression.
@param clazz The type for which to construct the filter.
@return An object filter that behaves according to the given CQL expression.
@throws java.text.ParseException When parsing fails for any reason (parser, lexer, IO)
"""
try {
Parser p = new Parser( new Lexer( new PushbackReader(new StringReader(cqlExpression), 1024)));
// Parse the input.
Start tree = p.parse();
// Build the filter expression
FilterExpressionBuilder builder = new FilterExpressionBuilder();
tree.apply(builder);
// Wrap in a filter
return new Filter(builder.getExp());
}
catch(ParserException e) {
ParseException parseException = new ParseException(e.getMessage(), e.getToken().getPos());
parseException.initCause(e);
throw parseException;
}
catch (LexerException e) {
ParseException parseException = new ParseException(e.getMessage(), 0);
parseException.initCause(e);
throw parseException;
}
catch (IOException e) {
ParseException parseException = new ParseException(e.getMessage(), 0);
parseException.initCause(e);
throw parseException;
}
} | java | public static Filter toStaticFilter(String cqlExpression, Class clazz) throws ParseException {
try {
Parser p = new Parser( new Lexer( new PushbackReader(new StringReader(cqlExpression), 1024)));
// Parse the input.
Start tree = p.parse();
// Build the filter expression
FilterExpressionBuilder builder = new FilterExpressionBuilder();
tree.apply(builder);
// Wrap in a filter
return new Filter(builder.getExp());
}
catch(ParserException e) {
ParseException parseException = new ParseException(e.getMessage(), e.getToken().getPos());
parseException.initCause(e);
throw parseException;
}
catch (LexerException e) {
ParseException parseException = new ParseException(e.getMessage(), 0);
parseException.initCause(e);
throw parseException;
}
catch (IOException e) {
ParseException parseException = new ParseException(e.getMessage(), 0);
parseException.initCause(e);
throw parseException;
}
} | [
"public",
"static",
"Filter",
"toStaticFilter",
"(",
"String",
"cqlExpression",
",",
"Class",
"clazz",
")",
"throws",
"ParseException",
"{",
"try",
"{",
"Parser",
"p",
"=",
"new",
"Parser",
"(",
"new",
"Lexer",
"(",
"new",
"PushbackReader",
"(",
"new",
"StringReader",
"(",
"cqlExpression",
")",
",",
"1024",
")",
")",
")",
";",
"// Parse the input.",
"Start",
"tree",
"=",
"p",
".",
"parse",
"(",
")",
";",
"// Build the filter expression",
"FilterExpressionBuilder",
"builder",
"=",
"new",
"FilterExpressionBuilder",
"(",
")",
";",
"tree",
".",
"apply",
"(",
"builder",
")",
";",
"// Wrap in a filter",
"return",
"new",
"Filter",
"(",
"builder",
".",
"getExp",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ParserException",
"e",
")",
"{",
"ParseException",
"parseException",
"=",
"new",
"ParseException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
".",
"getToken",
"(",
")",
".",
"getPos",
"(",
")",
")",
";",
"parseException",
".",
"initCause",
"(",
"e",
")",
";",
"throw",
"parseException",
";",
"}",
"catch",
"(",
"LexerException",
"e",
")",
"{",
"ParseException",
"parseException",
"=",
"new",
"ParseException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"0",
")",
";",
"parseException",
".",
"initCause",
"(",
"e",
")",
";",
"throw",
"parseException",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"ParseException",
"parseException",
"=",
"new",
"ParseException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"0",
")",
";",
"parseException",
".",
"initCause",
"(",
"e",
")",
";",
"throw",
"parseException",
";",
"}",
"}"
] | Creates an executable object filter based on the given CQL expression.
This filter is only applicable for the given class.
@param cqlExpression The CQL expression.
@param clazz The type for which to construct the filter.
@return An object filter that behaves according to the given CQL expression.
@throws java.text.ParseException When parsing fails for any reason (parser, lexer, IO) | [
"Creates",
"an",
"executable",
"object",
"filter",
"based",
"on",
"the",
"given",
"CQL",
"expression",
".",
"This",
"filter",
"is",
"only",
"applicable",
"for",
"the",
"given",
"class",
"."
] | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/cql/Cql.java#L72-L104 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.stripNewLineChar | public static String stripNewLineChar(String pString) {
"""
This method strips out all new line characters from the passed String.
@param pString A String value.
@return A clean String.
@see StringTokenizer
"""
String tmpFidValue = pString;
StringTokenizer aTokenizer = new StringTokenizer(pString, "\n");
if (aTokenizer.countTokens() > 1) {
StringBuffer nameBuffer = new StringBuffer();
while (aTokenizer.hasMoreTokens()) {
nameBuffer.append(aTokenizer.nextToken());
}
tmpFidValue = nameBuffer.toString();
}
return tmpFidValue;
} | java | public static String stripNewLineChar(String pString) {
String tmpFidValue = pString;
StringTokenizer aTokenizer = new StringTokenizer(pString, "\n");
if (aTokenizer.countTokens() > 1) {
StringBuffer nameBuffer = new StringBuffer();
while (aTokenizer.hasMoreTokens()) {
nameBuffer.append(aTokenizer.nextToken());
}
tmpFidValue = nameBuffer.toString();
}
return tmpFidValue;
} | [
"public",
"static",
"String",
"stripNewLineChar",
"(",
"String",
"pString",
")",
"{",
"String",
"tmpFidValue",
"=",
"pString",
";",
"StringTokenizer",
"aTokenizer",
"=",
"new",
"StringTokenizer",
"(",
"pString",
",",
"\"\\n\"",
")",
";",
"if",
"(",
"aTokenizer",
".",
"countTokens",
"(",
")",
">",
"1",
")",
"{",
"StringBuffer",
"nameBuffer",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"while",
"(",
"aTokenizer",
".",
"hasMoreTokens",
"(",
")",
")",
"{",
"nameBuffer",
".",
"append",
"(",
"aTokenizer",
".",
"nextToken",
"(",
")",
")",
";",
"}",
"tmpFidValue",
"=",
"nameBuffer",
".",
"toString",
"(",
")",
";",
"}",
"return",
"tmpFidValue",
";",
"}"
] | This method strips out all new line characters from the passed String.
@param pString A String value.
@return A clean String.
@see StringTokenizer | [
"This",
"method",
"strips",
"out",
"all",
"new",
"line",
"characters",
"from",
"the",
"passed",
"String",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L943-L954 |
code4everything/util | src/main/java/com/zhazhapan/util/NetUtils.java | NetUtils.getLocationByIp | public static String getLocationByIp(String ip) throws IOException, XPathExpressionException,
ParserConfigurationException {
"""
获取ip归属地
@param ip ip地址
@return 归属地
@throws IOException 异常
@throws XPathExpressionException 异常
@throws ParserConfigurationException 异常
"""
return evaluate(ValueConsts.IP_REGION_XPATH, getHtmlFromUrl("http://ip.chinaz.com/" + ip));
} | java | public static String getLocationByIp(String ip) throws IOException, XPathExpressionException,
ParserConfigurationException {
return evaluate(ValueConsts.IP_REGION_XPATH, getHtmlFromUrl("http://ip.chinaz.com/" + ip));
} | [
"public",
"static",
"String",
"getLocationByIp",
"(",
"String",
"ip",
")",
"throws",
"IOException",
",",
"XPathExpressionException",
",",
"ParserConfigurationException",
"{",
"return",
"evaluate",
"(",
"ValueConsts",
".",
"IP_REGION_XPATH",
",",
"getHtmlFromUrl",
"(",
"\"http://ip.chinaz.com/\"",
"+",
"ip",
")",
")",
";",
"}"
] | 获取ip归属地
@param ip ip地址
@return 归属地
@throws IOException 异常
@throws XPathExpressionException 异常
@throws ParserConfigurationException 异常 | [
"获取ip归属地"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/NetUtils.java#L680-L683 |
pedrovgs/Lynx | lynx/src/main/java/com/github/pedrovgs/lynx/LynxView.java | LynxView.showTraces | @Override public void showTraces(List<Trace> traces, int removedTraces) {
"""
Given a {@code List<Trace>} updates the ListView adapter with this information and keeps the
scroll position if needed.
"""
if (lastScrollPosition == 0) {
lastScrollPosition = lv_traces.getFirstVisiblePosition();
}
adapter.clear();
adapter.addAll(traces);
adapter.notifyDataSetChanged();
updateScrollPosition(removedTraces);
} | java | @Override public void showTraces(List<Trace> traces, int removedTraces) {
if (lastScrollPosition == 0) {
lastScrollPosition = lv_traces.getFirstVisiblePosition();
}
adapter.clear();
adapter.addAll(traces);
adapter.notifyDataSetChanged();
updateScrollPosition(removedTraces);
} | [
"@",
"Override",
"public",
"void",
"showTraces",
"(",
"List",
"<",
"Trace",
">",
"traces",
",",
"int",
"removedTraces",
")",
"{",
"if",
"(",
"lastScrollPosition",
"==",
"0",
")",
"{",
"lastScrollPosition",
"=",
"lv_traces",
".",
"getFirstVisiblePosition",
"(",
")",
";",
"}",
"adapter",
".",
"clear",
"(",
")",
";",
"adapter",
".",
"addAll",
"(",
"traces",
")",
";",
"adapter",
".",
"notifyDataSetChanged",
"(",
")",
";",
"updateScrollPosition",
"(",
"removedTraces",
")",
";",
"}"
] | Given a {@code List<Trace>} updates the ListView adapter with this information and keeps the
scroll position if needed. | [
"Given",
"a",
"{"
] | train | https://github.com/pedrovgs/Lynx/blob/6097ab18b76c1ebdd0819c10e5d09ec19ea5bf4d/lynx/src/main/java/com/github/pedrovgs/lynx/LynxView.java#L166-L174 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/utils/BsfUtils.java | BsfUtils.getInitParam | public static String getInitParam(String param, FacesContext context) {
"""
Shortcut for getting context parameters using an already obtained FacesContext.
@param param context parameter name
@return value of context parameter, may be null or empty
"""
return context.getExternalContext().getInitParameter(param);
} | java | public static String getInitParam(String param, FacesContext context) {
return context.getExternalContext().getInitParameter(param);
} | [
"public",
"static",
"String",
"getInitParam",
"(",
"String",
"param",
",",
"FacesContext",
"context",
")",
"{",
"return",
"context",
".",
"getExternalContext",
"(",
")",
".",
"getInitParameter",
"(",
"param",
")",
";",
"}"
] | Shortcut for getting context parameters using an already obtained FacesContext.
@param param context parameter name
@return value of context parameter, may be null or empty | [
"Shortcut",
"for",
"getting",
"context",
"parameters",
"using",
"an",
"already",
"obtained",
"FacesContext",
"."
] | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/utils/BsfUtils.java#L331-L333 |
optimaize/anythingworks | client/rest/src/main/java/com/optimaize/anythingworks/client/rest/http/StringUtil.java | StringUtil.containsIgnoreCase | public static boolean containsIgnoreCase(String[] array, String value) {
"""
Check if the given array contains the given value (with case-insensitive comparison).
@param array The array
@param value The value to search
@return true if the array contains the value
"""
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
}
return false;
} | java | public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
}
return false;
} | [
"public",
"static",
"boolean",
"containsIgnoreCase",
"(",
"String",
"[",
"]",
"array",
",",
"String",
"value",
")",
"{",
"for",
"(",
"String",
"str",
":",
"array",
")",
"{",
"if",
"(",
"value",
"==",
"null",
"&&",
"str",
"==",
"null",
")",
"return",
"true",
";",
"if",
"(",
"value",
"!=",
"null",
"&&",
"value",
".",
"equalsIgnoreCase",
"(",
"str",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Check if the given array contains the given value (with case-insensitive comparison).
@param array The array
@param value The value to search
@return true if the array contains the value | [
"Check",
"if",
"the",
"given",
"array",
"contains",
"the",
"given",
"value",
"(",
"with",
"case",
"-",
"insensitive",
"comparison",
")",
"."
] | train | https://github.com/optimaize/anythingworks/blob/23e5f1c63cd56d935afaac4ad033c7996b32a1f2/client/rest/src/main/java/com/optimaize/anythingworks/client/rest/http/StringUtil.java#L12-L18 |
Azure/azure-sdk-for-java | postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/ServerSecurityAlertPoliciesInner.java | ServerSecurityAlertPoliciesInner.createOrUpdateAsync | public Observable<ServerSecurityAlertPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ServerSecurityAlertPolicyInner parameters) {
"""
Creates or updates a threat detection policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param parameters The server security alert policy.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerSecurityAlertPolicyInner>, ServerSecurityAlertPolicyInner>() {
@Override
public ServerSecurityAlertPolicyInner call(ServiceResponse<ServerSecurityAlertPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<ServerSecurityAlertPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ServerSecurityAlertPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerSecurityAlertPolicyInner>, ServerSecurityAlertPolicyInner>() {
@Override
public ServerSecurityAlertPolicyInner call(ServiceResponse<ServerSecurityAlertPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ServerSecurityAlertPolicyInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"ServerSecurityAlertPolicyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ServerSecurityAlertPolicyInner",
">",
",",
"ServerSecurityAlertPolicyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ServerSecurityAlertPolicyInner",
"call",
"(",
"ServiceResponse",
"<",
"ServerSecurityAlertPolicyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates or updates a threat detection policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param parameters The server security alert policy.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"a",
"threat",
"detection",
"policy",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/ServerSecurityAlertPoliciesInner.java#L196-L203 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/DataTracker.java | DataTracker.replaceReaders | private void replaceReaders(Collection<SSTableReader> oldSSTables, Collection<SSTableReader> newSSTables, boolean notify) {
"""
A special kind of replacement for SSTableReaders that were cloned with a new index summary sampling level (see
SSTableReader.cloneWithNewSummarySamplingLevel and CASSANDRA-5519). This does not mark the old reader
as compacted.
@param oldSSTables replaced readers
@param newSSTables replacement readers
"""
View currentView, newView;
do
{
currentView = view.get();
newView = currentView.replace(oldSSTables, newSSTables);
}
while (!view.compareAndSet(currentView, newView));
if (!oldSSTables.isEmpty() && notify)
notifySSTablesChanged(oldSSTables, newSSTables, OperationType.UNKNOWN);
for (SSTableReader sstable : newSSTables)
sstable.setTrackedBy(this);
Refs.release(Refs.selfRefs(oldSSTables));
} | java | private void replaceReaders(Collection<SSTableReader> oldSSTables, Collection<SSTableReader> newSSTables, boolean notify)
{
View currentView, newView;
do
{
currentView = view.get();
newView = currentView.replace(oldSSTables, newSSTables);
}
while (!view.compareAndSet(currentView, newView));
if (!oldSSTables.isEmpty() && notify)
notifySSTablesChanged(oldSSTables, newSSTables, OperationType.UNKNOWN);
for (SSTableReader sstable : newSSTables)
sstable.setTrackedBy(this);
Refs.release(Refs.selfRefs(oldSSTables));
} | [
"private",
"void",
"replaceReaders",
"(",
"Collection",
"<",
"SSTableReader",
">",
"oldSSTables",
",",
"Collection",
"<",
"SSTableReader",
">",
"newSSTables",
",",
"boolean",
"notify",
")",
"{",
"View",
"currentView",
",",
"newView",
";",
"do",
"{",
"currentView",
"=",
"view",
".",
"get",
"(",
")",
";",
"newView",
"=",
"currentView",
".",
"replace",
"(",
"oldSSTables",
",",
"newSSTables",
")",
";",
"}",
"while",
"(",
"!",
"view",
".",
"compareAndSet",
"(",
"currentView",
",",
"newView",
")",
")",
";",
"if",
"(",
"!",
"oldSSTables",
".",
"isEmpty",
"(",
")",
"&&",
"notify",
")",
"notifySSTablesChanged",
"(",
"oldSSTables",
",",
"newSSTables",
",",
"OperationType",
".",
"UNKNOWN",
")",
";",
"for",
"(",
"SSTableReader",
"sstable",
":",
"newSSTables",
")",
"sstable",
".",
"setTrackedBy",
"(",
"this",
")",
";",
"Refs",
".",
"release",
"(",
"Refs",
".",
"selfRefs",
"(",
"oldSSTables",
")",
")",
";",
"}"
] | A special kind of replacement for SSTableReaders that were cloned with a new index summary sampling level (see
SSTableReader.cloneWithNewSummarySamplingLevel and CASSANDRA-5519). This does not mark the old reader
as compacted.
@param oldSSTables replaced readers
@param newSSTables replacement readers | [
"A",
"special",
"kind",
"of",
"replacement",
"for",
"SSTableReaders",
"that",
"were",
"cloned",
"with",
"a",
"new",
"index",
"summary",
"sampling",
"level",
"(",
"see",
"SSTableReader",
".",
"cloneWithNewSummarySamplingLevel",
"and",
"CASSANDRA",
"-",
"5519",
")",
".",
"This",
"does",
"not",
"mark",
"the",
"old",
"reader",
"as",
"compacted",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/DataTracker.java#L397-L414 |
VoltDB/voltdb | src/frontend/org/voltdb/planner/SubPlanAssembler.java | SubPlanAssembler.filterPostPredicateForPartialIndex | private void filterPostPredicateForPartialIndex(AccessPath path, List<AbstractExpression> exprToRemove) {
"""
Partial index optimization: Remove query expressions that exactly match the index WHERE expression(s)
from the access path.
@param path - Partial Index access path
@param exprToRemove - expressions to remove
"""
path.otherExprs.removeAll(exprToRemove);
// Keep the eliminated expressions for cost estimating purpose
path.eliminatedPostExprs.addAll(exprToRemove);
} | java | private void filterPostPredicateForPartialIndex(AccessPath path, List<AbstractExpression> exprToRemove) {
path.otherExprs.removeAll(exprToRemove);
// Keep the eliminated expressions for cost estimating purpose
path.eliminatedPostExprs.addAll(exprToRemove);
} | [
"private",
"void",
"filterPostPredicateForPartialIndex",
"(",
"AccessPath",
"path",
",",
"List",
"<",
"AbstractExpression",
">",
"exprToRemove",
")",
"{",
"path",
".",
"otherExprs",
".",
"removeAll",
"(",
"exprToRemove",
")",
";",
"// Keep the eliminated expressions for cost estimating purpose",
"path",
".",
"eliminatedPostExprs",
".",
"addAll",
"(",
"exprToRemove",
")",
";",
"}"
] | Partial index optimization: Remove query expressions that exactly match the index WHERE expression(s)
from the access path.
@param path - Partial Index access path
@param exprToRemove - expressions to remove | [
"Partial",
"index",
"optimization",
":",
"Remove",
"query",
"expressions",
"that",
"exactly",
"match",
"the",
"index",
"WHERE",
"expression",
"(",
"s",
")",
"from",
"the",
"access",
"path",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/SubPlanAssembler.java#L2309-L2313 |
LearnLib/automatalib | commons/util/src/main/java/net/automatalib/commons/util/comparison/CmpUtil.java | CmpUtil.canonicalCompare | public static <U extends Comparable<? super U>> int canonicalCompare(List<? extends U> o1, List<? extends U> o2) {
"""
Compares two {@link List}s of {@link Comparable} elements with respect to canonical ordering.
<p>
In canonical ordering, a sequence {@code o1} is less than a sequence {@code o2} if {@code o1} is shorter than
{@code o2}, or if they have the same length and {@code o1} is lexicographically smaller than {@code o2}.
@param o1
the first list
@param o2
the second list
@return the result of the comparison
"""
int siz1 = o1.size(), siz2 = o2.size();
if (siz1 != siz2) {
return siz1 - siz2;
}
return lexCompare(o1, o2);
} | java | public static <U extends Comparable<? super U>> int canonicalCompare(List<? extends U> o1, List<? extends U> o2) {
int siz1 = o1.size(), siz2 = o2.size();
if (siz1 != siz2) {
return siz1 - siz2;
}
return lexCompare(o1, o2);
} | [
"public",
"static",
"<",
"U",
"extends",
"Comparable",
"<",
"?",
"super",
"U",
">",
">",
"int",
"canonicalCompare",
"(",
"List",
"<",
"?",
"extends",
"U",
">",
"o1",
",",
"List",
"<",
"?",
"extends",
"U",
">",
"o2",
")",
"{",
"int",
"siz1",
"=",
"o1",
".",
"size",
"(",
")",
",",
"siz2",
"=",
"o2",
".",
"size",
"(",
")",
";",
"if",
"(",
"siz1",
"!=",
"siz2",
")",
"{",
"return",
"siz1",
"-",
"siz2",
";",
"}",
"return",
"lexCompare",
"(",
"o1",
",",
"o2",
")",
";",
"}"
] | Compares two {@link List}s of {@link Comparable} elements with respect to canonical ordering.
<p>
In canonical ordering, a sequence {@code o1} is less than a sequence {@code o2} if {@code o1} is shorter than
{@code o2}, or if they have the same length and {@code o1} is lexicographically smaller than {@code o2}.
@param o1
the first list
@param o2
the second list
@return the result of the comparison | [
"Compares",
"two",
"{",
"@link",
"List",
"}",
"s",
"of",
"{",
"@link",
"Comparable",
"}",
"elements",
"with",
"respect",
"to",
"canonical",
"ordering",
".",
"<p",
">",
"In",
"canonical",
"ordering",
"a",
"sequence",
"{",
"@code",
"o1",
"}",
"is",
"less",
"than",
"a",
"sequence",
"{",
"@code",
"o2",
"}",
"if",
"{",
"@code",
"o1",
"}",
"is",
"shorter",
"than",
"{",
"@code",
"o2",
"}",
"or",
"if",
"they",
"have",
"the",
"same",
"length",
"and",
"{",
"@code",
"o1",
"}",
"is",
"lexicographically",
"smaller",
"than",
"{",
"@code",
"o2",
"}",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/commons/util/src/main/java/net/automatalib/commons/util/comparison/CmpUtil.java#L80-L87 |
jaxio/celerio | celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java | IOUtil.stringToFile | public void stringToFile(String content, String filename) throws IOException {
"""
Save a string to a file.
@param content the string to be written to file
@param filename the full or relative path to the file.
"""
stringToOutputStream(content, new FileOutputStream(filename));
} | java | public void stringToFile(String content, String filename) throws IOException {
stringToOutputStream(content, new FileOutputStream(filename));
} | [
"public",
"void",
"stringToFile",
"(",
"String",
"content",
",",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"stringToOutputStream",
"(",
"content",
",",
"new",
"FileOutputStream",
"(",
"filename",
")",
")",
";",
"}"
] | Save a string to a file.
@param content the string to be written to file
@param filename the full or relative path to the file. | [
"Save",
"a",
"string",
"to",
"a",
"file",
"."
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java#L73-L75 |
alibaba/java-dns-cache-manipulator | library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java | DnsCacheManipulator.setDnsCache | public static void setDnsCache(long expireMillis, String host, String... ips) {
"""
Set a dns cache entry.
@param expireMillis expire time in milliseconds.
@param host host
@param ips ips
@throws DnsCacheManipulatorException Operation fail
"""
try {
InetAddressCacheUtil.setInetAddressCache(host, ips, System.currentTimeMillis() + expireMillis);
} catch (Exception e) {
final String message = String.format("Fail to setDnsCache for host %s ip %s expireMillis %s, cause: %s",
host, Arrays.toString(ips), expireMillis, e.toString());
throw new DnsCacheManipulatorException(message, e);
}
} | java | public static void setDnsCache(long expireMillis, String host, String... ips) {
try {
InetAddressCacheUtil.setInetAddressCache(host, ips, System.currentTimeMillis() + expireMillis);
} catch (Exception e) {
final String message = String.format("Fail to setDnsCache for host %s ip %s expireMillis %s, cause: %s",
host, Arrays.toString(ips), expireMillis, e.toString());
throw new DnsCacheManipulatorException(message, e);
}
} | [
"public",
"static",
"void",
"setDnsCache",
"(",
"long",
"expireMillis",
",",
"String",
"host",
",",
"String",
"...",
"ips",
")",
"{",
"try",
"{",
"InetAddressCacheUtil",
".",
"setInetAddressCache",
"(",
"host",
",",
"ips",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"expireMillis",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"final",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"Fail to setDnsCache for host %s ip %s expireMillis %s, cause: %s\"",
",",
"host",
",",
"Arrays",
".",
"toString",
"(",
"ips",
")",
",",
"expireMillis",
",",
"e",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"DnsCacheManipulatorException",
"(",
"message",
",",
"e",
")",
";",
"}",
"}"
] | Set a dns cache entry.
@param expireMillis expire time in milliseconds.
@param host host
@param ips ips
@throws DnsCacheManipulatorException Operation fail | [
"Set",
"a",
"dns",
"cache",
"entry",
"."
] | train | https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java#L53-L61 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java | StreamGraph.addVirtualSelectNode | public void addVirtualSelectNode(Integer originalId, Integer virtualId, List<String> selectedNames) {
"""
Adds a new virtual node that is used to connect a downstream vertex to only the outputs
with the selected names.
<p>When adding an edge from the virtual node to a downstream node the connection will be made
to the original node, only with the selected names given here.
@param originalId ID of the node that should be connected to.
@param virtualId ID of the virtual node.
@param selectedNames The selected names.
"""
if (virtualSelectNodes.containsKey(virtualId)) {
throw new IllegalStateException("Already has virtual select node with id " + virtualId);
}
virtualSelectNodes.put(virtualId,
new Tuple2<Integer, List<String>>(originalId, selectedNames));
} | java | public void addVirtualSelectNode(Integer originalId, Integer virtualId, List<String> selectedNames) {
if (virtualSelectNodes.containsKey(virtualId)) {
throw new IllegalStateException("Already has virtual select node with id " + virtualId);
}
virtualSelectNodes.put(virtualId,
new Tuple2<Integer, List<String>>(originalId, selectedNames));
} | [
"public",
"void",
"addVirtualSelectNode",
"(",
"Integer",
"originalId",
",",
"Integer",
"virtualId",
",",
"List",
"<",
"String",
">",
"selectedNames",
")",
"{",
"if",
"(",
"virtualSelectNodes",
".",
"containsKey",
"(",
"virtualId",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Already has virtual select node with id \"",
"+",
"virtualId",
")",
";",
"}",
"virtualSelectNodes",
".",
"put",
"(",
"virtualId",
",",
"new",
"Tuple2",
"<",
"Integer",
",",
"List",
"<",
"String",
">",
">",
"(",
"originalId",
",",
"selectedNames",
")",
")",
";",
"}"
] | Adds a new virtual node that is used to connect a downstream vertex to only the outputs
with the selected names.
<p>When adding an edge from the virtual node to a downstream node the connection will be made
to the original node, only with the selected names given here.
@param originalId ID of the node that should be connected to.
@param virtualId ID of the virtual node.
@param selectedNames The selected names. | [
"Adds",
"a",
"new",
"virtual",
"node",
"that",
"is",
"used",
"to",
"connect",
"a",
"downstream",
"vertex",
"to",
"only",
"the",
"outputs",
"with",
"the",
"selected",
"names",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java#L290-L298 |
cdk/cdk | base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/RGroupQuery.java | RGroupQuery.getBondPosition | private int getBondPosition(IBond bond, IAtomContainer container) {
"""
Helper method, used to help construct a configuration.
@param bond
@param container
@return the array position of the bond in the container
"""
for (int i = 0; i < container.getBondCount(); i++) {
if (bond.equals(container.getBond(i))) {
return i;
}
}
return -1;
} | java | private int getBondPosition(IBond bond, IAtomContainer container) {
for (int i = 0; i < container.getBondCount(); i++) {
if (bond.equals(container.getBond(i))) {
return i;
}
}
return -1;
} | [
"private",
"int",
"getBondPosition",
"(",
"IBond",
"bond",
",",
"IAtomContainer",
"container",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"container",
".",
"getBondCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"bond",
".",
"equals",
"(",
"container",
".",
"getBond",
"(",
"i",
")",
")",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Helper method, used to help construct a configuration.
@param bond
@param container
@return the array position of the bond in the container | [
"Helper",
"method",
"used",
"to",
"help",
"construct",
"a",
"configuration",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/RGroupQuery.java#L509-L516 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java | ClassUtility.getMethodByName | public static Method getMethodByName(final Class<?> cls, final String action) throws NoSuchMethodException {
"""
Return the method that exactly match the action name. The name must be unique into the class.
@param cls the class which contain the searched method
@param action the name of the method to find
@return the method
@throws NoSuchMethodException if no method was method
"""
for (final Method m : cls.getMethods()) {
if (m.getName().equals(action)) {
return m;
}
}
throw new NoSuchMethodException(action);
} | java | public static Method getMethodByName(final Class<?> cls, final String action) throws NoSuchMethodException {
for (final Method m : cls.getMethods()) {
if (m.getName().equals(action)) {
return m;
}
}
throw new NoSuchMethodException(action);
} | [
"public",
"static",
"Method",
"getMethodByName",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"String",
"action",
")",
"throws",
"NoSuchMethodException",
"{",
"for",
"(",
"final",
"Method",
"m",
":",
"cls",
".",
"getMethods",
"(",
")",
")",
"{",
"if",
"(",
"m",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"action",
")",
")",
"{",
"return",
"m",
";",
"}",
"}",
"throw",
"new",
"NoSuchMethodException",
"(",
"action",
")",
";",
"}"
] | Return the method that exactly match the action name. The name must be unique into the class.
@param cls the class which contain the searched method
@param action the name of the method to find
@return the method
@throws NoSuchMethodException if no method was method | [
"Return",
"the",
"method",
"that",
"exactly",
"match",
"the",
"action",
"name",
".",
"The",
"name",
"must",
"be",
"unique",
"into",
"the",
"class",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java#L296-L303 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceUtilHelper.java | PersistenceUtilHelper.getMethod | private static Method getMethod(Class<?> clazz, String methodName) {
"""
Returns the method with the specified name or <code>null</code> if it
does not exist.
@param clazz
The class to check.
@param methodName
The method name.
@return Returns the method with the specified name or <code>null</code>
if it does not exist.
"""
try
{
char string[] = methodName.toCharArray();
string[0] = Character.toUpperCase(string[0]);
methodName = new String(string);
try
{
return clazz.getDeclaredMethod("get" + methodName);
}
catch (NoSuchMethodException e)
{
return clazz.getDeclaredMethod("is" + methodName);
}
}
catch (NoSuchMethodException e)
{
return null;
}
} | java | private static Method getMethod(Class<?> clazz, String methodName)
{
try
{
char string[] = methodName.toCharArray();
string[0] = Character.toUpperCase(string[0]);
methodName = new String(string);
try
{
return clazz.getDeclaredMethod("get" + methodName);
}
catch (NoSuchMethodException e)
{
return clazz.getDeclaredMethod("is" + methodName);
}
}
catch (NoSuchMethodException e)
{
return null;
}
} | [
"private",
"static",
"Method",
"getMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
")",
"{",
"try",
"{",
"char",
"string",
"[",
"]",
"=",
"methodName",
".",
"toCharArray",
"(",
")",
";",
"string",
"[",
"0",
"]",
"=",
"Character",
".",
"toUpperCase",
"(",
"string",
"[",
"0",
"]",
")",
";",
"methodName",
"=",
"new",
"String",
"(",
"string",
")",
";",
"try",
"{",
"return",
"clazz",
".",
"getDeclaredMethod",
"(",
"\"get\"",
"+",
"methodName",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"return",
"clazz",
".",
"getDeclaredMethod",
"(",
"\"is\"",
"+",
"methodName",
")",
";",
"}",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Returns the method with the specified name or <code>null</code> if it
does not exist.
@param clazz
The class to check.
@param methodName
The method name.
@return Returns the method with the specified name or <code>null</code>
if it does not exist. | [
"Returns",
"the",
"method",
"with",
"the",
"specified",
"name",
"or",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceUtilHelper.java#L145-L165 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java | AtlasTypeDefGraphStoreV1.updateVertexProperty | private void updateVertexProperty(AtlasVertex vertex, String propertyName, String newValue) {
"""
/*
update the given vertex property, if the new value is not-blank
"""
if (StringUtils.isNotBlank(newValue)) {
String currValue = vertex.getProperty(propertyName, String.class);
if (!StringUtils.equals(currValue, newValue)) {
vertex.setProperty(propertyName, newValue);
}
}
} | java | private void updateVertexProperty(AtlasVertex vertex, String propertyName, String newValue) {
if (StringUtils.isNotBlank(newValue)) {
String currValue = vertex.getProperty(propertyName, String.class);
if (!StringUtils.equals(currValue, newValue)) {
vertex.setProperty(propertyName, newValue);
}
}
} | [
"private",
"void",
"updateVertexProperty",
"(",
"AtlasVertex",
"vertex",
",",
"String",
"propertyName",
",",
"String",
"newValue",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"newValue",
")",
")",
"{",
"String",
"currValue",
"=",
"vertex",
".",
"getProperty",
"(",
"propertyName",
",",
"String",
".",
"class",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"equals",
"(",
"currValue",
",",
"newValue",
")",
")",
"{",
"vertex",
".",
"setProperty",
"(",
"propertyName",
",",
"newValue",
")",
";",
"}",
"}",
"}"
] | /*
update the given vertex property, if the new value is not-blank | [
"/",
"*",
"update",
"the",
"given",
"vertex",
"property",
"if",
"the",
"new",
"value",
"is",
"not",
"-",
"blank"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java#L428-L436 |
apache/incubator-gobblin | gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanJobHelper.java | AzkabanJobHelper.isAzkabanJobPresent | public static boolean isAzkabanJobPresent(String sessionId, AzkabanProjectConfig azkabanProjectConfig)
throws IOException {
"""
*
Checks if an Azkaban project exists by name.
@param sessionId Session Id.
@param azkabanProjectConfig Azkaban Project Config that contains project name.
@return true if project exists else false.
@throws IOException
"""
log.info("Checking if Azkaban project: " + azkabanProjectConfig.getAzkabanProjectName() + " exists");
try {
// NOTE: hacky way to determine if project already exists because Azkaban does not provides a way to
// .. check if the project already exists or not
boolean isPresent = StringUtils.isNotBlank(AzkabanAjaxAPIClient.getProjectId(sessionId, azkabanProjectConfig));
log.info("Project exists: " + isPresent);
return isPresent;
} catch (IOException e) {
// Project doesn't exists
if (String.format("Project %s doesn't exist.", azkabanProjectConfig.getAzkabanProjectName())
.equalsIgnoreCase(e.getMessage())) {
log.info("Project does not exists.");
return false;
}
// Project exists but with no read access to current user
if ("Permission denied. Need READ access.".equalsIgnoreCase(e.getMessage())) {
log.info("Project exists, but current user does not has READ access.");
return true;
}
// Some other error
log.error("Issue in checking if project is present", e);
throw e;
}
} | java | public static boolean isAzkabanJobPresent(String sessionId, AzkabanProjectConfig azkabanProjectConfig)
throws IOException {
log.info("Checking if Azkaban project: " + azkabanProjectConfig.getAzkabanProjectName() + " exists");
try {
// NOTE: hacky way to determine if project already exists because Azkaban does not provides a way to
// .. check if the project already exists or not
boolean isPresent = StringUtils.isNotBlank(AzkabanAjaxAPIClient.getProjectId(sessionId, azkabanProjectConfig));
log.info("Project exists: " + isPresent);
return isPresent;
} catch (IOException e) {
// Project doesn't exists
if (String.format("Project %s doesn't exist.", azkabanProjectConfig.getAzkabanProjectName())
.equalsIgnoreCase(e.getMessage())) {
log.info("Project does not exists.");
return false;
}
// Project exists but with no read access to current user
if ("Permission denied. Need READ access.".equalsIgnoreCase(e.getMessage())) {
log.info("Project exists, but current user does not has READ access.");
return true;
}
// Some other error
log.error("Issue in checking if project is present", e);
throw e;
}
} | [
"public",
"static",
"boolean",
"isAzkabanJobPresent",
"(",
"String",
"sessionId",
",",
"AzkabanProjectConfig",
"azkabanProjectConfig",
")",
"throws",
"IOException",
"{",
"log",
".",
"info",
"(",
"\"Checking if Azkaban project: \"",
"+",
"azkabanProjectConfig",
".",
"getAzkabanProjectName",
"(",
")",
"+",
"\" exists\"",
")",
";",
"try",
"{",
"// NOTE: hacky way to determine if project already exists because Azkaban does not provides a way to",
"// .. check if the project already exists or not",
"boolean",
"isPresent",
"=",
"StringUtils",
".",
"isNotBlank",
"(",
"AzkabanAjaxAPIClient",
".",
"getProjectId",
"(",
"sessionId",
",",
"azkabanProjectConfig",
")",
")",
";",
"log",
".",
"info",
"(",
"\"Project exists: \"",
"+",
"isPresent",
")",
";",
"return",
"isPresent",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Project doesn't exists",
"if",
"(",
"String",
".",
"format",
"(",
"\"Project %s doesn't exist.\"",
",",
"azkabanProjectConfig",
".",
"getAzkabanProjectName",
"(",
")",
")",
".",
"equalsIgnoreCase",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Project does not exists.\"",
")",
";",
"return",
"false",
";",
"}",
"// Project exists but with no read access to current user",
"if",
"(",
"\"Permission denied. Need READ access.\"",
".",
"equalsIgnoreCase",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Project exists, but current user does not has READ access.\"",
")",
";",
"return",
"true",
";",
"}",
"// Some other error",
"log",
".",
"error",
"(",
"\"Issue in checking if project is present\"",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | *
Checks if an Azkaban project exists by name.
@param sessionId Session Id.
@param azkabanProjectConfig Azkaban Project Config that contains project name.
@return true if project exists else false.
@throws IOException | [
"*",
"Checks",
"if",
"an",
"Azkaban",
"project",
"exists",
"by",
"name",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanJobHelper.java#L56-L82 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Compatibility.java | Compatibility.checkDatasetName | public static void checkDatasetName(String namespace, String name) {
"""
Precondition-style validation that a dataset name is compatible.
@param namespace a String namespace
@param name a String name
"""
Preconditions.checkNotNull(namespace, "Namespace cannot be null");
Preconditions.checkNotNull(name, "Dataset name cannot be null");
ValidationException.check(Compatibility.isCompatibleName(namespace),
"Namespace %s is not alphanumeric (plus '_')",
namespace);
ValidationException.check(Compatibility.isCompatibleName(name),
"Dataset name %s is not alphanumeric (plus '_')",
name);
} | java | public static void checkDatasetName(String namespace, String name) {
Preconditions.checkNotNull(namespace, "Namespace cannot be null");
Preconditions.checkNotNull(name, "Dataset name cannot be null");
ValidationException.check(Compatibility.isCompatibleName(namespace),
"Namespace %s is not alphanumeric (plus '_')",
namespace);
ValidationException.check(Compatibility.isCompatibleName(name),
"Dataset name %s is not alphanumeric (plus '_')",
name);
} | [
"public",
"static",
"void",
"checkDatasetName",
"(",
"String",
"namespace",
",",
"String",
"name",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"namespace",
",",
"\"Namespace cannot be null\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"name",
",",
"\"Dataset name cannot be null\"",
")",
";",
"ValidationException",
".",
"check",
"(",
"Compatibility",
".",
"isCompatibleName",
"(",
"namespace",
")",
",",
"\"Namespace %s is not alphanumeric (plus '_')\"",
",",
"namespace",
")",
";",
"ValidationException",
".",
"check",
"(",
"Compatibility",
".",
"isCompatibleName",
"(",
"name",
")",
",",
"\"Dataset name %s is not alphanumeric (plus '_')\"",
",",
"name",
")",
";",
"}"
] | Precondition-style validation that a dataset name is compatible.
@param namespace a String namespace
@param name a String name | [
"Precondition",
"-",
"style",
"validation",
"that",
"a",
"dataset",
"name",
"is",
"compatible",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Compatibility.java#L99-L108 |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getPropertyAsBoolean | public static boolean getPropertyAsBoolean(final String name, final boolean defaultValue) {
"""
Get a property as a boolean, specifying a default value. If for any reason we are unable to
lookup the desired property, this method returns the supplied default value. This error
handling behavior makes this method suitable for calling from static initializers.
@param name - the name of the property to be accessed
@param defaultValue - default value that will be returned in the event of any error
@return the looked up property value, or the defaultValue if any problem.
@since 2.4
"""
if (PropertiesManager.props == null) loadProps();
boolean returnValue = defaultValue;
try {
returnValue = getPropertyAsBoolean(name);
} catch (MissingPropertyException mpe) {
// do nothing, since we already logged the missing property
}
return returnValue;
} | java | public static boolean getPropertyAsBoolean(final String name, final boolean defaultValue) {
if (PropertiesManager.props == null) loadProps();
boolean returnValue = defaultValue;
try {
returnValue = getPropertyAsBoolean(name);
} catch (MissingPropertyException mpe) {
// do nothing, since we already logged the missing property
}
return returnValue;
} | [
"public",
"static",
"boolean",
"getPropertyAsBoolean",
"(",
"final",
"String",
"name",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"boolean",
"returnValue",
"=",
"defaultValue",
";",
"try",
"{",
"returnValue",
"=",
"getPropertyAsBoolean",
"(",
"name",
")",
";",
"}",
"catch",
"(",
"MissingPropertyException",
"mpe",
")",
"{",
"// do nothing, since we already logged the missing property",
"}",
"return",
"returnValue",
";",
"}"
] | Get a property as a boolean, specifying a default value. If for any reason we are unable to
lookup the desired property, this method returns the supplied default value. This error
handling behavior makes this method suitable for calling from static initializers.
@param name - the name of the property to be accessed
@param defaultValue - default value that will be returned in the event of any error
@return the looked up property value, or the defaultValue if any problem.
@since 2.4 | [
"Get",
"a",
"property",
"as",
"a",
"boolean",
"specifying",
"a",
"default",
"value",
".",
"If",
"for",
"any",
"reason",
"we",
"are",
"unable",
"to",
"lookup",
"the",
"desired",
"property",
"this",
"method",
"returns",
"the",
"supplied",
"default",
"value",
".",
"This",
"error",
"handling",
"behavior",
"makes",
"this",
"method",
"suitable",
"for",
"calling",
"from",
"static",
"initializers",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L350-L359 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java | MessageRetriever.printWarning | private void printWarning(SourcePosition pos, String msg) {
"""
Print warning message, increment warning count.
@param pos the position of the source
@param msg message to print
"""
configuration.root.printWarning(pos, msg);
} | java | private void printWarning(SourcePosition pos, String msg) {
configuration.root.printWarning(pos, msg);
} | [
"private",
"void",
"printWarning",
"(",
"SourcePosition",
"pos",
",",
"String",
"msg",
")",
"{",
"configuration",
".",
"root",
".",
"printWarning",
"(",
"pos",
",",
"msg",
")",
";",
"}"
] | Print warning message, increment warning count.
@param pos the position of the source
@param msg message to print | [
"Print",
"warning",
"message",
"increment",
"warning",
"count",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java#L154-L156 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java | JobOperations.listPreparationAndReleaseTaskStatus | public PagedList<JobPreparationAndReleaseTaskExecutionInformation> listPreparationAndReleaseTaskStatus(String jobId) throws BatchErrorException, IOException {
"""
Lists the status of {@link JobPreparationTask} and {@link JobReleaseTask} tasks for the specified job.
@param jobId The ID of the job.
@return A list of {@link JobPreparationAndReleaseTaskExecutionInformation} instances.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
return listPreparationAndReleaseTaskStatus(jobId, null);
} | java | public PagedList<JobPreparationAndReleaseTaskExecutionInformation> listPreparationAndReleaseTaskStatus(String jobId) throws BatchErrorException, IOException {
return listPreparationAndReleaseTaskStatus(jobId, null);
} | [
"public",
"PagedList",
"<",
"JobPreparationAndReleaseTaskExecutionInformation",
">",
"listPreparationAndReleaseTaskStatus",
"(",
"String",
"jobId",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"return",
"listPreparationAndReleaseTaskStatus",
"(",
"jobId",
",",
"null",
")",
";",
"}"
] | Lists the status of {@link JobPreparationTask} and {@link JobReleaseTask} tasks for the specified job.
@param jobId The ID of the job.
@return A list of {@link JobPreparationAndReleaseTaskExecutionInformation} instances.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Lists",
"the",
"status",
"of",
"{",
"@link",
"JobPreparationTask",
"}",
"and",
"{",
"@link",
"JobReleaseTask",
"}",
"tasks",
"for",
"the",
"specified",
"job",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L246-L248 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.waitForPeersWithServiceMask | public ListenableFuture<List<Peer>> waitForPeersWithServiceMask(final int numPeers, final int mask) {
"""
Returns a future that is triggered when there are at least the requested number of connected peers that support
the given protocol version or higher. To block immediately, just call get() on the result.
@param numPeers How many peers to wait for.
@param mask An integer representing a bit mask that will be ANDed with the peers advertised service masks.
@return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers
"""
lock.lock();
try {
List<Peer> foundPeers = findPeersWithServiceMask(mask);
if (foundPeers.size() >= numPeers)
return Futures.immediateFuture(foundPeers);
final SettableFuture<List<Peer>> future = SettableFuture.create();
addConnectedEventListener(new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
final List<Peer> peers = findPeersWithServiceMask(mask);
if (peers.size() >= numPeers) {
future.set(peers);
removeConnectedEventListener(this);
}
}
});
return future;
} finally {
lock.unlock();
}
} | java | public ListenableFuture<List<Peer>> waitForPeersWithServiceMask(final int numPeers, final int mask) {
lock.lock();
try {
List<Peer> foundPeers = findPeersWithServiceMask(mask);
if (foundPeers.size() >= numPeers)
return Futures.immediateFuture(foundPeers);
final SettableFuture<List<Peer>> future = SettableFuture.create();
addConnectedEventListener(new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
final List<Peer> peers = findPeersWithServiceMask(mask);
if (peers.size() >= numPeers) {
future.set(peers);
removeConnectedEventListener(this);
}
}
});
return future;
} finally {
lock.unlock();
}
} | [
"public",
"ListenableFuture",
"<",
"List",
"<",
"Peer",
">",
">",
"waitForPeersWithServiceMask",
"(",
"final",
"int",
"numPeers",
",",
"final",
"int",
"mask",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"List",
"<",
"Peer",
">",
"foundPeers",
"=",
"findPeersWithServiceMask",
"(",
"mask",
")",
";",
"if",
"(",
"foundPeers",
".",
"size",
"(",
")",
">=",
"numPeers",
")",
"return",
"Futures",
".",
"immediateFuture",
"(",
"foundPeers",
")",
";",
"final",
"SettableFuture",
"<",
"List",
"<",
"Peer",
">",
">",
"future",
"=",
"SettableFuture",
".",
"create",
"(",
")",
";",
"addConnectedEventListener",
"(",
"new",
"PeerConnectedEventListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onPeerConnected",
"(",
"Peer",
"peer",
",",
"int",
"peerCount",
")",
"{",
"final",
"List",
"<",
"Peer",
">",
"peers",
"=",
"findPeersWithServiceMask",
"(",
"mask",
")",
";",
"if",
"(",
"peers",
".",
"size",
"(",
")",
">=",
"numPeers",
")",
"{",
"future",
".",
"set",
"(",
"peers",
")",
";",
"removeConnectedEventListener",
"(",
"this",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"future",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns a future that is triggered when there are at least the requested number of connected peers that support
the given protocol version or higher. To block immediately, just call get() on the result.
@param numPeers How many peers to wait for.
@param mask An integer representing a bit mask that will be ANDed with the peers advertised service masks.
@return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers | [
"Returns",
"a",
"future",
"that",
"is",
"triggered",
"when",
"there",
"are",
"at",
"least",
"the",
"requested",
"number",
"of",
"connected",
"peers",
"that",
"support",
"the",
"given",
"protocol",
"version",
"or",
"higher",
".",
"To",
"block",
"immediately",
"just",
"call",
"get",
"()",
"on",
"the",
"result",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1941-L1962 |
LearnLib/automatalib | visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/ImageComponent.java | ImageComponent.setImage | public void setImage(BufferedImage img) {
"""
Sets the image to be displayed.
@param img
the image to be displayed
"""
this.img = img;
Dimension dim;
if (img != null) {
dim = new Dimension(img.getWidth(), img.getHeight());
} else {
dim = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
setSize(dim);
setPreferredSize(dim);
repaint();
} | java | public void setImage(BufferedImage img) {
this.img = img;
Dimension dim;
if (img != null) {
dim = new Dimension(img.getWidth(), img.getHeight());
} else {
dim = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
setSize(dim);
setPreferredSize(dim);
repaint();
} | [
"public",
"void",
"setImage",
"(",
"BufferedImage",
"img",
")",
"{",
"this",
".",
"img",
"=",
"img",
";",
"Dimension",
"dim",
";",
"if",
"(",
"img",
"!=",
"null",
")",
"{",
"dim",
"=",
"new",
"Dimension",
"(",
"img",
".",
"getWidth",
"(",
")",
",",
"img",
".",
"getHeight",
"(",
")",
")",
";",
"}",
"else",
"{",
"dim",
"=",
"new",
"Dimension",
"(",
"DEFAULT_WIDTH",
",",
"DEFAULT_HEIGHT",
")",
";",
"}",
"setSize",
"(",
"dim",
")",
";",
"setPreferredSize",
"(",
"dim",
")",
";",
"repaint",
"(",
")",
";",
"}"
] | Sets the image to be displayed.
@param img
the image to be displayed | [
"Sets",
"the",
"image",
"to",
"be",
"displayed",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/ImageComponent.java#L110-L122 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java | InodeTreePersistentState.applyAndJournal | public long applyAndJournal(Supplier<JournalContext> context, NewBlockEntry entry) {
"""
Allocates and returns the next block ID for the indicated inode.
@param context journal context supplier
@param entry new block entry
@return the new block id
"""
try {
long id = applyNewBlock(entry);
context.get().append(JournalEntry.newBuilder().setNewBlock(entry).build());
return id;
} catch (Throwable t) {
ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry);
throw t; // fatalError will usually system.exit
}
} | java | public long applyAndJournal(Supplier<JournalContext> context, NewBlockEntry entry) {
try {
long id = applyNewBlock(entry);
context.get().append(JournalEntry.newBuilder().setNewBlock(entry).build());
return id;
} catch (Throwable t) {
ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry);
throw t; // fatalError will usually system.exit
}
} | [
"public",
"long",
"applyAndJournal",
"(",
"Supplier",
"<",
"JournalContext",
">",
"context",
",",
"NewBlockEntry",
"entry",
")",
"{",
"try",
"{",
"long",
"id",
"=",
"applyNewBlock",
"(",
"entry",
")",
";",
"context",
".",
"get",
"(",
")",
".",
"append",
"(",
"JournalEntry",
".",
"newBuilder",
"(",
")",
".",
"setNewBlock",
"(",
"entry",
")",
".",
"build",
"(",
")",
")",
";",
"return",
"id",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"ProcessUtils",
".",
"fatalError",
"(",
"LOG",
",",
"t",
",",
"\"Failed to apply %s\"",
",",
"entry",
")",
";",
"throw",
"t",
";",
"// fatalError will usually system.exit",
"}",
"}"
] | Allocates and returns the next block ID for the indicated inode.
@param context journal context supplier
@param entry new block entry
@return the new block id | [
"Allocates",
"and",
"returns",
"the",
"next",
"block",
"ID",
"for",
"the",
"indicated",
"inode",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java#L185-L194 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java | CmsSitemapView.updateModelPageDisabledState | public void updateModelPageDisabledState(CmsUUID entryId, boolean disabled) {
"""
Updates the disabled state for the given model page.<p>
@param entryId the model page id
@param disabled the disabled state
"""
if (m_modelPageTreeItems.containsKey(entryId)) {
m_modelPageTreeItems.get(entryId).setDisabled(disabled);
} else if (m_parentModelPageTreeItems.containsKey(entryId)) {
m_parentModelPageTreeItems.get(entryId).setDisabled(disabled);
}
} | java | public void updateModelPageDisabledState(CmsUUID entryId, boolean disabled) {
if (m_modelPageTreeItems.containsKey(entryId)) {
m_modelPageTreeItems.get(entryId).setDisabled(disabled);
} else if (m_parentModelPageTreeItems.containsKey(entryId)) {
m_parentModelPageTreeItems.get(entryId).setDisabled(disabled);
}
} | [
"public",
"void",
"updateModelPageDisabledState",
"(",
"CmsUUID",
"entryId",
",",
"boolean",
"disabled",
")",
"{",
"if",
"(",
"m_modelPageTreeItems",
".",
"containsKey",
"(",
"entryId",
")",
")",
"{",
"m_modelPageTreeItems",
".",
"get",
"(",
"entryId",
")",
".",
"setDisabled",
"(",
"disabled",
")",
";",
"}",
"else",
"if",
"(",
"m_parentModelPageTreeItems",
".",
"containsKey",
"(",
"entryId",
")",
")",
"{",
"m_parentModelPageTreeItems",
".",
"get",
"(",
"entryId",
")",
".",
"setDisabled",
"(",
"disabled",
")",
";",
"}",
"}"
] | Updates the disabled state for the given model page.<p>
@param entryId the model page id
@param disabled the disabled state | [
"Updates",
"the",
"disabled",
"state",
"for",
"the",
"given",
"model",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java#L1374-L1381 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java | Feature.setBooleanAttribute | public void setBooleanAttribute(String name, Boolean value) {
"""
Set attribute value of given type.
@param name attribute name
@param value attribute value
"""
Attribute attribute = getAttributes().get(name);
if (!(attribute instanceof BooleanAttribute)) {
throw new IllegalStateException("Cannot set boolean value on attribute with different type, " +
attribute.getClass().getName() + " setting value " + value);
}
((BooleanAttribute) attribute).setValue(value);
} | java | public void setBooleanAttribute(String name, Boolean value) {
Attribute attribute = getAttributes().get(name);
if (!(attribute instanceof BooleanAttribute)) {
throw new IllegalStateException("Cannot set boolean value on attribute with different type, " +
attribute.getClass().getName() + " setting value " + value);
}
((BooleanAttribute) attribute).setValue(value);
} | [
"public",
"void",
"setBooleanAttribute",
"(",
"String",
"name",
",",
"Boolean",
"value",
")",
"{",
"Attribute",
"attribute",
"=",
"getAttributes",
"(",
")",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"!",
"(",
"attribute",
"instanceof",
"BooleanAttribute",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot set boolean value on attribute with different type, \"",
"+",
"attribute",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\" setting value \"",
"+",
"value",
")",
";",
"}",
"(",
"(",
"BooleanAttribute",
")",
"attribute",
")",
".",
"setValue",
"(",
"value",
")",
";",
"}"
] | Set attribute value of given type.
@param name attribute name
@param value attribute value | [
"Set",
"attribute",
"value",
"of",
"given",
"type",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java#L215-L222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.