repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
Whiley/WhileyCompiler | src/main/java/wyil/interpreter/Interpreter.java | Interpreter.constructLVal | private LValue constructLVal(Expr expr, CallStack frame) {
switch (expr.getOpcode()) {
case EXPR_arrayborrow:
case EXPR_arrayaccess: {
Expr.ArrayAccess e = (Expr.ArrayAccess) expr;
LValue src = constructLVal(e.getFirstOperand(), frame);
RValue.Int index = executeExpression(INT_T, e.getSecondOperand(), frame);
return new LValue.Array(src, index);
}
case EXPR_dereference: {
Expr.Dereference e = (Expr.Dereference) expr;
LValue src = constructLVal(e.getOperand(), frame);
return new LValue.Dereference(src);
}
case EXPR_recordaccess:
case EXPR_recordborrow: {
Expr.RecordAccess e = (Expr.RecordAccess) expr;
LValue src = constructLVal(e.getOperand(), frame);
return new LValue.Record(src, e.getField());
}
case EXPR_variablemove:
case EXPR_variablecopy: {
Expr.VariableAccess e = (Expr.VariableAccess) expr;
Decl.Variable decl = e.getVariableDeclaration();
return new LValue.Variable(decl.getName());
}
}
deadCode(expr);
return null; // deadcode
} | java | private LValue constructLVal(Expr expr, CallStack frame) {
switch (expr.getOpcode()) {
case EXPR_arrayborrow:
case EXPR_arrayaccess: {
Expr.ArrayAccess e = (Expr.ArrayAccess) expr;
LValue src = constructLVal(e.getFirstOperand(), frame);
RValue.Int index = executeExpression(INT_T, e.getSecondOperand(), frame);
return new LValue.Array(src, index);
}
case EXPR_dereference: {
Expr.Dereference e = (Expr.Dereference) expr;
LValue src = constructLVal(e.getOperand(), frame);
return new LValue.Dereference(src);
}
case EXPR_recordaccess:
case EXPR_recordborrow: {
Expr.RecordAccess e = (Expr.RecordAccess) expr;
LValue src = constructLVal(e.getOperand(), frame);
return new LValue.Record(src, e.getField());
}
case EXPR_variablemove:
case EXPR_variablecopy: {
Expr.VariableAccess e = (Expr.VariableAccess) expr;
Decl.Variable decl = e.getVariableDeclaration();
return new LValue.Variable(decl.getName());
}
}
deadCode(expr);
return null; // deadcode
} | [
"private",
"LValue",
"constructLVal",
"(",
"Expr",
"expr",
",",
"CallStack",
"frame",
")",
"{",
"switch",
"(",
"expr",
".",
"getOpcode",
"(",
")",
")",
"{",
"case",
"EXPR_arrayborrow",
":",
"case",
"EXPR_arrayaccess",
":",
"{",
"Expr",
".",
"ArrayAccess",
... | This method constructs a "mutable" representation of the lval. This is a
bit strange, but is necessary because values in the frame are currently
immutable.
@param operand
@param frame
@param context
@return | [
"This",
"method",
"constructs",
"a",
"mutable",
"representation",
"of",
"the",
"lval",
".",
"This",
"is",
"a",
"bit",
"strange",
"but",
"is",
"necessary",
"because",
"values",
"in",
"the",
"frame",
"are",
"currently",
"immutable",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/interpreter/Interpreter.java#L1201-L1230 |
kiswanij/jk-util | src/main/java/com/jk/util/JKDateTimeUtil.java | JKDateTimeUtil.isTimesEqaualed | public static boolean isTimesEqaualed(Date time1, Date time2) {
return formatTime(time1).equals(formatTime(time2));
} | java | public static boolean isTimesEqaualed(Date time1, Date time2) {
return formatTime(time1).equals(formatTime(time2));
} | [
"public",
"static",
"boolean",
"isTimesEqaualed",
"(",
"Date",
"time1",
",",
"Date",
"time2",
")",
"{",
"return",
"formatTime",
"(",
"time1",
")",
".",
"equals",
"(",
"formatTime",
"(",
"time2",
")",
")",
";",
"}"
] | Checks if is times eqaualed.
@param time1 the time 1
@param time2 the time 2
@return true, if is times eqaualed | [
"Checks",
"if",
"is",
"times",
"eqaualed",
"."
] | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L164-L166 |
JOML-CI/JOML | src/org/joml/Matrix4x3d.java | Matrix4x3d.rotateYXZ | public Matrix4x3d rotateYXZ(Vector3d angles) {
return rotateYXZ(angles.y, angles.x, angles.z);
} | java | public Matrix4x3d rotateYXZ(Vector3d angles) {
return rotateYXZ(angles.y, angles.x, angles.z);
} | [
"public",
"Matrix4x3d",
"rotateYXZ",
"(",
"Vector3d",
"angles",
")",
"{",
"return",
"rotateYXZ",
"(",
"angles",
".",
"y",
",",
"angles",
".",
"x",
",",
"angles",
".",
"z",
")",
";",
"}"
] | Apply rotation of <code>angles.y</code> radians about the Y axis, followed by a rotation of <code>angles.x</code> radians about the X axis and
followed by a rotation of <code>angles.z</code> radians about the Z axis.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>M * R</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the
rotation will be applied first!
<p>
This method is equivalent to calling: <code>rotateY(angles.y).rotateX(angles.x).rotateZ(angles.z)</code>
@param angles
the Euler angles
@return this | [
"Apply",
"rotation",
"of",
"<code",
">",
"angles",
".",
"y<",
"/",
"code",
">",
"radians",
"about",
"the",
"Y",
"axis",
"followed",
"by",
"a",
"rotation",
"of",
"<code",
">",
"angles",
".",
"x<",
"/",
"code",
">",
"radians",
"about",
"the",
"X",
"axi... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L4580-L4582 |
taskadapter/redmine-java-api | src/main/java/com/taskadapter/redmineapi/internal/RedmineJSONBuilder.java | RedmineJSONBuilder.toSimpleJSON | public static <T> String toSimpleJSON(String tag, T object,
JsonObjectWriter<T> writer) throws RedmineInternalError {
final StringWriter swriter = new StringWriter();
final JSONWriter jsWriter = new JSONWriter(swriter);
try {
jsWriter.object();
jsWriter.key(tag);
jsWriter.object();
writer.write(jsWriter, object);
jsWriter.endObject();
jsWriter.endObject();
} catch (JSONException e) {
throw new RedmineInternalError("Unexpected JSONException", e);
}
return swriter.toString();
} | java | public static <T> String toSimpleJSON(String tag, T object,
JsonObjectWriter<T> writer) throws RedmineInternalError {
final StringWriter swriter = new StringWriter();
final JSONWriter jsWriter = new JSONWriter(swriter);
try {
jsWriter.object();
jsWriter.key(tag);
jsWriter.object();
writer.write(jsWriter, object);
jsWriter.endObject();
jsWriter.endObject();
} catch (JSONException e) {
throw new RedmineInternalError("Unexpected JSONException", e);
}
return swriter.toString();
} | [
"public",
"static",
"<",
"T",
">",
"String",
"toSimpleJSON",
"(",
"String",
"tag",
",",
"T",
"object",
",",
"JsonObjectWriter",
"<",
"T",
">",
"writer",
")",
"throws",
"RedmineInternalError",
"{",
"final",
"StringWriter",
"swriter",
"=",
"new",
"StringWriter",... | Converts object to a "simple" json.
@param tag
object tag.
@param object
object to convert.
@param writer
object writer.
@return object String representation.
@throws RedmineInternalError
if conversion fails. | [
"Converts",
"object",
"to",
"a",
"simple",
"json",
"."
] | train | https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/internal/RedmineJSONBuilder.java#L118-L134 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/LinearSGD.java | LinearSGD.setLambda1 | public void setLambda1(double lambda1)
{
if(lambda1 < 0 || Double.isNaN(lambda1) || Double.isInfinite(lambda1))
throw new IllegalArgumentException("Lambda1 must be non-negative, not " + lambda1);
this.lambda1 = lambda1;
} | java | public void setLambda1(double lambda1)
{
if(lambda1 < 0 || Double.isNaN(lambda1) || Double.isInfinite(lambda1))
throw new IllegalArgumentException("Lambda1 must be non-negative, not " + lambda1);
this.lambda1 = lambda1;
} | [
"public",
"void",
"setLambda1",
"(",
"double",
"lambda1",
")",
"{",
"if",
"(",
"lambda1",
"<",
"0",
"||",
"Double",
".",
"isNaN",
"(",
"lambda1",
")",
"||",
"Double",
".",
"isInfinite",
"(",
"lambda1",
")",
")",
"throw",
"new",
"IllegalArgumentException",
... | λ<sub>1</sub> controls the L<sub>1</sub> regularization penalty.
@param lambda1 the L<sub>1</sub> regularization penalty to use | [
"&lambda",
";",
"<sub",
">",
"1<",
"/",
"sub",
">",
"controls",
"the",
"L<sub",
">",
"1<",
"/",
"sub",
">",
"regularization",
"penalty",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/LinearSGD.java#L259-L264 |
code4everything/util | src/main/java/com/zhazhapan/util/FileExecutor.java | FileExecutor.saveFile | public static void saveFile(String path, String content) throws IOException {
saveFile(path, content, false);
} | java | public static void saveFile(String path, String content) throws IOException {
saveFile(path, content, false);
} | [
"public",
"static",
"void",
"saveFile",
"(",
"String",
"path",
",",
"String",
"content",
")",
"throws",
"IOException",
"{",
"saveFile",
"(",
"path",
",",
"content",
",",
"false",
")",
";",
"}"
] | 保存文件,覆盖原内容
@param path 文件路径
@param content 内容
@throws IOException 异常 | [
"保存文件,覆盖原内容"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L870-L872 |
caspervg/SC4D-LEX4J | lex4j/src/main/java/net/caspervg/lex4j/route/LotRoute.java | LotRoute.getLot | public Lot getLot(int id, ExtraLotInfo extra) {
ClientResource resource = new ClientResource(Route.LOT.url(id));
Route.handleExtraInfo(resource, extra, auth);
try {
Representation repr = resource.get();
return mapper.readValue(repr.getText(), Lot.class);
} catch (IOException e) {
LEX4JLogger.log(Level.WARNING, "Could not retrieve lot correctly!");
return null;
}
} | java | public Lot getLot(int id, ExtraLotInfo extra) {
ClientResource resource = new ClientResource(Route.LOT.url(id));
Route.handleExtraInfo(resource, extra, auth);
try {
Representation repr = resource.get();
return mapper.readValue(repr.getText(), Lot.class);
} catch (IOException e) {
LEX4JLogger.log(Level.WARNING, "Could not retrieve lot correctly!");
return null;
}
} | [
"public",
"Lot",
"getLot",
"(",
"int",
"id",
",",
"ExtraLotInfo",
"extra",
")",
"{",
"ClientResource",
"resource",
"=",
"new",
"ClientResource",
"(",
"Route",
".",
"LOT",
".",
"url",
"(",
"id",
")",
")",
";",
"Route",
".",
"handleExtraInfo",
"(",
"resour... | Retrieve the lot/file
@param id ID of the lot to be retrieved
@return Lot
@see ExtraLotInfo | [
"Retrieve",
"the",
"lot",
"/",
"file"
] | train | https://github.com/caspervg/SC4D-LEX4J/blob/3d086ec70c817119a88573c2e23af27276cdb1d6/lex4j/src/main/java/net/caspervg/lex4j/route/LotRoute.java#L66-L77 |
elki-project/elki | elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/LoggingUtil.java | LoggingUtil.logExpensive | public static void logExpensive(Level level, String message, Throwable e) {
String[] caller = inferCaller();
if(caller != null) {
Logger logger = Logger.getLogger(caller[0]);
logger.logp(level, caller[0], caller[1], message, e);
}
else {
Logger.getAnonymousLogger().log(level, message, e);
}
} | java | public static void logExpensive(Level level, String message, Throwable e) {
String[] caller = inferCaller();
if(caller != null) {
Logger logger = Logger.getLogger(caller[0]);
logger.logp(level, caller[0], caller[1], message, e);
}
else {
Logger.getAnonymousLogger().log(level, message, e);
}
} | [
"public",
"static",
"void",
"logExpensive",
"(",
"Level",
"level",
",",
"String",
"message",
",",
"Throwable",
"e",
")",
"{",
"String",
"[",
"]",
"caller",
"=",
"inferCaller",
"(",
")",
";",
"if",
"(",
"caller",
"!=",
"null",
")",
"{",
"Logger",
"logge... | Expensive logging function that is convenient, but should only be used in
rare conditions.
For 'frequent' logging, use more efficient techniques, such as explained in
the {@link de.lmu.ifi.dbs.elki.logging logging package documentation}.
@param level Logging level
@param message Message to log.
@param e Exception to report. | [
"Expensive",
"logging",
"function",
"that",
"is",
"convenient",
"but",
"should",
"only",
"be",
"used",
"in",
"rare",
"conditions",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/LoggingUtil.java#L58-L67 |
googleapis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/adapters/admin/ColumnDescriptorAdapter.java | ColumnDescriptorAdapter.processIntersection | protected static void processIntersection(GcRule gcRule, HColumnDescriptor columnDescriptor) {
// minVersions and maxAge are set.
List<GcRule> intersectionRules = gcRule.getIntersection().getRulesList();
Preconditions.checkArgument(intersectionRules.size() == 2, "Cannot process rule " + gcRule);
columnDescriptor.setMinVersions(getVersionCount(intersectionRules));
columnDescriptor.setTimeToLive(getTtl(intersectionRules));
} | java | protected static void processIntersection(GcRule gcRule, HColumnDescriptor columnDescriptor) {
// minVersions and maxAge are set.
List<GcRule> intersectionRules = gcRule.getIntersection().getRulesList();
Preconditions.checkArgument(intersectionRules.size() == 2, "Cannot process rule " + gcRule);
columnDescriptor.setMinVersions(getVersionCount(intersectionRules));
columnDescriptor.setTimeToLive(getTtl(intersectionRules));
} | [
"protected",
"static",
"void",
"processIntersection",
"(",
"GcRule",
"gcRule",
",",
"HColumnDescriptor",
"columnDescriptor",
")",
"{",
"// minVersions and maxAge are set.",
"List",
"<",
"GcRule",
">",
"intersectionRules",
"=",
"gcRule",
".",
"getIntersection",
"(",
")",... | <p>processIntersection.</p>
@param gcRule a {@link com.google.bigtable.admin.v2.GcRule} object.
@param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. | [
"<p",
">",
"processIntersection",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/adapters/admin/ColumnDescriptorAdapter.java#L262-L268 |
boncey/Flickr4Java | src/main/java/com/flickr4java/flickr/REST.java | REST.getNonOAuth | @Override
public Response getNonOAuth(String path, Map<String, String> parameters) {
InputStream in = null;
try {
URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters);
if (Flickr.debugRequest) {
logger.debug("GET: " + url);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (proxyAuth) {
conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials());
}
setTimeouts(conn);
conn.connect();
if (Flickr.debugStream) {
in = new DebugInputStream(conn.getInputStream(), System.out);
} else {
in = conn.getInputStream();
}
Response response;
DocumentBuilder builder = getDocumentBuilder();
Document document = builder.parse(in);
response = (Response) responseClass.newInstance();
response.parse(document);
return response;
} catch (IllegalAccessException | SAXException | IOException | InstantiationException | ParserConfigurationException e) {
throw new FlickrRuntimeException(e);
} finally {
IOUtilities.close(in);
}
} | java | @Override
public Response getNonOAuth(String path, Map<String, String> parameters) {
InputStream in = null;
try {
URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters);
if (Flickr.debugRequest) {
logger.debug("GET: " + url);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (proxyAuth) {
conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials());
}
setTimeouts(conn);
conn.connect();
if (Flickr.debugStream) {
in = new DebugInputStream(conn.getInputStream(), System.out);
} else {
in = conn.getInputStream();
}
Response response;
DocumentBuilder builder = getDocumentBuilder();
Document document = builder.parse(in);
response = (Response) responseClass.newInstance();
response.parse(document);
return response;
} catch (IllegalAccessException | SAXException | IOException | InstantiationException | ParserConfigurationException e) {
throw new FlickrRuntimeException(e);
} finally {
IOUtilities.close(in);
}
} | [
"@",
"Override",
"public",
"Response",
"getNonOAuth",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"InputStream",
"in",
"=",
"null",
";",
"try",
"{",
"URL",
"url",
"=",
"UrlUtilities",
".",
"buildUrl",
"("... | Invoke a non OAuth HTTP GET request on a remote host.
<p>
This is only used for the Flickr OAuth methods checkToken and getAccessToken.
@param path The request path
@param parameters The parameters
@return The Response | [
"Invoke",
"a",
"non",
"OAuth",
"HTTP",
"GET",
"request",
"on",
"a",
"remote",
"host",
".",
"<p",
">",
"This",
"is",
"only",
"used",
"for",
"the",
"Flickr",
"OAuth",
"methods",
"checkToken",
"and",
"getAccessToken",
"."
] | train | https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/REST.java#L281-L315 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/draw/LineSeparator.java | LineSeparator.drawLine | public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) {
float w;
if (getPercentage() < 0)
w = -getPercentage();
else
w = (rightX - leftX) * getPercentage() / 100.0f;
float s;
switch (getAlignment()) {
case Element.ALIGN_LEFT:
s = 0;
break;
case Element.ALIGN_RIGHT:
s = rightX - leftX - w;
break;
default:
s = (rightX - leftX - w) / 2;
break;
}
canvas.setLineWidth(getLineWidth());
if (getLineColor() != null)
canvas.setColorStroke(getLineColor());
canvas.moveTo(s + leftX, y + offset);
canvas.lineTo(s + w + leftX, y + offset);
canvas.stroke();
} | java | public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) {
float w;
if (getPercentage() < 0)
w = -getPercentage();
else
w = (rightX - leftX) * getPercentage() / 100.0f;
float s;
switch (getAlignment()) {
case Element.ALIGN_LEFT:
s = 0;
break;
case Element.ALIGN_RIGHT:
s = rightX - leftX - w;
break;
default:
s = (rightX - leftX - w) / 2;
break;
}
canvas.setLineWidth(getLineWidth());
if (getLineColor() != null)
canvas.setColorStroke(getLineColor());
canvas.moveTo(s + leftX, y + offset);
canvas.lineTo(s + w + leftX, y + offset);
canvas.stroke();
} | [
"public",
"void",
"drawLine",
"(",
"PdfContentByte",
"canvas",
",",
"float",
"leftX",
",",
"float",
"rightX",
",",
"float",
"y",
")",
"{",
"float",
"w",
";",
"if",
"(",
"getPercentage",
"(",
")",
"<",
"0",
")",
"w",
"=",
"-",
"getPercentage",
"(",
")... | Draws a horizontal line.
@param canvas the canvas to draw on
@param leftX the left x coordinate
@param rightX the right x coordindate
@param y the y coordinate | [
"Draws",
"a",
"horizontal",
"line",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/draw/LineSeparator.java#L114-L138 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/TileBoundingBoxMapUtils.java | TileBoundingBoxMapUtils.getLongitudeDistance | public static double getLongitudeDistance(double minLongitude,
double maxLongitude,
double latitude) {
LatLng leftMiddle = new LatLng(latitude, minLongitude);
LatLng middle = new LatLng(latitude, (minLongitude + maxLongitude) / 2.0);
LatLng rightMiddle = new LatLng(latitude, maxLongitude);
List<LatLng> path = new ArrayList<LatLng>();
path.add(leftMiddle);
path.add(middle);
path.add(rightMiddle);
double lonDistance = SphericalUtil.computeLength(path);
return lonDistance;
} | java | public static double getLongitudeDistance(double minLongitude,
double maxLongitude,
double latitude) {
LatLng leftMiddle = new LatLng(latitude, minLongitude);
LatLng middle = new LatLng(latitude, (minLongitude + maxLongitude) / 2.0);
LatLng rightMiddle = new LatLng(latitude, maxLongitude);
List<LatLng> path = new ArrayList<LatLng>();
path.add(leftMiddle);
path.add(middle);
path.add(rightMiddle);
double lonDistance = SphericalUtil.computeLength(path);
return lonDistance;
} | [
"public",
"static",
"double",
"getLongitudeDistance",
"(",
"double",
"minLongitude",
",",
"double",
"maxLongitude",
",",
"double",
"latitude",
")",
"{",
"LatLng",
"leftMiddle",
"=",
"new",
"LatLng",
"(",
"latitude",
",",
"minLongitude",
")",
";",
"LatLng",
"midd... | Get the longitude distance in the middle latitude
@param minLongitude min longitude
@param maxLongitude max longitude
@param latitude latitude
@return distance
@since 1.2.7 | [
"Get",
"the",
"longitude",
"distance",
"in",
"the",
"middle",
"latitude"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/TileBoundingBoxMapUtils.java#L52-L66 |
albfernandez/itext2 | src/main/java/com/lowagie/text/Utilities.java | Utilities.isSurrogatePair | public static boolean isSurrogatePair(String text, int idx) {
if (idx < 0 || idx > text.length() - 2)
return false;
return isSurrogateHigh(text.charAt(idx)) && isSurrogateLow(text.charAt(idx + 1));
} | java | public static boolean isSurrogatePair(String text, int idx) {
if (idx < 0 || idx > text.length() - 2)
return false;
return isSurrogateHigh(text.charAt(idx)) && isSurrogateLow(text.charAt(idx + 1));
} | [
"public",
"static",
"boolean",
"isSurrogatePair",
"(",
"String",
"text",
",",
"int",
"idx",
")",
"{",
"if",
"(",
"idx",
"<",
"0",
"||",
"idx",
">",
"text",
".",
"length",
"(",
")",
"-",
"2",
")",
"return",
"false",
";",
"return",
"isSurrogateHigh",
"... | Checks if two subsequent characters in a String are
are the higher and the lower character in a surrogate
pair (and therefore eligible for conversion to a UTF 32 character).
@param text the String with the high and low surrogate characters
@param idx the index of the 'high' character in the pair
@return true if the characters are surrogate pairs
@since 2.1.2 | [
"Checks",
"if",
"two",
"subsequent",
"characters",
"in",
"a",
"String",
"are",
"are",
"the",
"higher",
"and",
"the",
"lower",
"character",
"in",
"a",
"surrogate",
"pair",
"(",
"and",
"therefore",
"eligible",
"for",
"conversion",
"to",
"a",
"UTF",
"32",
"ch... | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Utilities.java#L275-L279 |
ow2-chameleon/fuchsia | importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java | ZWaveController.requestValue | public void requestValue(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
ZWaveGetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SENSOR_BINARY, ZWaveCommandClass.CommandClass.SENSOR_ALARM, ZWaveCommandClass.CommandClass.SENSOR_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveGetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.getValueMessage(), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | java | public void requestValue(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
ZWaveGetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SENSOR_BINARY, ZWaveCommandClass.CommandClass.SENSOR_ALARM, ZWaveCommandClass.CommandClass.SENSOR_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveGetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.getValueMessage(), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | [
"public",
"void",
"requestValue",
"(",
"int",
"nodeId",
",",
"int",
"endpoint",
")",
"{",
"ZWaveNode",
"node",
"=",
"this",
".",
"getNode",
"(",
"nodeId",
")",
";",
"ZWaveGetCommands",
"zwaveCommandClass",
"=",
"null",
";",
"SerialMessage",
"serialMessage",
"=... | Request value from the node / endpoint;
@param nodeId the node id to request the value for.
@param endpoint the endpoint to request the value for. | [
"Request",
"value",
"from",
"the",
"node",
"/",
"endpoint",
";"
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java#L854-L874 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/windows/WindowsProcessFaxClientSpi.java | WindowsProcessFaxClientSpi.createProcessCommandArgumentsForSubmitFaxJob | protected String createProcessCommandArgumentsForSubmitFaxJob(FaxJob faxJob)
{
//get values from fax job
String targetAddress=faxJob.getTargetAddress();
String targetName=faxJob.getTargetName();
String senderName=faxJob.getSenderName();
File file=faxJob.getFile();
String fileName=null;
try
{
fileName=file.getCanonicalPath();
}
catch(Exception exception)
{
throw new FaxException("Unable to extract canonical path from file: "+file,exception);
}
String documentName=faxJob.getProperty(WindowsFaxClientSpi.FaxJobExtendedPropertyConstants.DOCUMENT_NAME_PROPERTY_KEY.toString(), null);
//init buffer
StringBuilder buffer=new StringBuilder();
//create command line arguments
this.addCommandLineArgument(buffer,Fax4jExeConstants.ACTION_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),Fax4jExeConstants.SUBMIT_ACTION_FAX4J_EXE_COMMAND_LINE_ARGUMENT_VALUE.toString());
this.addCommandLineArgument(buffer,Fax4jExeConstants.SERVER_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),this.faxServerName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.TARGET_ADDRESS_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),targetAddress);
this.addCommandLineArgument(buffer,Fax4jExeConstants.TARGET_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),targetName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.SENDER_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),senderName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.FILE_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),fileName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.DOCUMENT_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),documentName);
//get text
String commandArguments=buffer.toString();
return commandArguments;
} | java | protected String createProcessCommandArgumentsForSubmitFaxJob(FaxJob faxJob)
{
//get values from fax job
String targetAddress=faxJob.getTargetAddress();
String targetName=faxJob.getTargetName();
String senderName=faxJob.getSenderName();
File file=faxJob.getFile();
String fileName=null;
try
{
fileName=file.getCanonicalPath();
}
catch(Exception exception)
{
throw new FaxException("Unable to extract canonical path from file: "+file,exception);
}
String documentName=faxJob.getProperty(WindowsFaxClientSpi.FaxJobExtendedPropertyConstants.DOCUMENT_NAME_PROPERTY_KEY.toString(), null);
//init buffer
StringBuilder buffer=new StringBuilder();
//create command line arguments
this.addCommandLineArgument(buffer,Fax4jExeConstants.ACTION_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),Fax4jExeConstants.SUBMIT_ACTION_FAX4J_EXE_COMMAND_LINE_ARGUMENT_VALUE.toString());
this.addCommandLineArgument(buffer,Fax4jExeConstants.SERVER_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),this.faxServerName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.TARGET_ADDRESS_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),targetAddress);
this.addCommandLineArgument(buffer,Fax4jExeConstants.TARGET_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),targetName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.SENDER_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),senderName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.FILE_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),fileName);
this.addCommandLineArgument(buffer,Fax4jExeConstants.DOCUMENT_NAME_FAX4J_EXE_COMMAND_LINE_ARGUMENT.toString(),documentName);
//get text
String commandArguments=buffer.toString();
return commandArguments;
} | [
"protected",
"String",
"createProcessCommandArgumentsForSubmitFaxJob",
"(",
"FaxJob",
"faxJob",
")",
"{",
"//get values from fax job",
"String",
"targetAddress",
"=",
"faxJob",
".",
"getTargetAddress",
"(",
")",
";",
"String",
"targetName",
"=",
"faxJob",
".",
"getTarge... | This function creates and returns the command line arguments for the fax4j
external exe when running the submit fax job action.
@param faxJob
The fax job object
@return The full command line arguments line | [
"This",
"function",
"creates",
"and",
"returns",
"the",
"command",
"line",
"arguments",
"for",
"the",
"fax4j",
"external",
"exe",
"when",
"running",
"the",
"submit",
"fax",
"job",
"action",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/windows/WindowsProcessFaxClientSpi.java#L341-L375 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseAdvisorsInner.java | DatabaseAdvisorsInner.listByDatabaseAsync | public Observable<AdvisorListResultInner> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) {
return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<AdvisorListResultInner>, AdvisorListResultInner>() {
@Override
public AdvisorListResultInner call(ServiceResponse<AdvisorListResultInner> response) {
return response.body();
}
});
} | java | public Observable<AdvisorListResultInner> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) {
return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<AdvisorListResultInner>, AdvisorListResultInner>() {
@Override
public AdvisorListResultInner call(ServiceResponse<AdvisorListResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AdvisorListResultInner",
">",
"listByDatabaseAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"listByDatabaseWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
... | Returns a list of database advisors.
@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 databaseName The name of the database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AdvisorListResultInner object | [
"Returns",
"a",
"list",
"of",
"database",
"advisors",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseAdvisorsInner.java#L109-L116 |
bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java | QRCodeImages.imageFromString | public static Image imageFromString(String uri, int width, int height) {
return imageFromMatrix(matrixFromString(uri, width, height));
} | java | public static Image imageFromString(String uri, int width, int height) {
return imageFromMatrix(matrixFromString(uri, width, height));
} | [
"public",
"static",
"Image",
"imageFromString",
"(",
"String",
"uri",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"return",
"imageFromMatrix",
"(",
"matrixFromString",
"(",
"uri",
",",
"width",
",",
"height",
")",
")",
";",
"}"
] | Create an Image from a Bitcoin URI
@param uri Bitcoin URI
@param width width of image
@param height height of image
@return a javafx Image | [
"Create",
"an",
"Image",
"from",
"a",
"Bitcoin",
"URI"
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java#L39-L41 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java | AccountsInner.beginUpdate | public DataLakeAnalyticsAccountInner beginUpdate(String resourceGroupName, String accountName, UpdateDataLakeAnalyticsAccountParameters parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body();
} | java | public DataLakeAnalyticsAccountInner beginUpdate(String resourceGroupName, String accountName, UpdateDataLakeAnalyticsAccountParameters parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body();
} | [
"public",
"DataLakeAnalyticsAccountInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"UpdateDataLakeAnalyticsAccountParameters",
"parameters",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"... | Updates the Data Lake Analytics account object specified by the accountName with the contents of the account object.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@param parameters Parameters supplied to the update Data Lake Analytics account operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DataLakeAnalyticsAccountInner object if successful. | [
"Updates",
"the",
"Data",
"Lake",
"Analytics",
"account",
"object",
"specified",
"by",
"the",
"accountName",
"with",
"the",
"contents",
"of",
"the",
"account",
"object",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java#L1116-L1118 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java | JSONHelpers.hasInstanceOf | public static boolean hasInstanceOf(final JSONObject json, final String key,
Class<?> type) {
Object o = json.opt(key);
return isInstanceOf(o, type);
} | java | public static boolean hasInstanceOf(final JSONObject json, final String key,
Class<?> type) {
Object o = json.opt(key);
return isInstanceOf(o, type);
} | [
"public",
"static",
"boolean",
"hasInstanceOf",
"(",
"final",
"JSONObject",
"json",
",",
"final",
"String",
"key",
",",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"Object",
"o",
"=",
"json",
".",
"opt",
"(",
"key",
")",
";",
"return",
"isInstanceOf",
"(... | Check if the {@link JSONObject} has an item at {@code key} that is an
instance of {@code type}.
@param json {@code JSONObject} to inspect
@param key Item in object to check
@param type Type to check the item against
@return {@code True} if the item exists and is of the specified
{@code type}; {@code false} otherwise | [
"Check",
"if",
"the",
"{",
"@link",
"JSONObject",
"}",
"has",
"an",
"item",
"at",
"{",
"@code",
"key",
"}",
"that",
"is",
"an",
"instance",
"of",
"{",
"@code",
"type",
"}",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L1117-L1121 |
redkale/redkale | src/org/redkale/asm/ClassWriter.java | ClassWriter.newStringishItem | Item newStringishItem(final int type, final String value) {
key2.set(type, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(type, newUTF8(value));
result = new Item(index++, key2);
put(result);
}
return result;
} | java | Item newStringishItem(final int type, final String value) {
key2.set(type, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(type, newUTF8(value));
result = new Item(index++, key2);
put(result);
}
return result;
} | [
"Item",
"newStringishItem",
"(",
"final",
"int",
"type",
",",
"final",
"String",
"value",
")",
"{",
"key2",
".",
"set",
"(",
"type",
",",
"value",
",",
"null",
",",
"null",
")",
";",
"Item",
"result",
"=",
"get",
"(",
"key2",
")",
";",
"if",
"(",
... | Adds a string reference, a class reference, a method type, a module
or a package to the constant pool of the class being build.
Does nothing if the constant pool already contains a similar item.
@param type
a type among STR, CLASS, MTYPE, MODULE or PACKAGE
@param value
string value of the reference.
@return a new or already existing reference item. | [
"Adds",
"a",
"string",
"reference",
"a",
"class",
"reference",
"a",
"method",
"type",
"a",
"module",
"or",
"a",
"package",
"to",
"the",
"constant",
"pool",
"of",
"the",
"class",
"being",
"build",
".",
"Does",
"nothing",
"if",
"the",
"constant",
"pool",
"... | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/asm/ClassWriter.java#L1188-L1197 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java | Organizer.sortByJavaBeanProperty | @SuppressWarnings("unchecked")
public static <T> Collection<T> sortByJavaBeanProperty(String aProperyName,
Collection<T> aCollection, boolean aDescending)
{
if (aCollection == null)
return (Collection<T>) new ArrayList<T>();
if (aProperyName == null)
throw new IllegalArgumentException(
"aProperyName required in Organizer");
BeanComparator bc = new BeanComparator(aProperyName, aDescending);
return (Collection<T>) bc.sort(aCollection);
} | java | @SuppressWarnings("unchecked")
public static <T> Collection<T> sortByJavaBeanProperty(String aProperyName,
Collection<T> aCollection, boolean aDescending)
{
if (aCollection == null)
return (Collection<T>) new ArrayList<T>();
if (aProperyName == null)
throw new IllegalArgumentException(
"aProperyName required in Organizer");
BeanComparator bc = new BeanComparator(aProperyName, aDescending);
return (Collection<T>) bc.sort(aCollection);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"Collection",
"<",
"T",
">",
"sortByJavaBeanProperty",
"(",
"String",
"aProperyName",
",",
"Collection",
"<",
"T",
">",
"aCollection",
",",
"boolean",
"aDescending",
")",
"{... | Sort collection of object by a given property name
@param <T>
the type class name
@param aProperyName
the property name
@param aDescending
boolean if sorting descending or not
@param aCollection
the collection of object to sort
@return the collection of sorted collection of the property | [
"Sort",
"collection",
"of",
"object",
"by",
"a",
"given",
"property",
"name"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L967-L982 |
rythmengine/rythmengine | src/main/java/org/rythmengine/utils/S.java | S.formatCurrency | public static String formatCurrency(Object data, String currencyCode, Locale locale) {
return formatCurrency(null, data, currencyCode, locale);
} | java | public static String formatCurrency(Object data, String currencyCode, Locale locale) {
return formatCurrency(null, data, currencyCode, locale);
} | [
"public",
"static",
"String",
"formatCurrency",
"(",
"Object",
"data",
",",
"String",
"currencyCode",
",",
"Locale",
"locale",
")",
"{",
"return",
"formatCurrency",
"(",
"null",
",",
"data",
",",
"currencyCode",
",",
"locale",
")",
";",
"}"
] | See {@link #formatCurrency(org.rythmengine.template.ITemplate, Object, String, java.util.Locale)}
@param data
@param currencyCode
@param locale
@return the currency string | [
"See",
"{",
"@link",
"#formatCurrency",
"(",
"org",
".",
"rythmengine",
".",
"template",
".",
"ITemplate",
"Object",
"String",
"java",
".",
"util",
".",
"Locale",
")",
"}"
] | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/utils/S.java#L1494-L1496 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newPageNotFoundException | public static PageNotFoundException newPageNotFoundException(String message, Object... args) {
return newPageNotFoundException(null, message, args);
} | java | public static PageNotFoundException newPageNotFoundException(String message, Object... args) {
return newPageNotFoundException(null, message, args);
} | [
"public",
"static",
"PageNotFoundException",
"newPageNotFoundException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newPageNotFoundException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] | Constructs and initializes a new {@link PageNotFoundException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link PageNotFoundException}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link PageNotFoundException} with the given {@link String message}.
@see #newPageNotFoundException(Throwable, String, Object...)
@see org.cp.elements.util.paging.PageNotFoundException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"PageNotFoundException",
"}",
"with",
"the",
"given",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L817-L819 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java | ApiOvhDbaaslogs.serviceName_option_optionId_GET | public OvhOption serviceName_option_optionId_GET(String serviceName, String optionId) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/option/{optionId}";
StringBuilder sb = path(qPath, serviceName, optionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOption.class);
} | java | public OvhOption serviceName_option_optionId_GET(String serviceName, String optionId) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/option/{optionId}";
StringBuilder sb = path(qPath, serviceName, optionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOption.class);
} | [
"public",
"OvhOption",
"serviceName_option_optionId_GET",
"(",
"String",
"serviceName",
",",
"String",
"optionId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dbaas/logs/{serviceName}/option/{optionId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
... | Returns details of a subscribed option
REST: GET /dbaas/logs/{serviceName}/option/{optionId}
@param serviceName [required] Service name
@param optionId [required] Option ID | [
"Returns",
"details",
"of",
"a",
"subscribed",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L636-L641 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/pattern/Patterns.java | Patterns.regex | public static Pattern regex(final java.util.regex.Pattern p) {
return new Pattern() {
@Override
public int match(CharSequence src, int begin, int end) {
if (begin > end)
return MISMATCH;
Matcher matcher = p.matcher(src.subSequence(begin, end));
if (matcher.lookingAt())
return matcher.end();
return MISMATCH;
}
};
} | java | public static Pattern regex(final java.util.regex.Pattern p) {
return new Pattern() {
@Override
public int match(CharSequence src, int begin, int end) {
if (begin > end)
return MISMATCH;
Matcher matcher = p.matcher(src.subSequence(begin, end));
if (matcher.lookingAt())
return matcher.end();
return MISMATCH;
}
};
} | [
"public",
"static",
"Pattern",
"regex",
"(",
"final",
"java",
".",
"util",
".",
"regex",
".",
"Pattern",
"p",
")",
"{",
"return",
"new",
"Pattern",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"match",
"(",
"CharSequence",
"src",
",",
"int",
"begin... | Adapts a regular expression pattern to a {@link Pattern}.
<p><em>WARNING</em>: in addition to regular expression cost, the returned {@code Pattern} object needs
to make a substring copy every time it's evaluated. This can incur excessive copying and memory overhead
when parsing large strings. Consider implementing {@code Pattern} manually for large input. | [
"Adapts",
"a",
"regular",
"expression",
"pattern",
"to",
"a",
"{",
"@link",
"Pattern",
"}",
"."
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/pattern/Patterns.java#L518-L530 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/FragmentJoiner.java | FragmentJoiner.getRMS | public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) throws StructureException {
// now svd ftmp and check if the rms is < X ...
AlternativeAlignment ali = new AlternativeAlignment();
ali.apairs_from_idxlst(frag);
double rms = 999;
int[] idx1 = ali.getIdx1();
int[] idx2 = ali.getIdx2();
Atom[] ca1subset = AlignUtils.getFragmentFromIdxList(ca1, idx1);
Atom[] ca2subset = AlignUtils.getFragmentFromIdxList(ca2,idx2);
ali.calculateSuperpositionByIdx(ca1,ca2);
Matrix rot = ali.getRotationMatrix();
Atom atom = ali.getShift();
for (Atom a : ca2subset) {
Calc.rotate(a, rot);
Calc.shift(a, atom);
}
rms = Calc.rmsd(ca1subset,ca2subset);
return rms;
} | java | public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) throws StructureException {
// now svd ftmp and check if the rms is < X ...
AlternativeAlignment ali = new AlternativeAlignment();
ali.apairs_from_idxlst(frag);
double rms = 999;
int[] idx1 = ali.getIdx1();
int[] idx2 = ali.getIdx2();
Atom[] ca1subset = AlignUtils.getFragmentFromIdxList(ca1, idx1);
Atom[] ca2subset = AlignUtils.getFragmentFromIdxList(ca2,idx2);
ali.calculateSuperpositionByIdx(ca1,ca2);
Matrix rot = ali.getRotationMatrix();
Atom atom = ali.getShift();
for (Atom a : ca2subset) {
Calc.rotate(a, rot);
Calc.shift(a, atom);
}
rms = Calc.rmsd(ca1subset,ca2subset);
return rms;
} | [
"public",
"static",
"double",
"getRMS",
"(",
"Atom",
"[",
"]",
"ca1",
",",
"Atom",
"[",
"]",
"ca2",
",",
"JointFragments",
"frag",
")",
"throws",
"StructureException",
"{",
"// now svd ftmp and check if the rms is < X ...",
"AlternativeAlignment",
"ali",
"=",
"... | Get the RMS of the JointFragments pair frag
@param ca1 the array of all atoms of structure1
@param ca2 the array of all atoms of structure1
@param frag the JointFragments object that contains the list of identical positions
@return the rms | [
"Get",
"the",
"RMS",
"of",
"the",
"JointFragments",
"pair",
"frag"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/FragmentJoiner.java#L296-L322 |
Alluxio/alluxio | core/server/worker/src/main/java/alluxio/worker/block/meta/AbstractBlockMeta.java | AbstractBlockMeta.tempPath | public static String tempPath(StorageDir dir, long sessionId, long blockId) {
final String tmpDir = ServerConfiguration.get(PropertyKey.WORKER_DATA_TMP_FOLDER);
final int subDirMax = ServerConfiguration.getInt(PropertyKey.WORKER_DATA_TMP_SUBDIR_MAX);
return PathUtils.concatPath(dir.getDirPath(), tmpDir, sessionId % subDirMax,
String.format("%x-%x", sessionId, blockId));
} | java | public static String tempPath(StorageDir dir, long sessionId, long blockId) {
final String tmpDir = ServerConfiguration.get(PropertyKey.WORKER_DATA_TMP_FOLDER);
final int subDirMax = ServerConfiguration.getInt(PropertyKey.WORKER_DATA_TMP_SUBDIR_MAX);
return PathUtils.concatPath(dir.getDirPath(), tmpDir, sessionId % subDirMax,
String.format("%x-%x", sessionId, blockId));
} | [
"public",
"static",
"String",
"tempPath",
"(",
"StorageDir",
"dir",
",",
"long",
"sessionId",
",",
"long",
"blockId",
")",
"{",
"final",
"String",
"tmpDir",
"=",
"ServerConfiguration",
".",
"get",
"(",
"PropertyKey",
".",
"WORKER_DATA_TMP_FOLDER",
")",
";",
"f... | All blocks are created as temp blocks before committed. They are stored in BlockStore under a
subdir of its {@link StorageDir}, the subdir is tmpFolder/sessionId % maxSubdirMax.
tmpFolder is a property of {@link PropertyKey#WORKER_DATA_TMP_FOLDER}.
maxSubdirMax is a property of {@link PropertyKey#WORKER_DATA_TMP_SUBDIR_MAX}.
The block file name is "sessionId-blockId". e.g. sessionId 2 creates a temp Block 100 in
{@link StorageDir} "/mnt/mem/0", this temp block has path:
<p>
/mnt/mem/0/.tmp_blocks/2/2-100
@param dir the parent directory
@param sessionId the session id
@param blockId the block id
@return temp file path | [
"All",
"blocks",
"are",
"created",
"as",
"temp",
"blocks",
"before",
"committed",
".",
"They",
"are",
"stored",
"in",
"BlockStore",
"under",
"a",
"subdir",
"of",
"its",
"{",
"@link",
"StorageDir",
"}",
"the",
"subdir",
"is",
"tmpFolder",
"/",
"sessionId",
... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/AbstractBlockMeta.java#L43-L49 |
dhemery/hartley | src/main/java/com/dhemery/expressing/Expressive.java | Expressive.waitUntil | public <S> void waitUntil(S subject, Feature<? super S, Boolean> feature) {
waitUntil(subject, feature, eventually(), isQuietlyTrue());
} | java | public <S> void waitUntil(S subject, Feature<? super S, Boolean> feature) {
waitUntil(subject, feature, eventually(), isQuietlyTrue());
} | [
"public",
"<",
"S",
">",
"void",
"waitUntil",
"(",
"S",
"subject",
",",
"Feature",
"<",
"?",
"super",
"S",
",",
"Boolean",
">",
"feature",
")",
"{",
"waitUntil",
"(",
"subject",
",",
"feature",
",",
"eventually",
"(",
")",
",",
"isQuietlyTrue",
"(",
... | Wait until a polled sample of the feature is {@code true}.
Uses a default ticker. | [
"Wait",
"until",
"a",
"polled",
"sample",
"of",
"the",
"feature",
"is",
"{"
] | train | https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/Expressive.java#L230-L232 |
byoutline/CachedField | cachedfield/src/main/java/com/byoutline/cachedfield/internal/CachedValue.java | CachedValue.addStateListener | public synchronized void addStateListener(@Nonnull EndpointStateListener<VALUE_TYPE, ARG_TYPE> listener) throws IllegalArgumentException {
checkListenerNonNull(listener);
fieldStateListeners.add(listener);
if (informStateListenerOnAdd) {
informStateListener(getStateAndValue(), listener);
}
} | java | public synchronized void addStateListener(@Nonnull EndpointStateListener<VALUE_TYPE, ARG_TYPE> listener) throws IllegalArgumentException {
checkListenerNonNull(listener);
fieldStateListeners.add(listener);
if (informStateListenerOnAdd) {
informStateListener(getStateAndValue(), listener);
}
} | [
"public",
"synchronized",
"void",
"addStateListener",
"(",
"@",
"Nonnull",
"EndpointStateListener",
"<",
"VALUE_TYPE",
",",
"ARG_TYPE",
">",
"listener",
")",
"throws",
"IllegalArgumentException",
"{",
"checkListenerNonNull",
"(",
"listener",
")",
";",
"fieldStateListene... | Register listener that will be informed each time {@link FieldState}
changes.
@param listener
@throws IllegalArgumentException if listener is null | [
"Register",
"listener",
"that",
"will",
"be",
"informed",
"each",
"time",
"{",
"@link",
"FieldState",
"}",
"changes",
"."
] | train | https://github.com/byoutline/CachedField/blob/73d83072cdca22d2b3f5b3d60a93b8a26d9513e6/cachedfield/src/main/java/com/byoutline/cachedfield/internal/CachedValue.java#L130-L136 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.booleanPath | public static BooleanPath booleanPath(Path<?> parent, String property) {
return new BooleanPath(PathMetadataFactory.forProperty(parent, property));
} | java | public static BooleanPath booleanPath(Path<?> parent, String property) {
return new BooleanPath(PathMetadataFactory.forProperty(parent, property));
} | [
"public",
"static",
"BooleanPath",
"booleanPath",
"(",
"Path",
"<",
"?",
">",
"parent",
",",
"String",
"property",
")",
"{",
"return",
"new",
"BooleanPath",
"(",
"PathMetadataFactory",
".",
"forProperty",
"(",
"parent",
",",
"property",
")",
")",
";",
"}"
] | Create a new Path expression
@param parent parent path
@param property property name
@return property path | [
"Create",
"a",
"new",
"Path",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L1537-L1539 |
ACRA/acra | acra-core/src/main/java/org/acra/collector/SharedPreferencesCollector.java | SharedPreferencesCollector.filteredKey | private boolean filteredKey(@NonNull CoreConfiguration config, @NonNull String key) {
for (String regex : config.excludeMatchingSharedPreferencesKeys()) {
if (key.matches(regex)) {
return true;
}
}
return false;
} | java | private boolean filteredKey(@NonNull CoreConfiguration config, @NonNull String key) {
for (String regex : config.excludeMatchingSharedPreferencesKeys()) {
if (key.matches(regex)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"filteredKey",
"(",
"@",
"NonNull",
"CoreConfiguration",
"config",
",",
"@",
"NonNull",
"String",
"key",
")",
"{",
"for",
"(",
"String",
"regex",
":",
"config",
".",
"excludeMatchingSharedPreferencesKeys",
"(",
")",
")",
"{",
"if",
"(",
... | Checks if the key matches one of the patterns provided by the developer
to exclude some preferences from reports.
@param key the name of the preference to be checked
@return true if the key has to be excluded from reports. | [
"Checks",
"if",
"the",
"key",
"matches",
"one",
"of",
"the",
"patterns",
"provided",
"by",
"the",
"developer",
"to",
"exclude",
"some",
"preferences",
"from",
"reports",
"."
] | train | https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/SharedPreferencesCollector.java#L117-L124 |
Waikato/moa | moa/src/main/java/moa/classifiers/rules/AbstractAMRules.java | AbstractAMRules.isAnomaly | private boolean isAnomaly(Instance instance, Rule rule) {
//AMRUles is equipped with anomaly detection. If on, compute the anomaly value.
boolean isAnomaly = false;
if (this.noAnomalyDetectionOption.isSet() == false){
if (rule.getInstancesSeen() >= this.anomalyNumInstThresholdOption.getValue()) {
isAnomaly = rule.isAnomaly(instance,
this.univariateAnomalyprobabilityThresholdOption.getValue(),
this.multivariateAnomalyProbabilityThresholdOption.getValue(),
this.anomalyNumInstThresholdOption.getValue());
}
}
return isAnomaly;
} | java | private boolean isAnomaly(Instance instance, Rule rule) {
//AMRUles is equipped with anomaly detection. If on, compute the anomaly value.
boolean isAnomaly = false;
if (this.noAnomalyDetectionOption.isSet() == false){
if (rule.getInstancesSeen() >= this.anomalyNumInstThresholdOption.getValue()) {
isAnomaly = rule.isAnomaly(instance,
this.univariateAnomalyprobabilityThresholdOption.getValue(),
this.multivariateAnomalyProbabilityThresholdOption.getValue(),
this.anomalyNumInstThresholdOption.getValue());
}
}
return isAnomaly;
} | [
"private",
"boolean",
"isAnomaly",
"(",
"Instance",
"instance",
",",
"Rule",
"rule",
")",
"{",
"//AMRUles is equipped with anomaly detection. If on, compute the anomaly value. \t\t\t",
"boolean",
"isAnomaly",
"=",
"false",
";",
"if",
"(",
"this",
".",
"noAnomalyDetectionOpt... | Method to verify if the instance is an anomaly.
@param instance
@param rule
@return | [
"Method",
"to",
"verify",
"if",
"the",
"instance",
"is",
"an",
"anomaly",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/rules/AbstractAMRules.java#L266-L278 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java | MutableRoaringArray.appendCopiesUntil | protected void appendCopiesUntil(PointableRoaringArray highLowContainer, short stoppingKey) {
final int stopKey = toIntUnsigned(stoppingKey);
MappeableContainerPointer cp = highLowContainer.getContainerPointer();
while (cp.hasContainer()) {
if (toIntUnsigned(cp.key()) >= stopKey) {
break;
}
extendArray(1);
this.keys[this.size] = cp.key();
this.values[this.size] = cp.getContainer().clone();
this.size++;
cp.advance();
}
} | java | protected void appendCopiesUntil(PointableRoaringArray highLowContainer, short stoppingKey) {
final int stopKey = toIntUnsigned(stoppingKey);
MappeableContainerPointer cp = highLowContainer.getContainerPointer();
while (cp.hasContainer()) {
if (toIntUnsigned(cp.key()) >= stopKey) {
break;
}
extendArray(1);
this.keys[this.size] = cp.key();
this.values[this.size] = cp.getContainer().clone();
this.size++;
cp.advance();
}
} | [
"protected",
"void",
"appendCopiesUntil",
"(",
"PointableRoaringArray",
"highLowContainer",
",",
"short",
"stoppingKey",
")",
"{",
"final",
"int",
"stopKey",
"=",
"toIntUnsigned",
"(",
"stoppingKey",
")",
";",
"MappeableContainerPointer",
"cp",
"=",
"highLowContainer",
... | Append copies of the values from another array, from the start
@param highLowContainer the other array
@param stoppingKey any equal or larger key in other array will terminate copying | [
"Append",
"copies",
"of",
"the",
"values",
"from",
"another",
"array",
"from",
"the",
"start"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java#L166-L179 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/ReportResourcesImpl.java | ReportResourcesImpl.getReport | public Report getReport(long reportId, EnumSet<ReportInclusion> includes, Integer pageSize, Integer page) throws SmartsheetException{
return this.getReport(reportId, includes, pageSize, page, null);
} | java | public Report getReport(long reportId, EnumSet<ReportInclusion> includes, Integer pageSize, Integer page) throws SmartsheetException{
return this.getReport(reportId, includes, pageSize, page, null);
} | [
"public",
"Report",
"getReport",
"(",
"long",
"reportId",
",",
"EnumSet",
"<",
"ReportInclusion",
">",
"includes",
",",
"Integer",
"pageSize",
",",
"Integer",
"page",
")",
"throws",
"SmartsheetException",
"{",
"return",
"this",
".",
"getReport",
"(",
"reportId",... | Get a report.
It mirrors to the following Smartsheet REST API method: GET /reports/{id}
Exceptions:
InvalidRequestException : if there is any problem with the REST API request
AuthorizationException : if there is any problem with the REST API authorization(access token)
ResourceNotFoundException : if the resource can not be found
ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
SmartsheetRestException : if there is any other REST API related error occurred during the operation
SmartsheetException : if there is any other error occurred during the operation
@param reportId the folder id
@param includes the optional objects to include in response
@param pageSize Number of rows per page
@param page page number to return
@return the report (note that if there is no such resource, this method will throw ResourceNotFoundException
rather than returning null)
@throws SmartsheetException the smartsheet exception | [
"Get",
"a",
"report",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/ReportResourcesImpl.java#L97-L99 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/FileSystem.java | FileSystem.listLocatedBlockStatus | public RemoteIterator<LocatedBlockFileStatus> listLocatedBlockStatus(
final Path f,
final PathFilter filter)
throws FileNotFoundException, IOException {
return new RemoteIterator<LocatedBlockFileStatus>() {
private final FileStatus[] stats;
private int i = 0;
{ // initializer
stats = listStatus(f, filter);
if (stats == null) {
throw new FileNotFoundException( "File " + f + " does not exist.");
}
}
@Override
public boolean hasNext() {
return i<stats.length;
}
@Override
public LocatedBlockFileStatus next() throws IOException {
if (!hasNext()) {
throw new NoSuchElementException("No more entry in " + f);
}
FileStatus result = stats[i++];
BlockAndLocation[] locs = null;
if (!result.isDir()) {
String[] name = { "localhost:50010" };
String[] host = { "localhost" };
// create a dummy blockandlocation
locs = new BlockAndLocation[] {
new BlockAndLocation(0L, 0L, name, host,
new String[0], 0, result.getLen(), false) };
}
return new LocatedBlockFileStatus(result, locs, false);
}
};
} | java | public RemoteIterator<LocatedBlockFileStatus> listLocatedBlockStatus(
final Path f,
final PathFilter filter)
throws FileNotFoundException, IOException {
return new RemoteIterator<LocatedBlockFileStatus>() {
private final FileStatus[] stats;
private int i = 0;
{ // initializer
stats = listStatus(f, filter);
if (stats == null) {
throw new FileNotFoundException( "File " + f + " does not exist.");
}
}
@Override
public boolean hasNext() {
return i<stats.length;
}
@Override
public LocatedBlockFileStatus next() throws IOException {
if (!hasNext()) {
throw new NoSuchElementException("No more entry in " + f);
}
FileStatus result = stats[i++];
BlockAndLocation[] locs = null;
if (!result.isDir()) {
String[] name = { "localhost:50010" };
String[] host = { "localhost" };
// create a dummy blockandlocation
locs = new BlockAndLocation[] {
new BlockAndLocation(0L, 0L, name, host,
new String[0], 0, result.getLen(), false) };
}
return new LocatedBlockFileStatus(result, locs, false);
}
};
} | [
"public",
"RemoteIterator",
"<",
"LocatedBlockFileStatus",
">",
"listLocatedBlockStatus",
"(",
"final",
"Path",
"f",
",",
"final",
"PathFilter",
"filter",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"return",
"new",
"RemoteIterator",
"<",
"Located... | Listing a directory
The returned results include its blocks and locations if it is a file
The results are filtered by the given path filter
@param f a path
@param filter a path filter
@return an iterator that traverses statuses of the files/directories
in the given path
@throws FileNotFoundException if <code>f</code> does not exist
@throws IOException if any I/O error occurred | [
"Listing",
"a",
"directory",
"The",
"returned",
"results",
"include",
"its",
"blocks",
"and",
"locations",
"if",
"it",
"is",
"a",
"file",
"The",
"results",
"are",
"filtered",
"by",
"the",
"given",
"path",
"filter"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L1123-L1162 |
Impetus/Kundera | src/kundera-mongo/src/main/java/com/impetus/client/mongodb/DefaultMongoDBDataHandler.java | DefaultMongoDBDataHandler.createGFSInputFile | private GridFSInputFile createGFSInputFile(GridFS gfs, Object entity, Field f)
{
Object obj = PropertyAccessorHelper.getObject(entity, f);
GridFSInputFile gridFSInputFile = null;
if (f.getType().isAssignableFrom(byte[].class))
gridFSInputFile = gfs.createFile((byte[]) obj);
else if (f.getType().isAssignableFrom(File.class))
{
try
{
gridFSInputFile = gfs.createFile((File) obj);
}
catch (IOException e)
{
log.error("Error while creating GridFS file for \"" + f.getName() + "\". Caused by: ", e);
throw new KunderaException("Error while creating GridFS file for \"" + f.getName() + "\". Caused by: ",
e);
}
}
else
new UnsupportedOperationException(f.getType().getSimpleName() + " is unsupported Lob object");
return gridFSInputFile;
} | java | private GridFSInputFile createGFSInputFile(GridFS gfs, Object entity, Field f)
{
Object obj = PropertyAccessorHelper.getObject(entity, f);
GridFSInputFile gridFSInputFile = null;
if (f.getType().isAssignableFrom(byte[].class))
gridFSInputFile = gfs.createFile((byte[]) obj);
else if (f.getType().isAssignableFrom(File.class))
{
try
{
gridFSInputFile = gfs.createFile((File) obj);
}
catch (IOException e)
{
log.error("Error while creating GridFS file for \"" + f.getName() + "\". Caused by: ", e);
throw new KunderaException("Error while creating GridFS file for \"" + f.getName() + "\". Caused by: ",
e);
}
}
else
new UnsupportedOperationException(f.getType().getSimpleName() + " is unsupported Lob object");
return gridFSInputFile;
} | [
"private",
"GridFSInputFile",
"createGFSInputFile",
"(",
"GridFS",
"gfs",
",",
"Object",
"entity",
",",
"Field",
"f",
")",
"{",
"Object",
"obj",
"=",
"PropertyAccessorHelper",
".",
"getObject",
"(",
"entity",
",",
"f",
")",
";",
"GridFSInputFile",
"gridFSInputFi... | Creates the GFS Input file.
@param gfs
the gfs
@param entity
the entity
@param f
the f
@return the grid fs input file | [
"Creates",
"the",
"GFS",
"Input",
"file",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-mongo/src/main/java/com/impetus/client/mongodb/DefaultMongoDBDataHandler.java#L416-L438 |
RestComm/jss7 | m3ua/impl/src/main/java/org/restcomm/protocols/ss7/m3ua/impl/M3UAManagementImpl.java | M3UAManagementImpl.startAsp | public void startAsp(String aspName) throws Exception {
AspFactoryImpl aspFactoryImpl = this.getAspFactory(aspName);
if (aspFactoryImpl == null) {
throw new Exception(String.format(M3UAOAMMessages.NO_ASP_FOUND, aspName));
}
if (aspFactoryImpl.getStatus()) {
throw new Exception(String.format(M3UAOAMMessages.ASP_ALREADY_STARTED, aspName));
}
if (aspFactoryImpl.aspList.size() == 0) {
throw new Exception(String.format(M3UAOAMMessages.ASP_NOT_ASSIGNED_TO_AS, aspName));
}
aspFactoryImpl.start();
this.store();
for (FastList.Node<M3UAManagementEventListener> n = this.managementEventListeners.head(), end = this.managementEventListeners
.tail(); (n = n.getNext()) != end;) {
M3UAManagementEventListener m3uaManagementEventListener = n.getValue();
try {
m3uaManagementEventListener.onAspFactoryStarted(aspFactoryImpl);
} catch (Throwable ee) {
logger.error("Exception while invoking onAspFactoryStarted", ee);
}
}
} | java | public void startAsp(String aspName) throws Exception {
AspFactoryImpl aspFactoryImpl = this.getAspFactory(aspName);
if (aspFactoryImpl == null) {
throw new Exception(String.format(M3UAOAMMessages.NO_ASP_FOUND, aspName));
}
if (aspFactoryImpl.getStatus()) {
throw new Exception(String.format(M3UAOAMMessages.ASP_ALREADY_STARTED, aspName));
}
if (aspFactoryImpl.aspList.size() == 0) {
throw new Exception(String.format(M3UAOAMMessages.ASP_NOT_ASSIGNED_TO_AS, aspName));
}
aspFactoryImpl.start();
this.store();
for (FastList.Node<M3UAManagementEventListener> n = this.managementEventListeners.head(), end = this.managementEventListeners
.tail(); (n = n.getNext()) != end;) {
M3UAManagementEventListener m3uaManagementEventListener = n.getValue();
try {
m3uaManagementEventListener.onAspFactoryStarted(aspFactoryImpl);
} catch (Throwable ee) {
logger.error("Exception while invoking onAspFactoryStarted", ee);
}
}
} | [
"public",
"void",
"startAsp",
"(",
"String",
"aspName",
")",
"throws",
"Exception",
"{",
"AspFactoryImpl",
"aspFactoryImpl",
"=",
"this",
".",
"getAspFactory",
"(",
"aspName",
")",
";",
"if",
"(",
"aspFactoryImpl",
"==",
"null",
")",
"{",
"throw",
"new",
"Ex... | This method should be called by management to start the ASP
@param aspName The name of the ASP to be started
@throws Exception | [
"This",
"method",
"should",
"be",
"called",
"by",
"management",
"to",
"start",
"the",
"ASP"
] | train | https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/m3ua/impl/src/main/java/org/restcomm/protocols/ss7/m3ua/impl/M3UAManagementImpl.java#L777-L805 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.getAnnotations | private List<Content> getAnnotations(int indent, AnnotationDesc[] descList, boolean linkBreak) {
return getAnnotations(indent, descList, linkBreak, true);
} | java | private List<Content> getAnnotations(int indent, AnnotationDesc[] descList, boolean linkBreak) {
return getAnnotations(indent, descList, linkBreak, true);
} | [
"private",
"List",
"<",
"Content",
">",
"getAnnotations",
"(",
"int",
"indent",
",",
"AnnotationDesc",
"[",
"]",
"descList",
",",
"boolean",
"linkBreak",
")",
"{",
"return",
"getAnnotations",
"(",
"indent",
",",
"descList",
",",
"linkBreak",
",",
"true",
")"... | Return the string representations of the annotation types for
the given doc.
@param indent the number of extra spaces to indent the annotations.
@param descList the array of {@link AnnotationDesc}.
@param linkBreak if true, add new line between each member value.
@return an array of strings representing the annotations being
documented. | [
"Return",
"the",
"string",
"representations",
"of",
"the",
"annotation",
"types",
"for",
"the",
"given",
"doc",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L1927-L1929 |
wcm-io-caravan/caravan-hal | docs-maven-plugin/src/main/java/io/wcm/caravan/maven/plugins/haldocs/GenerateHalDocsJsonMojo.java | GenerateHalDocsJsonMojo.getStaticFieldValue | @SuppressWarnings("unchecked")
private <T> T getStaticFieldValue(JavaClass javaClazz, JavaField javaField, ClassLoader compileClassLoader, Class<T> fieldType) {
try {
Class<?> clazz = compileClassLoader.loadClass(javaClazz.getFullyQualifiedName());
Field field = clazz.getField(javaField.getName());
return (T)field.get(fieldType);
}
catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
throw new RuntimeException("Unable to get contanst value of field '" + javaClazz.getName() + "#" + javaField.getName() + ":\n" + ex.getMessage(), ex);
}
} | java | @SuppressWarnings("unchecked")
private <T> T getStaticFieldValue(JavaClass javaClazz, JavaField javaField, ClassLoader compileClassLoader, Class<T> fieldType) {
try {
Class<?> clazz = compileClassLoader.loadClass(javaClazz.getFullyQualifiedName());
Field field = clazz.getField(javaField.getName());
return (T)field.get(fieldType);
}
catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
throw new RuntimeException("Unable to get contanst value of field '" + javaClazz.getName() + "#" + javaField.getName() + ":\n" + ex.getMessage(), ex);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"<",
"T",
">",
"T",
"getStaticFieldValue",
"(",
"JavaClass",
"javaClazz",
",",
"JavaField",
"javaField",
",",
"ClassLoader",
"compileClassLoader",
",",
"Class",
"<",
"T",
">",
"fieldType",
")",
"{",
... | Get constant field value.
@param javaClazz QDox class
@param javaField QDox field
@param compileClassLoader Classloader for compile dependencies
@param fieldType Field type
@return Value | [
"Get",
"constant",
"field",
"value",
"."
] | train | https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/docs-maven-plugin/src/main/java/io/wcm/caravan/maven/plugins/haldocs/GenerateHalDocsJsonMojo.java#L329-L339 |
citrusframework/citrus | modules/citrus-http/src/main/java/com/consol/citrus/http/interceptor/LoggingClientInterceptor.java | LoggingClientInterceptor.getRequestContent | private String getRequestContent(HttpRequest request, String body) {
StringBuilder builder = new StringBuilder();
builder.append(request.getMethod());
builder.append(" ");
builder.append(request.getURI());
builder.append(NEWLINE);
appendHeaders(request.getHeaders(), builder);
builder.append(NEWLINE);
builder.append(body);
return builder.toString();
} | java | private String getRequestContent(HttpRequest request, String body) {
StringBuilder builder = new StringBuilder();
builder.append(request.getMethod());
builder.append(" ");
builder.append(request.getURI());
builder.append(NEWLINE);
appendHeaders(request.getHeaders(), builder);
builder.append(NEWLINE);
builder.append(body);
return builder.toString();
} | [
"private",
"String",
"getRequestContent",
"(",
"HttpRequest",
"request",
",",
"String",
"body",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"request",
".",
"getMethod",
"(",
")",
")",
";",
... | Builds request content string from request and body.
@param request
@param body
@return | [
"Builds",
"request",
"content",
"string",
"from",
"request",
"and",
"body",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-http/src/main/java/com/consol/citrus/http/interceptor/LoggingClientInterceptor.java#L99-L113 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/util/ElementHelper.java | ElementHelper.attachProperties | public static void attachProperties(final TitanVertex vertex, final Object... propertyKeyValues) {
if (null == vertex)
throw Graph.Exceptions.argumentCanNotBeNull("vertex");
for (int i = 0; i < propertyKeyValues.length; i = i + 2) {
if (!propertyKeyValues[i].equals(T.id) && !propertyKeyValues[i].equals(T.label))
vertex.property((String) propertyKeyValues[i], propertyKeyValues[i + 1]);
}
} | java | public static void attachProperties(final TitanVertex vertex, final Object... propertyKeyValues) {
if (null == vertex)
throw Graph.Exceptions.argumentCanNotBeNull("vertex");
for (int i = 0; i < propertyKeyValues.length; i = i + 2) {
if (!propertyKeyValues[i].equals(T.id) && !propertyKeyValues[i].equals(T.label))
vertex.property((String) propertyKeyValues[i], propertyKeyValues[i + 1]);
}
} | [
"public",
"static",
"void",
"attachProperties",
"(",
"final",
"TitanVertex",
"vertex",
",",
"final",
"Object",
"...",
"propertyKeyValues",
")",
"{",
"if",
"(",
"null",
"==",
"vertex",
")",
"throw",
"Graph",
".",
"Exceptions",
".",
"argumentCanNotBeNull",
"(",
... | This is essentially an adjusted copy&paste from TinkerPop's ElementHelper class.
The reason for copying it is so that we can determine the cardinality of a property key based on
Titan's schema which is tied to this particular transaction and not the graph.
@param vertex
@param propertyKeyValues | [
"This",
"is",
"essentially",
"an",
"adjusted",
"copy&paste",
"from",
"TinkerPop",
"s",
"ElementHelper",
"class",
".",
"The",
"reason",
"for",
"copying",
"it",
"is",
"so",
"that",
"we",
"can",
"determine",
"the",
"cardinality",
"of",
"a",
"property",
"key",
"... | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/util/ElementHelper.java#L60-L68 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/CreatorUtils.java | CreatorUtils.getAnnotation | public static <T extends Annotation> Optional<T> getAnnotation( String annotation, List<? extends HasAnnotations>
hasAnnotationsList ) {
try {
Class clazz = Class.forName( annotation );
return getAnnotation( clazz, hasAnnotationsList );
} catch ( ClassNotFoundException e ) {
return Optional.absent();
}
} | java | public static <T extends Annotation> Optional<T> getAnnotation( String annotation, List<? extends HasAnnotations>
hasAnnotationsList ) {
try {
Class clazz = Class.forName( annotation );
return getAnnotation( clazz, hasAnnotationsList );
} catch ( ClassNotFoundException e ) {
return Optional.absent();
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Annotation",
">",
"Optional",
"<",
"T",
">",
"getAnnotation",
"(",
"String",
"annotation",
",",
"List",
"<",
"?",
"extends",
"HasAnnotations",
">",
"hasAnnotationsList",
")",
"{",
"try",
"{",
"Class",
"clazz",
"=",
... | Returns the first occurence of the annotation found on the types
@param annotation the annotation
@param hasAnnotationsList the types
@return the first occurence of the annotation found on the types
@param <T> a T object. | [
"Returns",
"the",
"first",
"occurence",
"of",
"the",
"annotation",
"found",
"on",
"the",
"types"
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/CreatorUtils.java#L124-L132 |
libgdx/box2dlights | src/box2dLight/RayHandler.java | RayHandler.setAmbientLight | public void setAmbientLight(float r, float g, float b, float a) {
this.ambientLight.set(r, g, b, a);
} | java | public void setAmbientLight(float r, float g, float b, float a) {
this.ambientLight.set(r, g, b, a);
} | [
"public",
"void",
"setAmbientLight",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"this",
".",
"ambientLight",
".",
"set",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
";",
"}"
] | Sets ambient light color.
Specifies how shadows colored and their brightness.
<p>Default = Color(0, 0, 0, 0)
@param r
shadows color red component
@param g
shadows color green component
@param b
shadows color blue component
@param a
shadows brightness component
@see #setAmbientLight(float)
@see #setAmbientLight(Color) | [
"Sets",
"ambient",
"light",
"color",
".",
"Specifies",
"how",
"shadows",
"colored",
"and",
"their",
"brightness",
"."
] | train | https://github.com/libgdx/box2dlights/blob/08cf93a41464f71d32475aaa2fe280dc6af78ff3/src/box2dLight/RayHandler.java#L530-L532 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2017_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2017_06_01_preview/implementation/RegistriesInner.java | RegistriesInner.beginCreateAsync | public Observable<RegistryInner> beginCreateAsync(String resourceGroupName, String registryName, RegistryInner registry) {
return beginCreateWithServiceResponseAsync(resourceGroupName, registryName, registry).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | java | public Observable<RegistryInner> beginCreateAsync(String resourceGroupName, String registryName, RegistryInner registry) {
return beginCreateWithServiceResponseAsync(resourceGroupName, registryName, registry).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RegistryInner",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"RegistryInner",
"registry",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryN... | Creates a container registry with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param registry The parameters for creating a container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RegistryInner object | [
"Creates",
"a",
"container",
"registry",
"with",
"the",
"specified",
"parameters",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2017_06_01_preview/implementation/RegistriesInner.java#L417-L424 |
Netflix/denominator | route53/src/main/java/denominator/route53/Route53ZoneApi.java | Route53ZoneApi.deleteEverythingExceptNSAndSOA | private void deleteEverythingExceptNSAndSOA(String id, String name) {
List<ActionOnResourceRecordSet> deletes = new ArrayList<ActionOnResourceRecordSet>();
ResourceRecordSetList page = api.listResourceRecordSets(id);
while (!page.isEmpty()) {
for (ResourceRecordSet<?> rrset : page) {
if (rrset.type().equals("SOA") || rrset.type().equals("NS") && rrset.name().equals(name)) {
continue;
}
deletes.add(ActionOnResourceRecordSet.delete(rrset));
}
if (!deletes.isEmpty()) {
api.changeResourceRecordSets(id, deletes);
}
if (page.next == null) {
page.clear();
} else {
deletes.clear();
page = api.listResourceRecordSets(id, page.next.name, page.next.type, page.next.identifier);
}
}
} | java | private void deleteEverythingExceptNSAndSOA(String id, String name) {
List<ActionOnResourceRecordSet> deletes = new ArrayList<ActionOnResourceRecordSet>();
ResourceRecordSetList page = api.listResourceRecordSets(id);
while (!page.isEmpty()) {
for (ResourceRecordSet<?> rrset : page) {
if (rrset.type().equals("SOA") || rrset.type().equals("NS") && rrset.name().equals(name)) {
continue;
}
deletes.add(ActionOnResourceRecordSet.delete(rrset));
}
if (!deletes.isEmpty()) {
api.changeResourceRecordSets(id, deletes);
}
if (page.next == null) {
page.clear();
} else {
deletes.clear();
page = api.listResourceRecordSets(id, page.next.name, page.next.type, page.next.identifier);
}
}
} | [
"private",
"void",
"deleteEverythingExceptNSAndSOA",
"(",
"String",
"id",
",",
"String",
"name",
")",
"{",
"List",
"<",
"ActionOnResourceRecordSet",
">",
"deletes",
"=",
"new",
"ArrayList",
"<",
"ActionOnResourceRecordSet",
">",
"(",
")",
";",
"ResourceRecordSetList... | Works through the zone, deleting each page of rrsets, except the zone's SOA and the NS rrsets.
Once the zone is cleared, it can be deleted.
<p/>Users can modify the zone's SOA and NS rrsets, but they cannot be deleted except via
deleting the zone. | [
"Works",
"through",
"the",
"zone",
"deleting",
"each",
"page",
"of",
"rrsets",
"except",
"the",
"zone",
"s",
"SOA",
"and",
"the",
"NS",
"rrsets",
".",
"Once",
"the",
"zone",
"is",
"cleared",
"it",
"can",
"be",
"deleted",
"."
] | train | https://github.com/Netflix/denominator/blob/c565e3b8c6043051252e0947029511f9ac5d306f/route53/src/main/java/denominator/route53/Route53ZoneApi.java#L101-L121 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/vod/VodClient.java | VodClient.stopMediaResource | public StopMediaResourceResponse stopMediaResource(StopMediaResourceRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.PUT, request, PATH_MEDIA, request.getMediaId());
internalRequest.addParameter(PARA_DISABLE, null);
return invokeHttpClient(internalRequest, StopMediaResourceResponse.class);
} | java | public StopMediaResourceResponse stopMediaResource(StopMediaResourceRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.PUT, request, PATH_MEDIA, request.getMediaId());
internalRequest.addParameter(PARA_DISABLE, null);
return invokeHttpClient(internalRequest, StopMediaResourceResponse.class);
} | [
"public",
"StopMediaResourceResponse",
"stopMediaResource",
"(",
"StopMediaResourceRequest",
"request",
")",
"{",
"checkStringNotEmpty",
"(",
"request",
".",
"getMediaId",
"(",
")",
",",
"\"Media ID should not be null or empty!\"",
")",
";",
"InternalRequest",
"internalReques... | Stop the specific media resource managed by VOD service, so that it can not be access and played. Disabled media
resource can be recovered by method <code>publishMediaResource()</code> later.
<p>
The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair.
@param request The request object containing all the options on how to
@return empty response will be returned | [
"Stop",
"the",
"specific",
"media",
"resource",
"managed",
"by",
"VOD",
"service",
"so",
"that",
"it",
"can",
"not",
"be",
"access",
"and",
"played",
".",
"Disabled",
"media",
"resource",
"can",
"be",
"recovered",
"by",
"method",
"<code",
">",
"publishMediaR... | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/vod/VodClient.java#L680-L687 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java | EncodingUtils.verifyJwsSignature | @SneakyThrows
public static byte[] verifyJwsSignature(final Key signingKey, final byte[] value) {
val asString = new String(value, StandardCharsets.UTF_8);
return verifyJwsSignature(signingKey, asString);
} | java | @SneakyThrows
public static byte[] verifyJwsSignature(final Key signingKey, final byte[] value) {
val asString = new String(value, StandardCharsets.UTF_8);
return verifyJwsSignature(signingKey, asString);
} | [
"@",
"SneakyThrows",
"public",
"static",
"byte",
"[",
"]",
"verifyJwsSignature",
"(",
"final",
"Key",
"signingKey",
",",
"final",
"byte",
"[",
"]",
"value",
")",
"{",
"val",
"asString",
"=",
"new",
"String",
"(",
"value",
",",
"StandardCharsets",
".",
"UTF... | Verify jws signature byte [ ].
@param value the value
@param signingKey the signing key
@return the byte [ ] | [
"Verify",
"jws",
"signature",
"byte",
"[",
"]",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java#L296-L300 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/BandwidthClient.java | BandwidthClient.buildMethod | protected HttpUriRequest buildMethod(final String method, final String path, final Map<String, Object> params) {
if (StringUtils.equalsIgnoreCase(method, HttpGet.METHOD_NAME)) {
return generateGetRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpPost.METHOD_NAME)) {
return generatePostRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpPut.METHOD_NAME)) {
return generatePutRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpDelete.METHOD_NAME)) {
return generateDeleteRequest(path);
} else {
throw new RuntimeException("Must not be here.");
}
} | java | protected HttpUriRequest buildMethod(final String method, final String path, final Map<String, Object> params) {
if (StringUtils.equalsIgnoreCase(method, HttpGet.METHOD_NAME)) {
return generateGetRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpPost.METHOD_NAME)) {
return generatePostRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpPut.METHOD_NAME)) {
return generatePutRequest(path, params);
} else if (StringUtils.equalsIgnoreCase(method, HttpDelete.METHOD_NAME)) {
return generateDeleteRequest(path);
} else {
throw new RuntimeException("Must not be here.");
}
} | [
"protected",
"HttpUriRequest",
"buildMethod",
"(",
"final",
"String",
"method",
",",
"final",
"String",
"path",
",",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"params",
")",
"{",
"if",
"(",
"StringUtils",
".",
"equalsIgnoreCase",
"(",
"method",
",",... | Helper method that builds the request to the server.
@param method the method.
@param path the path.
@param params the parameters.
@return the request. | [
"Helper",
"method",
"that",
"builds",
"the",
"request",
"to",
"the",
"server",
"."
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L571-L583 |
marvinlabs/android-intents | library/src/main/java/com/marvinlabs/intents/MediaIntents.java | MediaIntents.newPlayMediaIntent | public static Intent newPlayMediaIntent(Uri uri, String type) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, type);
return intent;
} | java | public static Intent newPlayMediaIntent(Uri uri, String type) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, type);
return intent;
} | [
"public",
"static",
"Intent",
"newPlayMediaIntent",
"(",
"Uri",
"uri",
",",
"String",
"type",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"Intent",
".",
"ACTION_VIEW",
")",
";",
"intent",
".",
"setDataAndType",
"(",
"uri",
",",
"type",
")",
... | Open the media player to play the given media Uri
@param uri The Uri of the media to play.
@param type The mime type
@return the intent | [
"Open",
"the",
"media",
"player",
"to",
"play",
"the",
"given",
"media",
"Uri"
] | train | https://github.com/marvinlabs/android-intents/blob/33e79c825188b6a97601869522533cc825801f6e/library/src/main/java/com/marvinlabs/intents/MediaIntents.java#L182-L186 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsfContainer_fat_2.3/fat/src/com/ibm/ws/jsf/container/fat/utils/JSFUtils.java | JSFUtils.createHttpUrl | public static URL createHttpUrl(LibertyServer server, String contextRoot, String path) throws Exception {
return new URL(createHttpUrlString(server, contextRoot, path));
} | java | public static URL createHttpUrl(LibertyServer server, String contextRoot, String path) throws Exception {
return new URL(createHttpUrlString(server, contextRoot, path));
} | [
"public",
"static",
"URL",
"createHttpUrl",
"(",
"LibertyServer",
"server",
",",
"String",
"contextRoot",
",",
"String",
"path",
")",
"throws",
"Exception",
"{",
"return",
"new",
"URL",
"(",
"createHttpUrlString",
"(",
"server",
",",
"contextRoot",
",",
"path",
... | Construct a URL for a test case so a request can be made.
@param server - The server that is under test, this is used to get the port and host name.
@param contextRoot - The context root of the application
@param path - Additional path information for the request.
@return - A fully formed URL.
@throws Exception | [
"Construct",
"a",
"URL",
"for",
"a",
"test",
"case",
"so",
"a",
"request",
"can",
"be",
"made",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsfContainer_fat_2.3/fat/src/com/ibm/ws/jsf/container/fat/utils/JSFUtils.java#L36-L38 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java | DefaultAsyncSearchQueryResult.fromHttp429 | public static AsyncSearchQueryResult fromHttp429(String payload) {
SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L);
SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d);
return new DefaultAsyncSearchQueryResult(
status,
Observable.<SearchQueryRow>error(new FtsServerOverloadException(payload)),
Observable.<FacetResult>empty(),
Observable.just(metrics)
);
} | java | public static AsyncSearchQueryResult fromHttp429(String payload) {
SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L);
SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d);
return new DefaultAsyncSearchQueryResult(
status,
Observable.<SearchQueryRow>error(new FtsServerOverloadException(payload)),
Observable.<FacetResult>empty(),
Observable.just(metrics)
);
} | [
"public",
"static",
"AsyncSearchQueryResult",
"fromHttp429",
"(",
"String",
"payload",
")",
"{",
"SearchStatus",
"status",
"=",
"new",
"DefaultSearchStatus",
"(",
"1L",
",",
"1L",
",",
"0L",
")",
";",
"SearchMetrics",
"metrics",
"=",
"new",
"DefaultSearchMetrics",... | Creates a result out of the http 429 response code if retry didn't work. | [
"Creates",
"a",
"result",
"out",
"of",
"the",
"http",
"429",
"response",
"code",
"if",
"retry",
"didn",
"t",
"work",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java#L305-L315 |
groupon/odo | proxyui/src/main/java/com/groupon/odo/controllers/EditController.java | EditController.removePathname | @RequestMapping(value = "api/edit/{profileId}/{pathId}", method = RequestMethod.DELETE)
public
@ResponseBody
String removePathname(Model model, @PathVariable int pathId, @PathVariable int profileId) {
editService.removePathnameFromProfile(pathId, profileId);
return null;
} | java | @RequestMapping(value = "api/edit/{profileId}/{pathId}", method = RequestMethod.DELETE)
public
@ResponseBody
String removePathname(Model model, @PathVariable int pathId, @PathVariable int profileId) {
editService.removePathnameFromProfile(pathId, profileId);
return null;
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"api/edit/{profileId}/{pathId}\"",
",",
"method",
"=",
"RequestMethod",
".",
"DELETE",
")",
"public",
"@",
"ResponseBody",
"String",
"removePathname",
"(",
"Model",
"model",
",",
"@",
"PathVariable",
"int",
"pathId",
","... | removes a pathname from a profile
@param model
@param pathId
@param profileId
@return | [
"removes",
"a",
"pathname",
"from",
"a",
"profile"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxyui/src/main/java/com/groupon/odo/controllers/EditController.java#L169-L175 |
apache/groovy | subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxEventListener.java | JmxEventListener.handleNotification | public void handleNotification(Notification notification, Object handback) {
Map event = (Map) handback;
if (event != null) {
Object del = event.get("managedObject");
Object callback = event.get("callback");
if (callback != null && callback instanceof Closure) {
Closure closure = (Closure) callback;
closure.setDelegate(del);
if (closure.getMaximumNumberOfParameters() == 1)
closure.call(buildOperationNotificationPacket(notification));
else closure.call();
}
}
} | java | public void handleNotification(Notification notification, Object handback) {
Map event = (Map) handback;
if (event != null) {
Object del = event.get("managedObject");
Object callback = event.get("callback");
if (callback != null && callback instanceof Closure) {
Closure closure = (Closure) callback;
closure.setDelegate(del);
if (closure.getMaximumNumberOfParameters() == 1)
closure.call(buildOperationNotificationPacket(notification));
else closure.call();
}
}
} | [
"public",
"void",
"handleNotification",
"(",
"Notification",
"notification",
",",
"Object",
"handback",
")",
"{",
"Map",
"event",
"=",
"(",
"Map",
")",
"handback",
";",
"if",
"(",
"event",
"!=",
"null",
")",
"{",
"Object",
"del",
"=",
"event",
".",
"get"... | This is the implemented method for NotificationListener. It is called by an event emitter to dispatch
JMX events to listeners. Here it handles internal JmxBuilder events.
@param notification the notification object passed to closure used to handle JmxBuilder events.
@param handback - In this case, the handback is the closure to execute when the event is handled. | [
"This",
"is",
"the",
"implemented",
"method",
"for",
"NotificationListener",
".",
"It",
"is",
"called",
"by",
"an",
"event",
"emitter",
"to",
"dispatch",
"JMX",
"events",
"to",
"listeners",
".",
"Here",
"it",
"handles",
"internal",
"JmxBuilder",
"events",
"."
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxEventListener.java#L56-L69 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/Backend.java | Backend.beginTransaction | public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException {
StoreTransaction tx = storeManagerLocking.beginTransaction(configuration);
// Cache
CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading());
// Index transactions
Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size());
for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) {
indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime));
}
return new BackendTransaction(cacheTx, configuration, storeFeatures,
edgeStore, indexStore, txLogStore,
maxReadTime, indexTx, threadPool);
} | java | public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException {
StoreTransaction tx = storeManagerLocking.beginTransaction(configuration);
// Cache
CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading());
// Index transactions
Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size());
for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) {
indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime));
}
return new BackendTransaction(cacheTx, configuration, storeFeatures,
edgeStore, indexStore, txLogStore,
maxReadTime, indexTx, threadPool);
} | [
"public",
"BackendTransaction",
"beginTransaction",
"(",
"TransactionConfiguration",
"configuration",
",",
"KeyInformation",
".",
"Retriever",
"indexKeyRetriever",
")",
"throws",
"BackendException",
"{",
"StoreTransaction",
"tx",
"=",
"storeManagerLocking",
".",
"beginTransac... | Opens a new transaction against all registered backend system wrapped in one {@link BackendTransaction}.
@return
@throws BackendException | [
"Opens",
"a",
"new",
"transaction",
"against",
"all",
"registered",
"backend",
"system",
"wrapped",
"in",
"one",
"{",
"@link",
"BackendTransaction",
"}",
"."
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/Backend.java#L523-L539 |
GoogleCloudPlatform/appengine-plugins-core | src/main/java/com/google/cloud/tools/managedcloudsdk/components/SdkUpdater.java | SdkUpdater.newUpdater | public static SdkUpdater newUpdater(OsInfo.Name osName, Path gcloudPath) {
switch (osName) {
case WINDOWS:
return new SdkUpdater(
gcloudPath,
CommandRunner.newRunner(),
new WindowsBundledPythonCopier(gcloudPath, CommandCaller.newCaller()));
default:
return new SdkUpdater(gcloudPath, CommandRunner.newRunner(), null);
}
} | java | public static SdkUpdater newUpdater(OsInfo.Name osName, Path gcloudPath) {
switch (osName) {
case WINDOWS:
return new SdkUpdater(
gcloudPath,
CommandRunner.newRunner(),
new WindowsBundledPythonCopier(gcloudPath, CommandCaller.newCaller()));
default:
return new SdkUpdater(gcloudPath, CommandRunner.newRunner(), null);
}
} | [
"public",
"static",
"SdkUpdater",
"newUpdater",
"(",
"OsInfo",
".",
"Name",
"osName",
",",
"Path",
"gcloudPath",
")",
"{",
"switch",
"(",
"osName",
")",
"{",
"case",
"WINDOWS",
":",
"return",
"new",
"SdkUpdater",
"(",
"gcloudPath",
",",
"CommandRunner",
".",... | Configure and create a new Updater instance.
@param gcloudPath path to gcloud in the Cloud SDK
@return a new configured Cloud SDK updater | [
"Configure",
"and",
"create",
"a",
"new",
"Updater",
"instance",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-plugins-core/blob/d22e9fa1103522409ab6fdfbf68c4a5a0bc5b97d/src/main/java/com/google/cloud/tools/managedcloudsdk/components/SdkUpdater.java#L75-L85 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java | TileDaoUtils.getZoomLevel | public static Long getZoomLevel(double[] widths, double[] heights,
List<TileMatrix> tileMatrices, double length) {
return getZoomLevel(widths, heights, tileMatrices, length, true);
} | java | public static Long getZoomLevel(double[] widths, double[] heights,
List<TileMatrix> tileMatrices, double length) {
return getZoomLevel(widths, heights, tileMatrices, length, true);
} | [
"public",
"static",
"Long",
"getZoomLevel",
"(",
"double",
"[",
"]",
"widths",
",",
"double",
"[",
"]",
"heights",
",",
"List",
"<",
"TileMatrix",
">",
"tileMatrices",
",",
"double",
"length",
")",
"{",
"return",
"getZoomLevel",
"(",
"widths",
",",
"height... | Get the zoom level for the provided width and height in the default units
@param widths
sorted widths
@param heights
sorted heights
@param tileMatrices
tile matrices
@param length
in default units
@return tile matrix zoom level | [
"Get",
"the",
"zoom",
"level",
"for",
"the",
"provided",
"width",
"and",
"height",
"in",
"the",
"default",
"units"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java#L59-L62 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/WorkspacePersistentDataManager.java | WorkspacePersistentDataManager.checkSameNameSibling | private void checkSameNameSibling(NodeData node, WorkspaceStorageConnection con, final Set<QPath> addedNodes)
throws RepositoryException
{
if (node.getQPath().getIndex() > 1)
{
// check if an older same-name sibling exists
// the check is actual for all operations including delete
final QPathEntry[] path = node.getQPath().getEntries();
final QPathEntry[] siblingPath = new QPathEntry[path.length];
final int li = path.length - 1;
System.arraycopy(path, 0, siblingPath, 0, li);
siblingPath[li] = new QPathEntry(path[li], path[li].getIndex() - 1);
if (addedNodes.contains(new QPath(siblingPath)))
{
// current changes log has the older same-name sibling
return;
}
else
{
// check in persistence
if (dataContainer.isCheckSNSNewConnection())
{
final WorkspaceStorageConnection acon = dataContainer.openConnection();
try
{
checkPersistedSNS(node, acon);
}
finally
{
acon.close();
}
}
else
{
checkPersistedSNS(node, con);
}
}
}
} | java | private void checkSameNameSibling(NodeData node, WorkspaceStorageConnection con, final Set<QPath> addedNodes)
throws RepositoryException
{
if (node.getQPath().getIndex() > 1)
{
// check if an older same-name sibling exists
// the check is actual for all operations including delete
final QPathEntry[] path = node.getQPath().getEntries();
final QPathEntry[] siblingPath = new QPathEntry[path.length];
final int li = path.length - 1;
System.arraycopy(path, 0, siblingPath, 0, li);
siblingPath[li] = new QPathEntry(path[li], path[li].getIndex() - 1);
if (addedNodes.contains(new QPath(siblingPath)))
{
// current changes log has the older same-name sibling
return;
}
else
{
// check in persistence
if (dataContainer.isCheckSNSNewConnection())
{
final WorkspaceStorageConnection acon = dataContainer.openConnection();
try
{
checkPersistedSNS(node, acon);
}
finally
{
acon.close();
}
}
else
{
checkPersistedSNS(node, con);
}
}
}
} | [
"private",
"void",
"checkSameNameSibling",
"(",
"NodeData",
"node",
",",
"WorkspaceStorageConnection",
"con",
",",
"final",
"Set",
"<",
"QPath",
">",
"addedNodes",
")",
"throws",
"RepositoryException",
"{",
"if",
"(",
"node",
".",
"getQPath",
"(",
")",
".",
"g... | Check if given node path contains index higher 1 and if yes if same-name sibling exists in
persistence or in current changes log. | [
"Check",
"if",
"given",
"node",
"path",
"contains",
"index",
"higher",
"1",
"and",
"if",
"yes",
"if",
"same",
"-",
"name",
"sibling",
"exists",
"in",
"persistence",
"or",
"in",
"current",
"changes",
"log",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/WorkspacePersistentDataManager.java#L1065-L1106 |
PinaeOS/nala | src/main/java/org/pinae/nala/xb/marshal/parser/ObjectParser.java | ObjectParser.parseAttributeValue | protected AttributeConfig parseAttributeValue(String fieldType, String name, Object value) {
value = parseValue(fieldType, value);
if (value != null) {
AttributeConfig attributeConfig = new AttributeConfig();
attributeConfig.setName(name);
attributeConfig.setValue(value.toString());
return attributeConfig;
}
return null;
} | java | protected AttributeConfig parseAttributeValue(String fieldType, String name, Object value) {
value = parseValue(fieldType, value);
if (value != null) {
AttributeConfig attributeConfig = new AttributeConfig();
attributeConfig.setName(name);
attributeConfig.setValue(value.toString());
return attributeConfig;
}
return null;
} | [
"protected",
"AttributeConfig",
"parseAttributeValue",
"(",
"String",
"fieldType",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"value",
"=",
"parseValue",
"(",
"fieldType",
",",
"value",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"A... | 根据字段类型解析对象之并构建属性
@param fieldType 字段类型
@param name 属性配置名称
@param value 属性配置值
@return 属性配置信息 | [
"根据字段类型解析对象之并构建属性"
] | train | https://github.com/PinaeOS/nala/blob/2047ade4af197cec938278d300d111ea94af6fbf/src/main/java/org/pinae/nala/xb/marshal/parser/ObjectParser.java#L117-L126 |
opengeospatial/teamengine | teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java | PBKDF2Realm.createGenericPrincipal | @SuppressWarnings({ "rawtypes", "unchecked" })
GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) {
Class klass = null;
try {
klass = Class.forName("org.apache.catalina.realm.GenericPrincipal");
} catch (ClassNotFoundException ex) {
LOGR.log(Level.SEVERE, ex.getMessage());
// Fortify Mod: If klass is not populated, then there is no point in continuing
return null;
}
Constructor[] ctors = klass.getConstructors();
Class firstParamType = ctors[0].getParameterTypes()[0];
Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class };
Object[] ctorArgs = new Object[] { this, username, password, roles };
GenericPrincipal principal = null;
try {
if (Realm.class.isAssignableFrom(firstParamType)) {
// Tomcat 6
Constructor ctor = klass.getConstructor(paramTypes);
principal = (GenericPrincipal) ctor.newInstance(ctorArgs);
} else {
// Realm parameter removed in Tomcat 7
Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length));
principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length));
}
} catch (Exception ex) {
LOGR.log(Level.WARNING, ex.getMessage());
}
return principal;
} | java | @SuppressWarnings({ "rawtypes", "unchecked" })
GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) {
Class klass = null;
try {
klass = Class.forName("org.apache.catalina.realm.GenericPrincipal");
} catch (ClassNotFoundException ex) {
LOGR.log(Level.SEVERE, ex.getMessage());
// Fortify Mod: If klass is not populated, then there is no point in continuing
return null;
}
Constructor[] ctors = klass.getConstructors();
Class firstParamType = ctors[0].getParameterTypes()[0];
Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class };
Object[] ctorArgs = new Object[] { this, username, password, roles };
GenericPrincipal principal = null;
try {
if (Realm.class.isAssignableFrom(firstParamType)) {
// Tomcat 6
Constructor ctor = klass.getConstructor(paramTypes);
principal = (GenericPrincipal) ctor.newInstance(ctorArgs);
} else {
// Realm parameter removed in Tomcat 7
Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length));
principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length));
}
} catch (Exception ex) {
LOGR.log(Level.WARNING, ex.getMessage());
}
return principal;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"GenericPrincipal",
"createGenericPrincipal",
"(",
"String",
"username",
",",
"String",
"password",
",",
"List",
"<",
"String",
">",
"roles",
")",
"{",
"Class",
"klass",
"=",
"n... | Creates a new GenericPrincipal representing the specified user.
@param username
The username for this user.
@param password
The authentication credentials for this user.
@param roles
The set of roles (specified using String values) associated
with this user.
@return A GenericPrincipal for use by this Realm implementation. | [
"Creates",
"a",
"new",
"GenericPrincipal",
"representing",
"the",
"specified",
"user",
"."
] | train | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java#L196-L225 |
lucee/Lucee | core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java | ResourceUtil.changeExtension | public static Resource changeExtension(Resource file, String newExtension) {
String ext = getExtension(file, null);
if (ext == null) return file.getParentResource().getRealResource(file.getName() + '.' + newExtension);
// new File(file.getParentFile(),file.getName()+'.'+newExtension);
String name = file.getName();
return file.getParentResource().getRealResource(name.substring(0, name.length() - ext.length()) + newExtension);
// new File(file.getParentFile(),name.substring(0,name.length()-ext.length())+newExtension);
} | java | public static Resource changeExtension(Resource file, String newExtension) {
String ext = getExtension(file, null);
if (ext == null) return file.getParentResource().getRealResource(file.getName() + '.' + newExtension);
// new File(file.getParentFile(),file.getName()+'.'+newExtension);
String name = file.getName();
return file.getParentResource().getRealResource(name.substring(0, name.length() - ext.length()) + newExtension);
// new File(file.getParentFile(),name.substring(0,name.length()-ext.length())+newExtension);
} | [
"public",
"static",
"Resource",
"changeExtension",
"(",
"Resource",
"file",
",",
"String",
"newExtension",
")",
"{",
"String",
"ext",
"=",
"getExtension",
"(",
"file",
",",
"null",
")",
";",
"if",
"(",
"ext",
"==",
"null",
")",
"return",
"file",
".",
"ge... | change extension of file and return new file
@param file
@param newExtension
@return file with new Extension | [
"change",
"extension",
"of",
"file",
"and",
"return",
"new",
"file"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java#L883-L890 |
PrashamTrivedi/SharedPreferenceInspector | sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java | SharedPreferenceUtils.putFloat | public void putFloat(String key, float value) {
sharedPreferences.edit().putFloat(key, value).commit();
} | java | public void putFloat(String key, float value) {
sharedPreferences.edit().putFloat(key, value).commit();
} | [
"public",
"void",
"putFloat",
"(",
"String",
"key",
",",
"float",
"value",
")",
"{",
"sharedPreferences",
".",
"edit",
"(",
")",
".",
"putFloat",
"(",
"key",
",",
"value",
")",
".",
"commit",
"(",
")",
";",
"}"
] | put the float value to shared preference
@param key
the name of the preference to save
@param value
the name of the preference to modify.
@see android.content.SharedPreferences#edit()#putFloat(String, float) | [
"put",
"the",
"float",
"value",
"to",
"shared",
"preference"
] | train | https://github.com/PrashamTrivedi/SharedPreferenceInspector/blob/c04d567c4d0fc5e0f8cda308ca85df19c6b3b838/sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java#L460-L462 |
ddf-project/DDF | core/src/main/java/io/ddf/DDF.java | DDF.validateName | private void validateName(String name) throws DDFException {
Boolean isNameExisted;
try {
this.getManager().getDDFByName(name);
isNameExisted = true;
} catch (DDFException e) {
isNameExisted = false;
}
if(isNameExisted) {
throw new DDFException(String.format("DDF with name %s already exists", name));
}
Pattern p = Pattern.compile("^[a-zA-Z0-9_-]*$");
Matcher m = p.matcher(name);
if(!m.find()) {
throw new DDFException(String.format("Invalid name %s, only allow alphanumeric (uppercase and lowercase a-z, " +
"numbers 0-9) and dash (\"-\") and underscore (\"_\")", name));
}
} | java | private void validateName(String name) throws DDFException {
Boolean isNameExisted;
try {
this.getManager().getDDFByName(name);
isNameExisted = true;
} catch (DDFException e) {
isNameExisted = false;
}
if(isNameExisted) {
throw new DDFException(String.format("DDF with name %s already exists", name));
}
Pattern p = Pattern.compile("^[a-zA-Z0-9_-]*$");
Matcher m = p.matcher(name);
if(!m.find()) {
throw new DDFException(String.format("Invalid name %s, only allow alphanumeric (uppercase and lowercase a-z, " +
"numbers 0-9) and dash (\"-\") and underscore (\"_\")", name));
}
} | [
"private",
"void",
"validateName",
"(",
"String",
"name",
")",
"throws",
"DDFException",
"{",
"Boolean",
"isNameExisted",
";",
"try",
"{",
"this",
".",
"getManager",
"(",
")",
".",
"getDDFByName",
"(",
"name",
")",
";",
"isNameExisted",
"=",
"true",
";",
"... | Also only allow alphanumberic and dash "-" and underscore "_" | [
"Also",
"only",
"allow",
"alphanumberic",
"and",
"dash",
"-",
"and",
"underscore",
"_"
] | train | https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/core/src/main/java/io/ddf/DDF.java#L241-L259 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/seo/CmsAliasList.java | CmsAliasList.addAlias | public void addAlias(final CmsAliasBean alias) {
final HorizontalPanel hp = new HorizontalPanel();
hp.getElement().getStyle().setMargin(2, Unit.PX);
final CmsTextBox textbox = createTextBox();
textbox.setFormValueAsString(alias.getSitePath());
hp.add(textbox);
CmsSelectBox selectbox = createSelectBox();
selectbox.setFormValueAsString(alias.getMode().toString());
hp.add(selectbox);
PushButton deleteButton = createDeleteButton();
hp.add(deleteButton);
final AliasControls controls = new AliasControls(alias, textbox, selectbox);
m_aliasControls.put(controls.getId(), controls);
selectbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
onChangePath(controls);
}
});
deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
m_aliasControls.remove(controls.getId());
hp.removeFromParent();
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> e) {
onChangePath(controls);
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
onChangePath(controls);
}
});
m_changeBox.add(hp);
CmsDomUtil.resizeAncestor(this);
} | java | public void addAlias(final CmsAliasBean alias) {
final HorizontalPanel hp = new HorizontalPanel();
hp.getElement().getStyle().setMargin(2, Unit.PX);
final CmsTextBox textbox = createTextBox();
textbox.setFormValueAsString(alias.getSitePath());
hp.add(textbox);
CmsSelectBox selectbox = createSelectBox();
selectbox.setFormValueAsString(alias.getMode().toString());
hp.add(selectbox);
PushButton deleteButton = createDeleteButton();
hp.add(deleteButton);
final AliasControls controls = new AliasControls(alias, textbox, selectbox);
m_aliasControls.put(controls.getId(), controls);
selectbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
onChangePath(controls);
}
});
deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
m_aliasControls.remove(controls.getId());
hp.removeFromParent();
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> e) {
onChangePath(controls);
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
onChangePath(controls);
}
});
m_changeBox.add(hp);
CmsDomUtil.resizeAncestor(this);
} | [
"public",
"void",
"addAlias",
"(",
"final",
"CmsAliasBean",
"alias",
")",
"{",
"final",
"HorizontalPanel",
"hp",
"=",
"new",
"HorizontalPanel",
"(",
")",
";",
"hp",
".",
"getElement",
"(",
")",
".",
"getStyle",
"(",
")",
".",
"setMargin",
"(",
"2",
",",
... | Adds the controls for a single alias to the widget.<p>
@param alias the alias for which the controls should be added | [
"Adds",
"the",
"controls",
"for",
"a",
"single",
"alias",
"to",
"the",
"widget",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/seo/CmsAliasList.java#L219-L271 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/authentication/ExtensionAuthentication.java | ExtensionAuthentication.getPopupFlagLoggedInIndicatorMenu | private PopupContextMenuItemFactory getPopupFlagLoggedInIndicatorMenu() {
if (this.popupFlagLoggedInIndicatorMenuFactory == null) {
popupFlagLoggedInIndicatorMenuFactory = new PopupContextMenuItemFactory("dd - "
+ Constant.messages.getString("context.flag.popup")) {
private static final long serialVersionUID = 2453839120088204122L;
@Override
public ExtensionPopupMenuItem getContextMenu(Context context, String parentMenu) {
return new PopupFlagLoggedInIndicatorMenu(context);
}
};
}
return this.popupFlagLoggedInIndicatorMenuFactory;
} | java | private PopupContextMenuItemFactory getPopupFlagLoggedInIndicatorMenu() {
if (this.popupFlagLoggedInIndicatorMenuFactory == null) {
popupFlagLoggedInIndicatorMenuFactory = new PopupContextMenuItemFactory("dd - "
+ Constant.messages.getString("context.flag.popup")) {
private static final long serialVersionUID = 2453839120088204122L;
@Override
public ExtensionPopupMenuItem getContextMenu(Context context, String parentMenu) {
return new PopupFlagLoggedInIndicatorMenu(context);
}
};
}
return this.popupFlagLoggedInIndicatorMenuFactory;
} | [
"private",
"PopupContextMenuItemFactory",
"getPopupFlagLoggedInIndicatorMenu",
"(",
")",
"{",
"if",
"(",
"this",
".",
"popupFlagLoggedInIndicatorMenuFactory",
"==",
"null",
")",
"{",
"popupFlagLoggedInIndicatorMenuFactory",
"=",
"new",
"PopupContextMenuItemFactory",
"(",
"\"d... | Gets the popup menu for flagging the "Logged in" pattern.
@return the popup menu | [
"Gets",
"the",
"popup",
"menu",
"for",
"flagging",
"the",
"Logged",
"in",
"pattern",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/authentication/ExtensionAuthentication.java#L156-L171 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java | SeaGlassLookAndFeel.defineProgressBars | private void defineProgressBars(UIDefaults d) {
// Copied from nimbus
//Initialize ProgressBar
d.put("ProgressBar.contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put("ProgressBar.States", "Enabled,Disabled,Indeterminate,Finished");
d.put("ProgressBar.tileWhenIndeterminate", Boolean.TRUE);
d.put("ProgressBar.paintOutsideClip", Boolean.TRUE);
d.put("ProgressBar.rotateText", Boolean.TRUE);
d.put("ProgressBar.vertictalSize", new DimensionUIResource(19, 150));
d.put("ProgressBar.horizontalSize", new DimensionUIResource(150, 19));
addColor(d, "ProgressBar[Disabled].textForeground", "seaGlassDisabledText", 0.0f, 0.0f, 0.0f, 0);
d.put("ProgressBar[Disabled+Indeterminate].progressPadding", new Integer(3));
// Seaglass starts below.
d.put("progressBarTrackInterior", Color.WHITE);
d.put("progressBarTrackBase", new Color(0x4076bf));
d.put("ProgressBar.Indeterminate", new ProgressBarIndeterminateState());
d.put("ProgressBar.Finished", new ProgressBarFinishedState());
String p = "ProgressBar";
String c = PAINTER_PREFIX + "ProgressBarPainter";
d.put(p + ".cycleTime", 500);
d.put(p + ".progressPadding", new Integer(3));
d.put(p + ".trackThickness", new Integer(19));
d.put(p + ".tileWidth", new Integer(24));
d.put(p + ".backgroundFillColor", Color.WHITE);
d.put(p + ".font", new DerivedFont("defaultFont", 0.769f, null, null));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Enabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_FINISHED));
d.put(p + "[Enabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_INDETERMINATE));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Disabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_FINISHED));
d.put(p + "[Disabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_INDETERMINATE));
} | java | private void defineProgressBars(UIDefaults d) {
// Copied from nimbus
//Initialize ProgressBar
d.put("ProgressBar.contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put("ProgressBar.States", "Enabled,Disabled,Indeterminate,Finished");
d.put("ProgressBar.tileWhenIndeterminate", Boolean.TRUE);
d.put("ProgressBar.paintOutsideClip", Boolean.TRUE);
d.put("ProgressBar.rotateText", Boolean.TRUE);
d.put("ProgressBar.vertictalSize", new DimensionUIResource(19, 150));
d.put("ProgressBar.horizontalSize", new DimensionUIResource(150, 19));
addColor(d, "ProgressBar[Disabled].textForeground", "seaGlassDisabledText", 0.0f, 0.0f, 0.0f, 0);
d.put("ProgressBar[Disabled+Indeterminate].progressPadding", new Integer(3));
// Seaglass starts below.
d.put("progressBarTrackInterior", Color.WHITE);
d.put("progressBarTrackBase", new Color(0x4076bf));
d.put("ProgressBar.Indeterminate", new ProgressBarIndeterminateState());
d.put("ProgressBar.Finished", new ProgressBarFinishedState());
String p = "ProgressBar";
String c = PAINTER_PREFIX + "ProgressBarPainter";
d.put(p + ".cycleTime", 500);
d.put(p + ".progressPadding", new Integer(3));
d.put(p + ".trackThickness", new Integer(19));
d.put(p + ".tileWidth", new Integer(24));
d.put(p + ".backgroundFillColor", Color.WHITE);
d.put(p + ".font", new DerivedFont("defaultFont", 0.769f, null, null));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Enabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_FINISHED));
d.put(p + "[Enabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_INDETERMINATE));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Disabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_FINISHED));
d.put(p + "[Disabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_INDETERMINATE));
} | [
"private",
"void",
"defineProgressBars",
"(",
"UIDefaults",
"d",
")",
"{",
"// Copied from nimbus",
"//Initialize ProgressBar",
"d",
".",
"put",
"(",
"\"ProgressBar.contentMargins\"",
",",
"new",
"InsetsUIResource",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"... | Initialize the progress bar settings.
@param d the UI defaults map. | [
"Initialize",
"the",
"progress",
"bar",
"settings",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java#L1601-L1644 |
telly/MrVector | library/src/main/java/com/telly/mrvector/PathParser.java | PathParser.updateNodes | public static void updateNodes(PathDataNode[] target, PathDataNode[] source) {
for (int i = 0; i < source.length; i ++) {
target[i].mType = source[i].mType;
for (int j = 0; j < source[i].mParams.length; j ++) {
target[i].mParams[j] = source[i].mParams[j];
}
}
} | java | public static void updateNodes(PathDataNode[] target, PathDataNode[] source) {
for (int i = 0; i < source.length; i ++) {
target[i].mType = source[i].mType;
for (int j = 0; j < source[i].mParams.length; j ++) {
target[i].mParams[j] = source[i].mParams[j];
}
}
} | [
"public",
"static",
"void",
"updateNodes",
"(",
"PathDataNode",
"[",
"]",
"target",
",",
"PathDataNode",
"[",
"]",
"source",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"source",
".",
"length",
";",
"i",
"++",
")",
"{",
"target",
"["... | Update the target's data to match the source.
Before calling this, make sure canMorph(target, source) is true.
@param target The target path represented in an array of PathDataNode
@param source The source path represented in an array of PathDataNode | [
"Update",
"the",
"target",
"s",
"data",
"to",
"match",
"the",
"source",
".",
"Before",
"calling",
"this",
"make",
"sure",
"canMorph",
"(",
"target",
"source",
")",
"is",
"true",
"."
] | train | https://github.com/telly/MrVector/blob/846cd05ab6e57dcdc1cae28e796ac84b1d6365d5/library/src/main/java/com/telly/mrvector/PathParser.java#L119-L126 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java | ExtensionsInner.enableMonitoringAsync | public Observable<Void> enableMonitoringAsync(String resourceGroupName, String clusterName, ClusterMonitoringRequest parameters) {
return enableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> enableMonitoringAsync(String resourceGroupName, String clusterName, ClusterMonitoringRequest parameters) {
return enableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"enableMonitoringAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"ClusterMonitoringRequest",
"parameters",
")",
"{",
"return",
"enableMonitoringWithServiceResponseAsync",
"(",
"resourceGroupName",
",",... | Enables the Operations Management Suite (OMS) on the HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param parameters The Operations Management Suite (OMS) workspace parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Enables",
"the",
"Operations",
"Management",
"Suite",
"(",
"OMS",
")",
"on",
"the",
"HDInsight",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java#L138-L145 |
ddf-project/DDF | core/src/main/java/io/ddf/DDF.java | DDF.validateSchema | private void validateSchema(Schema schema) throws DDFException {
Set<String> columnSet = new HashSet<String>();
if(schema != null && schema.getColumns() != null) {
for (Column column : schema.getColumns()) {
if (columnSet.contains(column.getName())) {
throw new DDFException(String.format("Duplicated column name %s", column.getName()));
} else {
columnSet.add(column.getName());
}
}
}
} | java | private void validateSchema(Schema schema) throws DDFException {
Set<String> columnSet = new HashSet<String>();
if(schema != null && schema.getColumns() != null) {
for (Column column : schema.getColumns()) {
if (columnSet.contains(column.getName())) {
throw new DDFException(String.format("Duplicated column name %s", column.getName()));
} else {
columnSet.add(column.getName());
}
}
}
} | [
"private",
"void",
"validateSchema",
"(",
"Schema",
"schema",
")",
"throws",
"DDFException",
"{",
"Set",
"<",
"String",
">",
"columnSet",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"schema",
"!=",
"null",
"&&",
"schema",
".",
... | ////// MetaData that deserves to be right here at the top level //////// | [
"//////",
"MetaData",
"that",
"deserves",
"to",
"be",
"right",
"here",
"at",
"the",
"top",
"level",
"////////"
] | train | https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/core/src/main/java/io/ddf/DDF.java#L296-L307 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Caster.java | Caster.toNull | public static Object toNull(Object value) throws PageException {
if (value == null) return null;
if (value instanceof String && Caster.toString(value).trim().length() == 0) return null;
if (value instanceof Number && ((Number) value).intValue() == 0) return null;
throw new CasterException(value, "null");
} | java | public static Object toNull(Object value) throws PageException {
if (value == null) return null;
if (value instanceof String && Caster.toString(value).trim().length() == 0) return null;
if (value instanceof Number && ((Number) value).intValue() == 0) return null;
throw new CasterException(value, "null");
} | [
"public",
"static",
"Object",
"toNull",
"(",
"Object",
"value",
")",
"throws",
"PageException",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"value",
"instanceof",
"String",
"&&",
"Caster",
".",
"toString",
"(",
"value",
... | casts a Object to null
@param value
@return to null from Object
@throws PageException | [
"casts",
"a",
"Object",
"to",
"null"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L4414-L4419 |
pressgang-ccms/PressGangCCMSBuilder | src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java | DocBookBuilder.createDummyTranslatedTopicFromTopic | private TranslatedTopicWrapper createDummyTranslatedTopicFromTopic(final TopicWrapper topic, final LocaleWrapper locale) {
final TranslatedTopicWrapper pushedTranslatedTopic = EntityUtilities.returnPushedTranslatedTopic(topic);
/*
* Try and use the untranslated default locale translated topic as the base for the dummy topic. If that fails then
* create a dummy topic from the passed RESTTopicV1.
*/
if (pushedTranslatedTopic != null) {
pushedTranslatedTopic.setTopic(topic);
pushedTranslatedTopic.setTags(topic.getTags());
pushedTranslatedTopic.setProperties(topic.getProperties());
return createDummyTranslatedTopicFromExisting(pushedTranslatedTopic, locale);
} else {
return createDummyTranslatedTopic(topic, locale);
}
} | java | private TranslatedTopicWrapper createDummyTranslatedTopicFromTopic(final TopicWrapper topic, final LocaleWrapper locale) {
final TranslatedTopicWrapper pushedTranslatedTopic = EntityUtilities.returnPushedTranslatedTopic(topic);
/*
* Try and use the untranslated default locale translated topic as the base for the dummy topic. If that fails then
* create a dummy topic from the passed RESTTopicV1.
*/
if (pushedTranslatedTopic != null) {
pushedTranslatedTopic.setTopic(topic);
pushedTranslatedTopic.setTags(topic.getTags());
pushedTranslatedTopic.setProperties(topic.getProperties());
return createDummyTranslatedTopicFromExisting(pushedTranslatedTopic, locale);
} else {
return createDummyTranslatedTopic(topic, locale);
}
} | [
"private",
"TranslatedTopicWrapper",
"createDummyTranslatedTopicFromTopic",
"(",
"final",
"TopicWrapper",
"topic",
",",
"final",
"LocaleWrapper",
"locale",
")",
"{",
"final",
"TranslatedTopicWrapper",
"pushedTranslatedTopic",
"=",
"EntityUtilities",
".",
"returnPushedTranslated... | Creates a dummy translated topic so that a book can be built using the same relationships as a normal build.
@param topic The topic to create the dummy topic from.
@param locale The locale to build the dummy translations for.
@return The dummy translated topic. | [
"Creates",
"a",
"dummy",
"translated",
"topic",
"so",
"that",
"a",
"book",
"can",
"be",
"built",
"using",
"the",
"same",
"relationships",
"as",
"a",
"normal",
"build",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java#L978-L993 |
jblas-project/jblas | src/main/java/org/jblas/Eigen.java | Eigen.symmetricGeneralizedEigenvalues | public static FloatMatrix symmetricGeneralizedEigenvalues(FloatMatrix A, FloatMatrix B, float vl, float vu) {
A.assertSquare();
B.assertSquare();
A.assertSameSize(B);
if (vu <= vl) {
throw new IllegalArgumentException("Bound exception: make sure vu > vl");
}
float abstol = (float) 1e-9; // What is a good tolerance?
int[] m = new int[1];
FloatMatrix W = new FloatMatrix(A.rows);
FloatMatrix Z = new FloatMatrix(A.rows, A.rows);
SimpleBlas.sygvx(1, 'N', 'V', 'U', A.dup(), B.dup(), vl, vu, 0, 0, abstol, m, W, Z);
if (m[0] == 0) {
throw new NoEigenResultException("No eigenvalues found for selected range");
}
return W.get(new IntervalRange(0, m[0]), 0);
} | java | public static FloatMatrix symmetricGeneralizedEigenvalues(FloatMatrix A, FloatMatrix B, float vl, float vu) {
A.assertSquare();
B.assertSquare();
A.assertSameSize(B);
if (vu <= vl) {
throw new IllegalArgumentException("Bound exception: make sure vu > vl");
}
float abstol = (float) 1e-9; // What is a good tolerance?
int[] m = new int[1];
FloatMatrix W = new FloatMatrix(A.rows);
FloatMatrix Z = new FloatMatrix(A.rows, A.rows);
SimpleBlas.sygvx(1, 'N', 'V', 'U', A.dup(), B.dup(), vl, vu, 0, 0, abstol, m, W, Z);
if (m[0] == 0) {
throw new NoEigenResultException("No eigenvalues found for selected range");
}
return W.get(new IntervalRange(0, m[0]), 0);
} | [
"public",
"static",
"FloatMatrix",
"symmetricGeneralizedEigenvalues",
"(",
"FloatMatrix",
"A",
",",
"FloatMatrix",
"B",
",",
"float",
"vl",
",",
"float",
"vu",
")",
"{",
"A",
".",
"assertSquare",
"(",
")",
";",
"B",
".",
"assertSquare",
"(",
")",
";",
"A",... | Computes selected eigenvalues of the real generalized symmetric-definite eigenproblem of the form A x = L B x
or, equivalently, (A - L B)x = 0. Here A and B are assumed to be symmetric and B is also positive definite.
The selection is based on the given range of values for the desired eigenvalues.
<p/>
The range is half open: (vl,vu].
@param A symmetric Matrix A. Only the upper triangle will be considered.
@param B symmetric Matrix B. Only the upper triangle will be considered.
@param vl lower bound of the smallest eigenvalue to return
@param vu upper bound of the largest eigenvalue to return
@throws IllegalArgumentException if <code>vl > vu</code>
@throws NoEigenResultException if no eigevalues are found for the selected range: (vl,vu]
@return a vector of eigenvalues L | [
"Computes",
"selected",
"eigenvalues",
"of",
"the",
"real",
"generalized",
"symmetric",
"-",
"definite",
"eigenproblem",
"of",
"the",
"form",
"A",
"x",
"=",
"L",
"B",
"x",
"or",
"equivalently",
"(",
"A",
"-",
"L",
"B",
")",
"x",
"=",
"0",
".",
"Here",
... | train | https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Eigen.java#L437-L453 |
alipay/sofa-rpc | extension-impl/codec-sofa-hessian/src/main/java/com/alipay/sofa/rpc/codec/sofahessian/BlackListFileLoader.java | BlackListFileLoader.readToList | private static void readToList(InputStream input, String encoding, List<String> blackPrefixList) {
InputStreamReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new InputStreamReader(input, encoding);
bufferedReader = new BufferedReader(reader);
String lineText;
while ((lineText = bufferedReader.readLine()) != null) {
String pkg = lineText.trim();
if (pkg.length() > 0) {
blackPrefixList.add(pkg);
}
}
} catch (IOException e) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(e.getMessage(), e);
}
} finally {
closeQuietly(bufferedReader);
closeQuietly(reader);
}
} | java | private static void readToList(InputStream input, String encoding, List<String> blackPrefixList) {
InputStreamReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new InputStreamReader(input, encoding);
bufferedReader = new BufferedReader(reader);
String lineText;
while ((lineText = bufferedReader.readLine()) != null) {
String pkg = lineText.trim();
if (pkg.length() > 0) {
blackPrefixList.add(pkg);
}
}
} catch (IOException e) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(e.getMessage(), e);
}
} finally {
closeQuietly(bufferedReader);
closeQuietly(reader);
}
} | [
"private",
"static",
"void",
"readToList",
"(",
"InputStream",
"input",
",",
"String",
"encoding",
",",
"List",
"<",
"String",
">",
"blackPrefixList",
")",
"{",
"InputStreamReader",
"reader",
"=",
"null",
";",
"BufferedReader",
"bufferedReader",
"=",
"null",
";"... | 读文件,将结果丢入List
@param input 输入流程
@param encoding 编码
@param blackPrefixList 保持黑名单前缀的List | [
"读文件,将结果丢入List"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/codec-sofa-hessian/src/main/java/com/alipay/sofa/rpc/codec/sofahessian/BlackListFileLoader.java#L77-L98 |
liferay/com-liferay-commerce | commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java | CommerceDiscountPersistenceImpl.findByGroupId | @Override
public List<CommerceDiscount> findByGroupId(long groupId, int start, int end) {
return findByGroupId(groupId, start, end, null);
} | java | @Override
public List<CommerceDiscount> findByGroupId(long groupId, int start, int end) {
return findByGroupId(groupId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceDiscount",
">",
"findByGroupId",
"(",
"long",
"groupId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce discounts where groupId = ?.
<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 CommerceDiscountModelImpl}. 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 groupId the group ID
@param start the lower bound of the range of commerce discounts
@param end the upper bound of the range of commerce discounts (not inclusive)
@return the range of matching commerce discounts | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"discounts",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java#L1535-L1538 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/breadcrumbs/BreadcrumbsRenderer.java | BreadcrumbsRenderer.encodeEnd | @Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
// End point / current page
UIComponent end = component.getFacet("end");
if (end != null) {
rw.startElement("li", component);
end.encodeAll(context);
rw.endElement("li");
}
rw.endElement("ol");
Tooltip.activateTooltips(context, component);
} | java | @Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
// End point / current page
UIComponent end = component.getFacet("end");
if (end != null) {
rw.startElement("li", component);
end.encodeAll(context);
rw.endElement("li");
}
rw.endElement("ol");
Tooltip.activateTooltips(context, component);
} | [
"@",
"Override",
"public",
"void",
"encodeEnd",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"ResponseWriter",
"rw"... | This methods generates the HTML code of the current b:breadcrumbs. <code>encodeBegin</code> generates the
start of the component. After the, the JSF framework calls <code>encodeChildren()</code> to generate the HTML
code between the beginning and the end of the component. For instance, in the case of a panel component the
content of the panel is generated by <code>encodeChildren()</code>. After that, <code>encodeEnd()</code> is
called to generate the rest of the HTML code.
@param context the FacesContext.
@param component the current b:breadcrumbs.
@throws IOException thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"breadcrumbs",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framewor... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/breadcrumbs/BreadcrumbsRenderer.java#L91-L108 |
JodaOrg/joda-time | src/main/java/org/joda/time/YearMonth.java | YearMonth.withChronologyRetainFields | public YearMonth withChronologyRetainFields(Chronology newChronology) {
newChronology = DateTimeUtils.getChronology(newChronology);
newChronology = newChronology.withUTC();
if (newChronology == getChronology()) {
return this;
} else {
YearMonth newYearMonth = new YearMonth(this, newChronology);
newChronology.validate(newYearMonth, getValues());
return newYearMonth;
}
} | java | public YearMonth withChronologyRetainFields(Chronology newChronology) {
newChronology = DateTimeUtils.getChronology(newChronology);
newChronology = newChronology.withUTC();
if (newChronology == getChronology()) {
return this;
} else {
YearMonth newYearMonth = new YearMonth(this, newChronology);
newChronology.validate(newYearMonth, getValues());
return newYearMonth;
}
} | [
"public",
"YearMonth",
"withChronologyRetainFields",
"(",
"Chronology",
"newChronology",
")",
"{",
"newChronology",
"=",
"DateTimeUtils",
".",
"getChronology",
"(",
"newChronology",
")",
";",
"newChronology",
"=",
"newChronology",
".",
"withUTC",
"(",
")",
";",
"if"... | Returns a copy of this year-month with the specified chronology.
This instance is immutable and unaffected by this method call.
<p>
This method retains the values of the fields, thus the result will
typically refer to a different instant.
<p>
The time zone of the specified chronology is ignored, as YearMonth
operates without a time zone.
@param newChronology the new chronology, null means ISO
@return a copy of this year-month with a different chronology, never null
@throws IllegalArgumentException if the values are invalid for the new chronology | [
"Returns",
"a",
"copy",
"of",
"this",
"year",
"-",
"month",
"with",
"the",
"specified",
"chronology",
".",
"This",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
".",
"<p",
">",
"This",
"method",
"retains",
"the",
"valu... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonth.java#L447-L457 |
sksamuel/scrimage | scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java | MarvinImage.getBufferedImage | public BufferedImage getBufferedImage(int width, int height, int type) {
int wDif,
hDif,
fWidth = 0,
fHeight = 0;
double imgWidth,
imgHeight;
double factor;
imgWidth = image.getWidth();
imgHeight = image.getHeight();
switch (type) {
case PROPORTIONAL:
wDif = (int) imgWidth - width;
hDif = (int) imgHeight - height;
if (wDif > hDif) {
factor = width / imgWidth;
} else {
factor = height / imgHeight;
}
fWidth = (int) Math.floor(imgWidth * factor);
fHeight = (int) Math.floor(imgHeight * factor);
break;
}
return getBufferedImage(fWidth, fHeight);
} | java | public BufferedImage getBufferedImage(int width, int height, int type) {
int wDif,
hDif,
fWidth = 0,
fHeight = 0;
double imgWidth,
imgHeight;
double factor;
imgWidth = image.getWidth();
imgHeight = image.getHeight();
switch (type) {
case PROPORTIONAL:
wDif = (int) imgWidth - width;
hDif = (int) imgHeight - height;
if (wDif > hDif) {
factor = width / imgWidth;
} else {
factor = height / imgHeight;
}
fWidth = (int) Math.floor(imgWidth * factor);
fHeight = (int) Math.floor(imgHeight * factor);
break;
}
return getBufferedImage(fWidth, fHeight);
} | [
"public",
"BufferedImage",
"getBufferedImage",
"(",
"int",
"width",
",",
"int",
"height",
",",
"int",
"type",
")",
"{",
"int",
"wDif",
",",
"hDif",
",",
"fWidth",
"=",
"0",
",",
"fHeight",
"=",
"0",
";",
"double",
"imgWidth",
",",
"imgHeight",
";",
"do... | Resize and return the image passing the new height and width, but maintains width/height factor
@param height
@param width
@return | [
"Resize",
"and",
"return",
"the",
"image",
"passing",
"the",
"new",
"height",
"and",
"width",
"but",
"maintains",
"width",
"/",
"height",
"factor"
] | train | https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java#L497-L525 |
aws/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/ListInventoryEntriesResult.java | ListInventoryEntriesResult.withEntries | public ListInventoryEntriesResult withEntries(java.util.Collection<java.util.Map<String, String>> entries) {
setEntries(entries);
return this;
} | java | public ListInventoryEntriesResult withEntries(java.util.Collection<java.util.Map<String, String>> entries) {
setEntries(entries);
return this;
} | [
"public",
"ListInventoryEntriesResult",
"withEntries",
"(",
"java",
".",
"util",
".",
"Collection",
"<",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
">",
"entries",
")",
"{",
"setEntries",
"(",
"entries",
")",
";",
"return",
"this",... | <p>
A list of inventory items on the instance(s).
</p>
@param entries
A list of inventory items on the instance(s).
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"list",
"of",
"inventory",
"items",
"on",
"the",
"instance",
"(",
"s",
")",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/ListInventoryEntriesResult.java#L292-L295 |
medallia/Word2VecJava | src/main/java/com/medallia/word2vec/util/IO.java | IO.createTempFile | public static File createTempFile(byte[] fileContents, String namePrefix, String extension) throws IOException {
Preconditions.checkNotNull(fileContents, "file contents missing");
File tempFile = File.createTempFile(namePrefix, extension);
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(fileContents);
}
return tempFile;
} | java | public static File createTempFile(byte[] fileContents, String namePrefix, String extension) throws IOException {
Preconditions.checkNotNull(fileContents, "file contents missing");
File tempFile = File.createTempFile(namePrefix, extension);
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(fileContents);
}
return tempFile;
} | [
"public",
"static",
"File",
"createTempFile",
"(",
"byte",
"[",
"]",
"fileContents",
",",
"String",
"namePrefix",
",",
"String",
"extension",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"fileContents",
",",
"\"file contents missing\... | Stores the given contents into a temporary file
@param fileContents the raw contents to store in the temporary file
@param namePrefix the desired file name prefix (must be at least 3 characters long)
@param extension the desired extension including the '.' character (use null for '.tmp')
@return a {@link File} reference to the newly created temporary file
@throws IOException if the temporary file creation fails | [
"Stores",
"the",
"given",
"contents",
"into",
"a",
"temporary",
"file"
] | train | https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/IO.java#L248-L255 |
eduarddrenth/ConfigurableReports | src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java | DefaultElementProducer.createElementByStyler | public <E extends Element> E createElementByStyler(Collection<? extends BaseStyler> stylers, Object data, Class<E> clazz) throws VectorPrintException {
// pdfptable, Section and others do not have a default constructor, a styler creates it
E e = null;
return styleHelper.style(e, data, stylers);
} | java | public <E extends Element> E createElementByStyler(Collection<? extends BaseStyler> stylers, Object data, Class<E> clazz) throws VectorPrintException {
// pdfptable, Section and others do not have a default constructor, a styler creates it
E e = null;
return styleHelper.style(e, data, stylers);
} | [
"public",
"<",
"E",
"extends",
"Element",
">",
"E",
"createElementByStyler",
"(",
"Collection",
"<",
"?",
"extends",
"BaseStyler",
">",
"stylers",
",",
"Object",
"data",
",",
"Class",
"<",
"E",
">",
"clazz",
")",
"throws",
"VectorPrintException",
"{",
"// pd... | leaves object creation to the first styler in the list
@param <E>
@param stylers
@param data
@param clazz
@return
@throws VectorPrintException | [
"leaves",
"object",
"creation",
"to",
"the",
"first",
"styler",
"in",
"the",
"list"
] | train | https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java#L133-L138 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseRecommendedActionsInner.java | DatabaseRecommendedActionsInner.updateAsync | public Observable<RecommendedActionInner> updateAsync(String resourceGroupName, String serverName, String databaseName, String advisorName, String recommendedActionName, RecommendedActionStateInfo state) {
return updateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName, state).map(new Func1<ServiceResponse<RecommendedActionInner>, RecommendedActionInner>() {
@Override
public RecommendedActionInner call(ServiceResponse<RecommendedActionInner> response) {
return response.body();
}
});
} | java | public Observable<RecommendedActionInner> updateAsync(String resourceGroupName, String serverName, String databaseName, String advisorName, String recommendedActionName, RecommendedActionStateInfo state) {
return updateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName, state).map(new Func1<ServiceResponse<RecommendedActionInner>, RecommendedActionInner>() {
@Override
public RecommendedActionInner call(ServiceResponse<RecommendedActionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RecommendedActionInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"advisorName",
",",
"String",
"recommendedActionName",
",",
"RecommendedActionStateInf... | Updates a database recommended action.
@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 databaseName The name of the database.
@param advisorName The name of the Database Advisor.
@param recommendedActionName The name of Database Recommended Action.
@param state Gets the info of the current state the recommended action is in.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RecommendedActionInner object | [
"Updates",
"a",
"database",
"recommended",
"action",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseRecommendedActionsInner.java#L327-L334 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java | SdkUtils.createDefaultThreadPoolExecutor | public static ThreadPoolExecutor createDefaultThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit) {
return new StringMappedThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
});
} | java | public static ThreadPoolExecutor createDefaultThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit) {
return new StringMappedThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
});
} | [
"public",
"static",
"ThreadPoolExecutor",
"createDefaultThreadPoolExecutor",
"(",
"int",
"corePoolSize",
",",
"int",
"maximumPoolSize",
",",
"long",
"keepAliveTime",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"new",
"StringMappedThreadPoolExecutor",
"(",
"corePoolSize",... | Utility method to create a new StringMappedThreadPoolExecutor (which can be used to inspect runnables).
@param corePoolSize the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
@param maximumPoolSize the maximum number of threads to allow in the pool
@param keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
@param unit the time unit for the keepAliveTime argument
@return a StringMappedThreadPoolExecutor created from given arguments. | [
"Utility",
"method",
"to",
"create",
"a",
"new",
"StringMappedThreadPoolExecutor",
"(",
"which",
"can",
"be",
"used",
"to",
"inspect",
"runnables",
")",
"."
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java#L309-L321 |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/TransitionUtils.java | TransitionUtils.createViewBitmap | @Nullable
public static Bitmap createViewBitmap(@NonNull View view, @NonNull Matrix matrix, @NonNull RectF bounds) {
Bitmap bitmap = null;
int bitmapWidth = Math.round(bounds.width());
int bitmapHeight = Math.round(bounds.height());
if (bitmapWidth > 0 && bitmapHeight > 0) {
float scale = Math.min(1f, ((float)MAX_IMAGE_SIZE) / (bitmapWidth * bitmapHeight));
bitmapWidth *= scale;
bitmapHeight *= scale;
matrix.postTranslate(-bounds.left, -bounds.top);
matrix.postScale(scale, scale);
try {
bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.concat(matrix);
view.draw(canvas);
} catch (OutOfMemoryError e) {
// ignore
}
}
return bitmap;
} | java | @Nullable
public static Bitmap createViewBitmap(@NonNull View view, @NonNull Matrix matrix, @NonNull RectF bounds) {
Bitmap bitmap = null;
int bitmapWidth = Math.round(bounds.width());
int bitmapHeight = Math.round(bounds.height());
if (bitmapWidth > 0 && bitmapHeight > 0) {
float scale = Math.min(1f, ((float)MAX_IMAGE_SIZE) / (bitmapWidth * bitmapHeight));
bitmapWidth *= scale;
bitmapHeight *= scale;
matrix.postTranslate(-bounds.left, -bounds.top);
matrix.postScale(scale, scale);
try {
bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.concat(matrix);
view.draw(canvas);
} catch (OutOfMemoryError e) {
// ignore
}
}
return bitmap;
} | [
"@",
"Nullable",
"public",
"static",
"Bitmap",
"createViewBitmap",
"(",
"@",
"NonNull",
"View",
"view",
",",
"@",
"NonNull",
"Matrix",
"matrix",
",",
"@",
"NonNull",
"RectF",
"bounds",
")",
"{",
"Bitmap",
"bitmap",
"=",
"null",
";",
"int",
"bitmapWidth",
"... | Creates a Bitmap of the given view, using the Matrix matrix to transform to the local
coordinates. <code>matrix</code> will be modified during the bitmap creation.
<p>If the bitmap is large, it will be scaled uniformly down to at most 1MB size.</p>
@param view The view to create a bitmap for.
@param matrix The matrix converting the view local coordinates to the coordinates that
the bitmap will be displayed in. <code>matrix</code> will be modified before
returning.
@param bounds The bounds of the bitmap in the destination coordinate system (where the
view should be presented. Typically, this is matrix.mapRect(viewBounds);
@return A bitmap of the given view or null if bounds has no width or height. | [
"Creates",
"a",
"Bitmap",
"of",
"the",
"given",
"view",
"using",
"the",
"Matrix",
"matrix",
"to",
"transform",
"to",
"the",
"local",
"coordinates",
".",
"<code",
">",
"matrix<",
"/",
"code",
">",
"will",
"be",
"modified",
"during",
"the",
"bitmap",
"creati... | train | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/TransitionUtils.java#L163-L184 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/storage/PayloadSender.java | PayloadSender.sendPayloadRequest | private synchronized void sendPayloadRequest(final PayloadData payload) {
ApptentiveLog.v(PAYLOADS, "Sending payload: %s", payload);
// create request object
final HttpRequest payloadRequest = requestSender.createPayloadSendRequest(payload, new HttpRequest.Listener<HttpRequest>() {
@Override
public void onFinish(HttpRequest request) {
try {
String json = StringUtils.isNullOrEmpty(request.getResponseData()) ? "{}" : request.getResponseData();
final JSONObject responseData = new JSONObject(json);
handleFinishSendingPayload(payload, false, null, request.getResponseCode(), responseData);
} catch (Exception e) {
// TODO: Stop assuming the response is JSON. In fact, just send bytes back, and whatever part of the SDK needs it can try to convert it to the desired format.
ApptentiveLog.e(PAYLOADS, e, "Exception while handling payload send response");
logException(e);
handleFinishSendingPayload(payload, false, null, -1, null);
}
}
@Override
public void onCancel(HttpRequest request) {
handleFinishSendingPayload(payload, true, null, request.getResponseCode(), null);
}
@Override
public void onFail(HttpRequest request, String reason) {
if (request.isAuthenticationFailure()) {
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_AUTHENTICATION_FAILED, NOTIFICATION_KEY_CONVERSATION_ID, payload.getConversationId(), NOTIFICATION_KEY_AUTHENTICATION_FAILED_REASON, request.getAuthenticationFailedReason());
}
handleFinishSendingPayload(payload, false, reason, request.getResponseCode(), null);
}
});
// set 'retry' policy
payloadRequest.setRetryPolicy(requestRetryPolicy);
payloadRequest.setCallbackQueue(conversationQueue());
payloadRequest.start();
} | java | private synchronized void sendPayloadRequest(final PayloadData payload) {
ApptentiveLog.v(PAYLOADS, "Sending payload: %s", payload);
// create request object
final HttpRequest payloadRequest = requestSender.createPayloadSendRequest(payload, new HttpRequest.Listener<HttpRequest>() {
@Override
public void onFinish(HttpRequest request) {
try {
String json = StringUtils.isNullOrEmpty(request.getResponseData()) ? "{}" : request.getResponseData();
final JSONObject responseData = new JSONObject(json);
handleFinishSendingPayload(payload, false, null, request.getResponseCode(), responseData);
} catch (Exception e) {
// TODO: Stop assuming the response is JSON. In fact, just send bytes back, and whatever part of the SDK needs it can try to convert it to the desired format.
ApptentiveLog.e(PAYLOADS, e, "Exception while handling payload send response");
logException(e);
handleFinishSendingPayload(payload, false, null, -1, null);
}
}
@Override
public void onCancel(HttpRequest request) {
handleFinishSendingPayload(payload, true, null, request.getResponseCode(), null);
}
@Override
public void onFail(HttpRequest request, String reason) {
if (request.isAuthenticationFailure()) {
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_AUTHENTICATION_FAILED, NOTIFICATION_KEY_CONVERSATION_ID, payload.getConversationId(), NOTIFICATION_KEY_AUTHENTICATION_FAILED_REASON, request.getAuthenticationFailedReason());
}
handleFinishSendingPayload(payload, false, reason, request.getResponseCode(), null);
}
});
// set 'retry' policy
payloadRequest.setRetryPolicy(requestRetryPolicy);
payloadRequest.setCallbackQueue(conversationQueue());
payloadRequest.start();
} | [
"private",
"synchronized",
"void",
"sendPayloadRequest",
"(",
"final",
"PayloadData",
"payload",
")",
"{",
"ApptentiveLog",
".",
"v",
"(",
"PAYLOADS",
",",
"\"Sending payload: %s\"",
",",
"payload",
")",
";",
"// create request object",
"final",
"HttpRequest",
"payloa... | Creates and sends payload Http-request asynchronously (returns immediately)
@param payload | [
"Creates",
"and",
"sends",
"payload",
"Http",
"-",
"request",
"asynchronously",
"(",
"returns",
"immediately",
")"
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/storage/PayloadSender.java#L104-L142 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/converter/object/OpenTypeConverter.java | OpenTypeConverter.toJSON | protected JSONAware toJSON(Object pValue) {
Class givenClass = pValue.getClass();
if (JSONAware.class.isAssignableFrom(givenClass)) {
return (JSONAware) pValue;
} else {
try {
return (JSONAware) new JSONParser().parse(pValue.toString());
} catch (ParseException e) {
throw new IllegalArgumentException("Cannot parse JSON " + pValue + ": " + e,e);
} catch (ClassCastException exp) {
throw new IllegalArgumentException("Given value " + pValue.toString() +
" cannot be parsed to JSONAware object: " + exp,exp);
}
}
} | java | protected JSONAware toJSON(Object pValue) {
Class givenClass = pValue.getClass();
if (JSONAware.class.isAssignableFrom(givenClass)) {
return (JSONAware) pValue;
} else {
try {
return (JSONAware) new JSONParser().parse(pValue.toString());
} catch (ParseException e) {
throw new IllegalArgumentException("Cannot parse JSON " + pValue + ": " + e,e);
} catch (ClassCastException exp) {
throw new IllegalArgumentException("Given value " + pValue.toString() +
" cannot be parsed to JSONAware object: " + exp,exp);
}
}
} | [
"protected",
"JSONAware",
"toJSON",
"(",
"Object",
"pValue",
")",
"{",
"Class",
"givenClass",
"=",
"pValue",
".",
"getClass",
"(",
")",
";",
"if",
"(",
"JSONAware",
".",
"class",
".",
"isAssignableFrom",
"(",
"givenClass",
")",
")",
"{",
"return",
"(",
"... | Convert to JSON. The given object must be either a valid JSON string or of type {@link JSONAware}, in which
case it is returned directly
@param pValue the value to parse (or to return directly if it is a {@link JSONAware}
@return the resulting value | [
"Convert",
"to",
"JSON",
".",
"The",
"given",
"object",
"must",
"be",
"either",
"a",
"valid",
"JSON",
"string",
"or",
"of",
"type",
"{",
"@link",
"JSONAware",
"}",
"in",
"which",
"case",
"it",
"is",
"returned",
"directly"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/object/OpenTypeConverter.java#L71-L85 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ReplaceableString.java | ReplaceableString.getChars | public void getChars(int srcStart, int srcLimit, char dst[], int dstStart) {
if (srcStart != srcLimit) {
buf.getChars(srcStart, srcLimit, dst, dstStart);
}
} | java | public void getChars(int srcStart, int srcLimit, char dst[], int dstStart) {
if (srcStart != srcLimit) {
buf.getChars(srcStart, srcLimit, dst, dstStart);
}
} | [
"public",
"void",
"getChars",
"(",
"int",
"srcStart",
",",
"int",
"srcLimit",
",",
"char",
"dst",
"[",
"]",
",",
"int",
"dstStart",
")",
"{",
"if",
"(",
"srcStart",
"!=",
"srcLimit",
")",
"{",
"buf",
".",
"getChars",
"(",
"srcStart",
",",
"srcLimit",
... | Copies characters from this object into the destination
character array. The first character to be copied is at index
<code>srcStart</code>; the last character to be copied is at
index <code>srcLimit-1</code> (thus the total number of
characters to be copied is <code>srcLimit-srcStart</code>). The
characters are copied into the subarray of <code>dst</code>
starting at index <code>dstStart</code> and ending at index
<code>dstStart + (srcLimit-srcStart) - 1</code>.
@param srcStart the beginning index to copy, inclusive; <code>0
<= start <= limit</code>.
@param srcLimit the ending index to copy, exclusive;
<code>start <= limit <= length()</code>.
@param dst the destination array.
@param dstStart the start offset in the destination array. | [
"Copies",
"characters",
"from",
"this",
"object",
"into",
"the",
"destination",
"character",
"array",
".",
"The",
"first",
"character",
"to",
"be",
"copied",
"is",
"at",
"index",
"<code",
">",
"srcStart<",
"/",
"code",
">",
";",
"the",
"last",
"character",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ReplaceableString.java#L120-L124 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java | SchemaManager.findUserTableForIndex | Table findUserTableForIndex(Session session, String name,
String schemaName) {
Schema schema = (Schema) schemaMap.get(schemaName);
HsqlName indexName = schema.indexLookup.getName(name);
if (indexName == null) {
return null;
}
return findUserTable(session, indexName.parent.name, schemaName);
} | java | Table findUserTableForIndex(Session session, String name,
String schemaName) {
Schema schema = (Schema) schemaMap.get(schemaName);
HsqlName indexName = schema.indexLookup.getName(name);
if (indexName == null) {
return null;
}
return findUserTable(session, indexName.parent.name, schemaName);
} | [
"Table",
"findUserTableForIndex",
"(",
"Session",
"session",
",",
"String",
"name",
",",
"String",
"schemaName",
")",
"{",
"Schema",
"schema",
"=",
"(",
"Schema",
")",
"schemaMap",
".",
"get",
"(",
"schemaName",
")",
";",
"HsqlName",
"indexName",
"=",
"schem... | Returns the table that has an index with the given name and schema. | [
"Returns",
"the",
"table",
"that",
"has",
"an",
"index",
"with",
"the",
"given",
"name",
"and",
"schema",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java#L957-L968 |
bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java | MimeMessageHelper.setAttachments | static void setAttachments(final Email email, final MimeMultipart multipartRoot)
throws MessagingException {
for (final AttachmentResource resource : email.getAttachments()) {
multipartRoot.addBodyPart(getBodyPartFromDatasource(resource, Part.ATTACHMENT));
}
} | java | static void setAttachments(final Email email, final MimeMultipart multipartRoot)
throws MessagingException {
for (final AttachmentResource resource : email.getAttachments()) {
multipartRoot.addBodyPart(getBodyPartFromDatasource(resource, Part.ATTACHMENT));
}
} | [
"static",
"void",
"setAttachments",
"(",
"final",
"Email",
"email",
",",
"final",
"MimeMultipart",
"multipartRoot",
")",
"throws",
"MessagingException",
"{",
"for",
"(",
"final",
"AttachmentResource",
"resource",
":",
"email",
".",
"getAttachments",
"(",
")",
")",... | Fills the {@link Message} instance with the attachments from the {@link Email}.
@param email The message in which the attachments are defined.
@param multipartRoot The branch in the email structure in which we'll stuff the attachments.
@throws MessagingException See {@link MimeMultipart#addBodyPart(BodyPart)} and {@link #getBodyPartFromDatasource(AttachmentResource, String)} | [
"Fills",
"the",
"{",
"@link",
"Message",
"}",
"instance",
"with",
"the",
"attachments",
"from",
"the",
"{",
"@link",
"Email",
"}",
"."
] | train | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/converter/internal/mimemessage/MimeMessageHelper.java#L172-L177 |
upwork/java-upwork | src/com/Upwork/api/Routers/Messages.java | Messages.createRoom | public JSONObject createRoom(String company, HashMap<String, String> params) throws JSONException {
return oClient.post("/messages/v3/" + company + "/rooms", params);
} | java | public JSONObject createRoom(String company, HashMap<String, String> params) throws JSONException {
return oClient.post("/messages/v3/" + company + "/rooms", params);
} | [
"public",
"JSONObject",
"createRoom",
"(",
"String",
"company",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"return",
"oClient",
".",
"post",
"(",
"\"/messages/v3/\"",
"+",
"company",
"+",
"\"/rooms\"",
","... | Create a new room
@param company Company ID
@param params Parameters
@throws JSONException If error occurred
@return {@link JSONObject} | [
"Create",
"a",
"new",
"room"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Messages.java#L113-L115 |
phax/ph-pdf-layout | src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java | PDPageContentStreamExt.drawImage | public void drawImage (final PDInlineImage inlineImage, final float x, final float y) throws IOException
{
drawImage (inlineImage, x, y, inlineImage.getWidth (), inlineImage.getHeight ());
} | java | public void drawImage (final PDInlineImage inlineImage, final float x, final float y) throws IOException
{
drawImage (inlineImage, x, y, inlineImage.getWidth (), inlineImage.getHeight ());
} | [
"public",
"void",
"drawImage",
"(",
"final",
"PDInlineImage",
"inlineImage",
",",
"final",
"float",
"x",
",",
"final",
"float",
"y",
")",
"throws",
"IOException",
"{",
"drawImage",
"(",
"inlineImage",
",",
"x",
",",
"y",
",",
"inlineImage",
".",
"getWidth",
... | Draw an inline image at the x,y coordinates, with the default size of the
image.
@param inlineImage
The inline image to draw.
@param x
The x-coordinate to draw the inline image.
@param y
The y-coordinate to draw the inline image.
@throws IOException
If there is an error writing to the stream. | [
"Draw",
"an",
"inline",
"image",
"at",
"the",
"x",
"y",
"coordinates",
"with",
"the",
"default",
"size",
"of",
"the",
"image",
"."
] | train | https://github.com/phax/ph-pdf-layout/blob/777d9f3a131cbe8f592c0de1cf554084e541bb54/src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java#L545-L548 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/context/rule/ExceptionRule.java | ExceptionRule.getMatchedDepth | private int getMatchedDepth(String exceptionType, Class<?> exceptionClass, int depth) {
if (exceptionClass.getName().equals(exceptionType)) {
return depth;
}
if (exceptionClass.equals(Throwable.class)) {
return -1;
}
return getMatchedDepth(exceptionType, exceptionClass.getSuperclass(), depth + 1);
} | java | private int getMatchedDepth(String exceptionType, Class<?> exceptionClass, int depth) {
if (exceptionClass.getName().equals(exceptionType)) {
return depth;
}
if (exceptionClass.equals(Throwable.class)) {
return -1;
}
return getMatchedDepth(exceptionType, exceptionClass.getSuperclass(), depth + 1);
} | [
"private",
"int",
"getMatchedDepth",
"(",
"String",
"exceptionType",
",",
"Class",
"<",
"?",
">",
"exceptionClass",
",",
"int",
"depth",
")",
"{",
"if",
"(",
"exceptionClass",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"exceptionType",
")",
")",
"{",
... | Returns the matched depth.
@param exceptionType the exception type
@param exceptionClass the exception class
@param depth the depth
@return the matched depth | [
"Returns",
"the",
"matched",
"depth",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/context/rule/ExceptionRule.java#L115-L123 |
lessthanoptimal/ejml | main/ejml-simple/src/org/ejml/simple/SimpleEVD.java | SimpleEVD.getEigenvalue | public Complex_F64 getEigenvalue(int index ) {
if( is64 )
return ((EigenDecomposition_F64)eig).getEigenvalue(index);
else {
Complex_F64 c = ((EigenDecomposition_F64)eig).getEigenvalue(index);
return new Complex_F64(c.real, c.imaginary);
}
} | java | public Complex_F64 getEigenvalue(int index ) {
if( is64 )
return ((EigenDecomposition_F64)eig).getEigenvalue(index);
else {
Complex_F64 c = ((EigenDecomposition_F64)eig).getEigenvalue(index);
return new Complex_F64(c.real, c.imaginary);
}
} | [
"public",
"Complex_F64",
"getEigenvalue",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"is64",
")",
"return",
"(",
"(",
"EigenDecomposition_F64",
")",
"eig",
")",
".",
"getEigenvalue",
"(",
"index",
")",
";",
"else",
"{",
"Complex_F64",
"c",
"=",
"(",
"(",
... | <p>
Returns an eigenvalue as a complex number. For symmetric matrices the returned eigenvalue will always be a real
number, which means the imaginary component will be equal to zero.
</p>
<p>
NOTE: The order of the eigenvalues is dependent upon the decomposition algorithm used. This means that they may
or may not be ordered by magnitude. For example the QR algorithm will returns results that are partially
ordered by magnitude, but this behavior should not be relied upon.
</p>
@param index Index of the eigenvalue eigenvector pair.
@return An eigenvalue. | [
"<p",
">",
"Returns",
"an",
"eigenvalue",
"as",
"a",
"complex",
"number",
".",
"For",
"symmetric",
"matrices",
"the",
"returned",
"eigenvalue",
"will",
"always",
"be",
"a",
"real",
"number",
"which",
"means",
"the",
"imaginary",
"component",
"will",
"be",
"e... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/simple/SimpleEVD.java#L106-L113 |
apache/spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java | ExternalShuffleBlockResolver.getBlockData | public ManagedBuffer getBlockData(
String appId,
String execId,
int shuffleId,
int mapId,
int reduceId) {
ExecutorShuffleInfo executor = executors.get(new AppExecId(appId, execId));
if (executor == null) {
throw new RuntimeException(
String.format("Executor is not registered (appId=%s, execId=%s)", appId, execId));
}
return getSortBasedShuffleBlockData(executor, shuffleId, mapId, reduceId);
} | java | public ManagedBuffer getBlockData(
String appId,
String execId,
int shuffleId,
int mapId,
int reduceId) {
ExecutorShuffleInfo executor = executors.get(new AppExecId(appId, execId));
if (executor == null) {
throw new RuntimeException(
String.format("Executor is not registered (appId=%s, execId=%s)", appId, execId));
}
return getSortBasedShuffleBlockData(executor, shuffleId, mapId, reduceId);
} | [
"public",
"ManagedBuffer",
"getBlockData",
"(",
"String",
"appId",
",",
"String",
"execId",
",",
"int",
"shuffleId",
",",
"int",
"mapId",
",",
"int",
"reduceId",
")",
"{",
"ExecutorShuffleInfo",
"executor",
"=",
"executors",
".",
"get",
"(",
"new",
"AppExecId"... | Obtains a FileSegmentManagedBuffer from (shuffleId, mapId, reduceId). We make assumptions
about how the hash and sort based shuffles store their data. | [
"Obtains",
"a",
"FileSegmentManagedBuffer",
"from",
"(",
"shuffleId",
"mapId",
"reduceId",
")",
".",
"We",
"make",
"assumptions",
"about",
"how",
"the",
"hash",
"and",
"sort",
"based",
"shuffles",
"store",
"their",
"data",
"."
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java#L168-L180 |
joniles/mpxj | src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java | ProjectTreeController.addFilters | private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)
{
for (Filter field : filters)
{
final Filter f = field;
MpxjTreeNode childNode = new MpxjTreeNode(field)
{
@Override public String toString()
{
return f.getName();
}
};
parentNode.add(childNode);
}
} | java | private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)
{
for (Filter field : filters)
{
final Filter f = field;
MpxjTreeNode childNode = new MpxjTreeNode(field)
{
@Override public String toString()
{
return f.getName();
}
};
parentNode.add(childNode);
}
} | [
"private",
"void",
"addFilters",
"(",
"MpxjTreeNode",
"parentNode",
",",
"List",
"<",
"Filter",
">",
"filters",
")",
"{",
"for",
"(",
"Filter",
"field",
":",
"filters",
")",
"{",
"final",
"Filter",
"f",
"=",
"field",
";",
"MpxjTreeNode",
"childNode",
"=",
... | Add filters to the tree.
@param parentNode parent tree node
@param filters list of filters | [
"Add",
"filters",
"to",
"the",
"tree",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java#L466-L480 |
google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.initializeModuleScope | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | java | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | [
"private",
"void",
"initializeModuleScope",
"(",
"Node",
"moduleBody",
",",
"Module",
"module",
",",
"TypedScope",
"moduleScope",
")",
"{",
"if",
"(",
"module",
".",
"metadata",
"(",
")",
".",
"isGoogModule",
"(",
")",
")",
"{",
"declareExportsInModuleScope",
... | Builds the beginning of a module-scope. This can be an ES module or a goog.module. | [
"Builds",
"the",
"beginning",
"of",
"a",
"module",
"-",
"scope",
".",
"This",
"can",
"be",
"an",
"ES",
"module",
"or",
"a",
"goog",
".",
"module",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L465-L470 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java | LinearSearch.searchLast | public static int searchLast(double[] doubleArray, double value, int occurrence) {
if(occurrence <= 0 || occurrence > doubleArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = doubleArray.length-1; i >=0; i--) {
if(doubleArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | java | public static int searchLast(double[] doubleArray, double value, int occurrence) {
if(occurrence <= 0 || occurrence > doubleArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = doubleArray.length-1; i >=0; i--) {
if(doubleArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"searchLast",
"(",
"double",
"[",
"]",
"doubleArray",
",",
"double",
"value",
",",
"int",
"occurrence",
")",
"{",
"if",
"(",
"occurrence",
"<=",
"0",
"||",
"occurrence",
">",
"doubleArray",
".",
"length",
")",
"{",
"throw",
"ne... | Search for the value in the double array and return the index of the first occurrence from the
end of the array.
@param doubleArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"double",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"from",
"the",
"end",
"of",
"the",
"array",
"."
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L1710-L1729 |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.createRoleFromUpdateRequest | @POST
@Path("{group}/{id}")
@Consumes("application/x.json-create-role")
public Response createRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id,
CreateEmoRoleRequest request,
@Authenticated Subject subject) {
_uac.createRole(subject, request.setRoleKey(new EmoRoleKey(group, id)));
return Response.created(URI.create(""))
.entity(SuccessResponse.instance())
.build();
} | java | @POST
@Path("{group}/{id}")
@Consumes("application/x.json-create-role")
public Response createRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id,
CreateEmoRoleRequest request,
@Authenticated Subject subject) {
_uac.createRole(subject, request.setRoleKey(new EmoRoleKey(group, id)));
return Response.created(URI.create(""))
.entity(SuccessResponse.instance())
.build();
} | [
"@",
"POST",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"@",
"Consumes",
"(",
"\"application/x.json-create-role\"",
")",
"public",
"Response",
"createRoleFromUpdateRequest",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(... | Alternate endpoint for creating a role. Although slightly less REST compliant it provides a more flexible
interface for specifying role attributes. | [
"Alternate",
"endpoint",
"for",
"creating",
"a",
"role",
".",
"Although",
"slightly",
"less",
"REST",
"compliant",
"it",
"provides",
"a",
"more",
"flexible",
"interface",
"for",
"specifying",
"role",
"attributes",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L100-L110 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/DataDecoder.java | DataDecoder.decodeLongObj | public static Long decodeLongObj(byte[] src, int srcOffset)
throws CorruptEncodingException
{
try {
int b = src[srcOffset];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
return decodeLong(src, srcOffset + 1);
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | java | public static Long decodeLongObj(byte[] src, int srcOffset)
throws CorruptEncodingException
{
try {
int b = src[srcOffset];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
return decodeLong(src, srcOffset + 1);
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | [
"public",
"static",
"Long",
"decodeLongObj",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"srcOffset",
")",
"throws",
"CorruptEncodingException",
"{",
"try",
"{",
"int",
"b",
"=",
"src",
"[",
"srcOffset",
"]",
";",
"if",
"(",
"b",
"==",
"NULL_BYTE_HIGH",
"|... | Decodes a signed Long object from exactly 1 or 9 bytes. If null is
returned, then 1 byte was read.
@param src source of encoded bytes
@param srcOffset offset into source array
@return signed Long object or null | [
"Decodes",
"a",
"signed",
"Long",
"object",
"from",
"exactly",
"1",
"or",
"9",
"bytes",
".",
"If",
"null",
"is",
"returned",
"then",
"1",
"byte",
"was",
"read",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataDecoder.java#L114-L126 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java | MapTileCircuitModel.getCircuitOverTransition | private Circuit getCircuitOverTransition(Circuit circuit, Tile neighbor)
{
final String group = getTransitiveGroup(circuit, neighbor);
final Circuit newCircuit;
if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getIn()))
{
newCircuit = new Circuit(circuit.getType(), group, circuit.getOut());
}
else if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getOut()))
{
newCircuit = new Circuit(circuit.getType(), circuit.getIn(), group);
}
else
{
newCircuit = circuit;
}
return newCircuit;
} | java | private Circuit getCircuitOverTransition(Circuit circuit, Tile neighbor)
{
final String group = getTransitiveGroup(circuit, neighbor);
final Circuit newCircuit;
if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getIn()))
{
newCircuit = new Circuit(circuit.getType(), group, circuit.getOut());
}
else if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getOut()))
{
newCircuit = new Circuit(circuit.getType(), circuit.getIn(), group);
}
else
{
newCircuit = circuit;
}
return newCircuit;
} | [
"private",
"Circuit",
"getCircuitOverTransition",
"(",
"Circuit",
"circuit",
",",
"Tile",
"neighbor",
")",
"{",
"final",
"String",
"group",
"=",
"getTransitiveGroup",
"(",
"circuit",
",",
"neighbor",
")",
";",
"final",
"Circuit",
"newCircuit",
";",
"if",
"(",
... | Get the circuit, supporting over existing transition.
@param circuit The initial circuit.
@param neighbor The neighbor tile which can be a transition.
@return The new circuit or original one. | [
"Get",
"the",
"circuit",
"supporting",
"over",
"existing",
"transition",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java#L177-L194 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.2/src/com/ibm/ws/microprofile/config12/impl/Config12ConversionManager.java | Config12ConversionManager.implicitConverters | @Override
protected <T> ConversionStatus implicitConverters(String rawString, Class<T> type) {
ConversionStatus status = new ConversionStatus();
BuiltInConverter automaticConverter = getConverter(type);
//will be null if a suitable string constructor method could not be found
if (automaticConverter != null) {
try {
Object converted = automaticConverter.convert(rawString);
status.setConverted(converted);
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, e);
}
throw e;
} catch (Throwable t) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, t);
}
throw new ConfigException(t);
}
}
return status;
} | java | @Override
protected <T> ConversionStatus implicitConverters(String rawString, Class<T> type) {
ConversionStatus status = new ConversionStatus();
BuiltInConverter automaticConverter = getConverter(type);
//will be null if a suitable string constructor method could not be found
if (automaticConverter != null) {
try {
Object converted = automaticConverter.convert(rawString);
status.setConverted(converted);
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, e);
}
throw e;
} catch (Throwable t) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, t);
}
throw new ConfigException(t);
}
}
return status;
} | [
"@",
"Override",
"protected",
"<",
"T",
">",
"ConversionStatus",
"implicitConverters",
"(",
"String",
"rawString",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"ConversionStatus",
"status",
"=",
"new",
"ConversionStatus",
"(",
")",
";",
"BuiltInConverter",
"... | Attempt to apply a valueOf or T(String s) constructor
@param rawString
@param type
@return a converted T object | [
"Attempt",
"to",
"apply",
"a",
"valueOf",
"or",
"T",
"(",
"String",
"s",
")",
"constructor"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.2/src/com/ibm/ws/microprofile/config12/impl/Config12ConversionManager.java#L42-L66 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java | KeyValueHandler.handleSnappyDecompression | private void handleSnappyDecompression(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse response) {
ByteBuf decompressed;
if (response.content().readableBytes() > 0) {
// we need to copy it on-heap...
byte[] compressed = Unpooled.copiedBuffer(response.content()).array();
try {
decompressed = Unpooled.wrappedBuffer(Snappy.uncompress(compressed, 0, compressed.length));
} catch (Exception ex) {
throw new RuntimeException("Could not decode snappy-compressed value.", ex);
}
} else {
decompressed = Unpooled.buffer(0);
}
response.content().release();
response.setContent(decompressed);
response.setTotalBodyLength(
response.getExtrasLength()
+ response.getKeyLength()
+ decompressed.readableBytes()
);
response.setDataType((byte) (response.getDataType() & ~DATATYPE_SNAPPY));
} | java | private void handleSnappyDecompression(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse response) {
ByteBuf decompressed;
if (response.content().readableBytes() > 0) {
// we need to copy it on-heap...
byte[] compressed = Unpooled.copiedBuffer(response.content()).array();
try {
decompressed = Unpooled.wrappedBuffer(Snappy.uncompress(compressed, 0, compressed.length));
} catch (Exception ex) {
throw new RuntimeException("Could not decode snappy-compressed value.", ex);
}
} else {
decompressed = Unpooled.buffer(0);
}
response.content().release();
response.setContent(decompressed);
response.setTotalBodyLength(
response.getExtrasLength()
+ response.getKeyLength()
+ decompressed.readableBytes()
);
response.setDataType((byte) (response.getDataType() & ~DATATYPE_SNAPPY));
} | [
"private",
"void",
"handleSnappyDecompression",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"FullBinaryMemcacheResponse",
"response",
")",
"{",
"ByteBuf",
"decompressed",
";",
"if",
"(",
"response",
".",
"content",
"(",
")",
".",
"readableBytes",
"("... | Helper method which performs decompression for snappy compressed values. | [
"Helper",
"method",
"which",
"performs",
"decompression",
"for",
"snappy",
"compressed",
"values",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L389-L412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.