repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
albfernandez/itext2 | src/main/java/com/lowagie/text/xml/SAXmyHandler.java | SAXmyHandler.startElement | public void startElement(String uri, String lname, String name, Attributes attrs) {
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
handleStartingTags(peer.getTag(), peer.getAttributes(attrs));
}
else {
Properties attributes = new Properties();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i);
attributes.setProperty(attribute, attrs.getValue(i));
}
}
handleStartingTags(name, attributes);
}
} | java | public void startElement(String uri, String lname, String name, Attributes attrs) {
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
handleStartingTags(peer.getTag(), peer.getAttributes(attrs));
}
else {
Properties attributes = new Properties();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i);
attributes.setProperty(attribute, attrs.getValue(i));
}
}
handleStartingTags(name, attributes);
}
} | [
"public",
"void",
"startElement",
"(",
"String",
"uri",
",",
"String",
"lname",
",",
"String",
"name",
",",
"Attributes",
"attrs",
")",
"{",
"if",
"(",
"myTags",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"XmlPeer",
"peer",
"=",
"(",
"XmlPeer",
")... | This method gets called when a start tag is encountered.
@param uri the Uniform Resource Identifier
@param lname the local name (without prefix), or the empty string if Namespace processing is not being performed.
@param name the name of the tag that is encountered
@param attrs the list of attributes | [
"This",
"method",
"gets",
"called",
"when",
"a",
"start",
"tag",
"is",
"encountered",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/xml/SAXmyHandler.java#L86-L101 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigRational.java | BigRational.valueOf | public static BigRational valueOf(int numerator, int denominator) {
return of(BigDecimal.valueOf(numerator), BigDecimal.valueOf(denominator));
} | java | public static BigRational valueOf(int numerator, int denominator) {
return of(BigDecimal.valueOf(numerator), BigDecimal.valueOf(denominator));
} | [
"public",
"static",
"BigRational",
"valueOf",
"(",
"int",
"numerator",
",",
"int",
"denominator",
")",
"{",
"return",
"of",
"(",
"BigDecimal",
".",
"valueOf",
"(",
"numerator",
")",
",",
"BigDecimal",
".",
"valueOf",
"(",
"denominator",
")",
")",
";",
"}"
... | Creates a rational number of the specified numerator/denominator int values.
@param numerator the numerator int value
@param denominator the denominator int value (0 not allowed)
@return the rational number
@throws ArithmeticException if the denominator is 0 (division by zero) | [
"Creates",
"a",
"rational",
"number",
"of",
"the",
"specified",
"numerator",
"/",
"denominator",
"int",
"values",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigRational.java#L825-L827 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/io/MPIO.java | MPIO.isCompatibleME | public boolean isCompatibleME(SIBUuid8 meUuid, ProtocolVersion version)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "isCompatibleME", new Object[] {meUuid});
boolean result = false;
MPConnection conn = findMPConnection(meUuid);
if (conn!=null)
{
// If the other ME is an older version then we are incompatible
ProtocolVersion otherVersion = conn.getVersion();
if (otherVersion != null && otherVersion.compareTo(version) >= 0)
result = true;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "isCompatibleME", Boolean.valueOf(result));
return result;
} | java | public boolean isCompatibleME(SIBUuid8 meUuid, ProtocolVersion version)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "isCompatibleME", new Object[] {meUuid});
boolean result = false;
MPConnection conn = findMPConnection(meUuid);
if (conn!=null)
{
// If the other ME is an older version then we are incompatible
ProtocolVersion otherVersion = conn.getVersion();
if (otherVersion != null && otherVersion.compareTo(version) >= 0)
result = true;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "isCompatibleME", Boolean.valueOf(result));
return result;
} | [
"public",
"boolean",
"isCompatibleME",
"(",
"SIBUuid8",
"meUuid",
",",
"ProtocolVersion",
"version",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"t... | Test whether or not a particular ME is of a version compatible with this one.
@param me The ME to test.
@return True if ME is of a compatible version | [
"Test",
"whether",
"or",
"not",
"a",
"particular",
"ME",
"is",
"of",
"a",
"version",
"compatible",
"with",
"this",
"one",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/io/MPIO.java#L628-L647 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnGetConvolutionForwardWorkspaceSize | public static int cudnnGetConvolutionForwardWorkspaceSize(
cudnnHandle handle,
cudnnTensorDescriptor xDesc,
cudnnFilterDescriptor wDesc,
cudnnConvolutionDescriptor convDesc,
cudnnTensorDescriptor yDesc,
int algo,
long[] sizeInBytes)
{
return checkResult(cudnnGetConvolutionForwardWorkspaceSizeNative(handle, xDesc, wDesc, convDesc, yDesc, algo, sizeInBytes));
} | java | public static int cudnnGetConvolutionForwardWorkspaceSize(
cudnnHandle handle,
cudnnTensorDescriptor xDesc,
cudnnFilterDescriptor wDesc,
cudnnConvolutionDescriptor convDesc,
cudnnTensorDescriptor yDesc,
int algo,
long[] sizeInBytes)
{
return checkResult(cudnnGetConvolutionForwardWorkspaceSizeNative(handle, xDesc, wDesc, convDesc, yDesc, algo, sizeInBytes));
} | [
"public",
"static",
"int",
"cudnnGetConvolutionForwardWorkspaceSize",
"(",
"cudnnHandle",
"handle",
",",
"cudnnTensorDescriptor",
"xDesc",
",",
"cudnnFilterDescriptor",
"wDesc",
",",
"cudnnConvolutionDescriptor",
"convDesc",
",",
"cudnnTensorDescriptor",
"yDesc",
",",
"int",
... | Helper function to return the minimum size of the workspace to be passed to the convolution given an algo | [
"Helper",
"function",
"to",
"return",
"the",
"minimum",
"size",
"of",
"the",
"workspace",
"to",
"be",
"passed",
"to",
"the",
"convolution",
"given",
"an",
"algo"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L1133-L1143 |
getlantern/kaleidoscope | src/main/java/org/kaleidoscope/TrustGraphNode.java | TrustGraphNode.forwardAdvertisement | protected boolean forwardAdvertisement(TrustGraphAdvertisement message) {
// don't forward if the forwarding policy rejects
if (!shouldForward(message)) {
return false;
}
// determine the next hop to send to
TrustGraphNodeId nextHop = getRoutingTable().getNextHop(message);
// if there is no next hop, reject
if (nextHop == null) {
return false;
}
// forward the message to the next node on the route
// with ttl decreased by 1
sendAdvertisement(message, nextHop, message.getInboundTTL() - 1);
return true;
} | java | protected boolean forwardAdvertisement(TrustGraphAdvertisement message) {
// don't forward if the forwarding policy rejects
if (!shouldForward(message)) {
return false;
}
// determine the next hop to send to
TrustGraphNodeId nextHop = getRoutingTable().getNextHop(message);
// if there is no next hop, reject
if (nextHop == null) {
return false;
}
// forward the message to the next node on the route
// with ttl decreased by 1
sendAdvertisement(message, nextHop, message.getInboundTTL() - 1);
return true;
} | [
"protected",
"boolean",
"forwardAdvertisement",
"(",
"TrustGraphAdvertisement",
"message",
")",
"{",
"// don't forward if the forwarding policy rejects",
"if",
"(",
"!",
"shouldForward",
"(",
"message",
")",
")",
"{",
"return",
"false",
";",
"}",
"// determine the next ho... | This method performs the forwarding behavior for a received
message. The message is forwarded to the next hop on the
route according to the routing table, with ttl decreased by 1.
The message is dropped if it has an invalid hop count or
the sender of the message is not a known peer (ie is not
paired to another outbound neighbor)
@return true if and only if the message was forwarded | [
"This",
"method",
"performs",
"the",
"forwarding",
"behavior",
"for",
"a",
"received",
"message",
".",
"The",
"message",
"is",
"forwarded",
"to",
"the",
"next",
"hop",
"on",
"the",
"route",
"according",
"to",
"the",
"routing",
"table",
"with",
"ttl",
"decrea... | train | https://github.com/getlantern/kaleidoscope/blob/7516f05724c8f54e5d535d23da9116817c08a09f/src/main/java/org/kaleidoscope/TrustGraphNode.java#L254-L273 |
iipc/webarchive-commons | src/main/java/org/archive/io/ArchiveReader.java | ArchiveReader.logStdErr | public void logStdErr(Level level, String message) {
System.err.println(level.toString() + " " + message);
} | java | public void logStdErr(Level level, String message) {
System.err.println(level.toString() + " " + message);
} | [
"public",
"void",
"logStdErr",
"(",
"Level",
"level",
",",
"String",
"message",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"level",
".",
"toString",
"(",
")",
"+",
"\" \"",
"+",
"message",
")",
";",
"}"
] | Log on stderr.
Logging should go via the logging system. This method
bypasses the logging system going direct to stderr.
Should not generally be used. Its used for rare messages
that come of cmdline usage of ARCReader ERRORs and WARNINGs.
Override if using ARCReader in a context where no stderr or
where you'd like to redirect stderr to other than System.err.
@param level Level to log message at.
@param message Message to log. | [
"Log",
"on",
"stderr",
".",
"Logging",
"should",
"go",
"via",
"the",
"logging",
"system",
".",
"This",
"method",
"bypasses",
"the",
"logging",
"system",
"going",
"direct",
"to",
"stderr",
".",
"Should",
"not",
"generally",
"be",
"used",
".",
"Its",
"used",... | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/ArchiveReader.java#L389-L391 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java | JDBCStorableGenerator.closeStatement | private void closeStatement
(CodeBuilder b, LocalVariable statementVar, Label tryAfterStatement)
{
Label contLabel = b.createLabel();
Label endFinallyLabel = b.createLabel().setLocation();
b.loadLocal(statementVar);
b.invokeInterface(TypeDesc.forClass(Statement.class), "close", null, null);
b.branch(contLabel);
b.exceptionHandler(tryAfterStatement, endFinallyLabel, null);
b.loadLocal(statementVar);
b.invokeInterface(TypeDesc.forClass(Statement.class), "close", null, null);
b.throwObject();
contLabel.setLocation();
} | java | private void closeStatement
(CodeBuilder b, LocalVariable statementVar, Label tryAfterStatement)
{
Label contLabel = b.createLabel();
Label endFinallyLabel = b.createLabel().setLocation();
b.loadLocal(statementVar);
b.invokeInterface(TypeDesc.forClass(Statement.class), "close", null, null);
b.branch(contLabel);
b.exceptionHandler(tryAfterStatement, endFinallyLabel, null);
b.loadLocal(statementVar);
b.invokeInterface(TypeDesc.forClass(Statement.class), "close", null, null);
b.throwObject();
contLabel.setLocation();
} | [
"private",
"void",
"closeStatement",
"(",
"CodeBuilder",
"b",
",",
"LocalVariable",
"statementVar",
",",
"Label",
"tryAfterStatement",
")",
"{",
"Label",
"contLabel",
"=",
"b",
".",
"createLabel",
"(",
")",
";",
"Label",
"endFinallyLabel",
"=",
"b",
".",
"crea... | Generates code which emulates this:
...
} finally {
statement.close();
}
@param statementVar Statement variable
@param tryAfterStatement label right after Statement acquisition | [
"Generates",
"code",
"which",
"emulates",
"this",
":"
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java#L1886-L1902 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java | BaseProfile.generateMbeanXml | void generateMbeanXml(Definition def, String outputDir)
{
String mbeanName = def.getDefaultValue().toLowerCase(Locale.US);
if (def.getRaPackage() != null && !def.getRaPackage().equals(""))
{
if (def.getRaPackage().indexOf('.') >= 0)
{
mbeanName = def.getRaPackage().substring(def.getRaPackage().lastIndexOf('.') + 1);
}
else
mbeanName = def.getRaPackage();
}
try
{
outputDir = outputDir + File.separatorChar + "src" + File.separatorChar +
"main" + File.separatorChar + "resources" + File.separatorChar + "jca";
FileWriter mbfw = Utils.createFile(mbeanName + ".xml", outputDir);
MbeanXmlGen mbGen = new MbeanXmlGen();
mbGen.generate(def, mbfw);
mbfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | java | void generateMbeanXml(Definition def, String outputDir)
{
String mbeanName = def.getDefaultValue().toLowerCase(Locale.US);
if (def.getRaPackage() != null && !def.getRaPackage().equals(""))
{
if (def.getRaPackage().indexOf('.') >= 0)
{
mbeanName = def.getRaPackage().substring(def.getRaPackage().lastIndexOf('.') + 1);
}
else
mbeanName = def.getRaPackage();
}
try
{
outputDir = outputDir + File.separatorChar + "src" + File.separatorChar +
"main" + File.separatorChar + "resources" + File.separatorChar + "jca";
FileWriter mbfw = Utils.createFile(mbeanName + ".xml", outputDir);
MbeanXmlGen mbGen = new MbeanXmlGen();
mbGen.generate(def, mbfw);
mbfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | [
"void",
"generateMbeanXml",
"(",
"Definition",
"def",
",",
"String",
"outputDir",
")",
"{",
"String",
"mbeanName",
"=",
"def",
".",
"getDefaultValue",
"(",
")",
".",
"toLowerCase",
"(",
"Locale",
".",
"US",
")",
";",
"if",
"(",
"def",
".",
"getRaPackage",
... | generate mbean deployment xml
@param def Definition
@param outputDir output directory | [
"generate",
"mbean",
"deployment",
"xml"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java#L510-L536 |
flow/caustic | api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java | MeshGenerator.generateNormals | public static TFloatList generateNormals(TFloatList positions, TIntList indices) {
final TFloatList normals = new TFloatArrayList();
generateNormals(positions, indices, normals);
return normals;
} | java | public static TFloatList generateNormals(TFloatList positions, TIntList indices) {
final TFloatList normals = new TFloatArrayList();
generateNormals(positions, indices, normals);
return normals;
} | [
"public",
"static",
"TFloatList",
"generateNormals",
"(",
"TFloatList",
"positions",
",",
"TIntList",
"indices",
")",
"{",
"final",
"TFloatList",
"normals",
"=",
"new",
"TFloatArrayList",
"(",
")",
";",
"generateNormals",
"(",
"positions",
",",
"indices",
",",
"... | Generate the normals for the positions, according to the indices. This assumes that the positions have 3 components, in the x, y, z order. The normals are stored as a 3 component vector, in the
x, y, z order.
@param positions The position components
@param indices The indices
@return The normals | [
"Generate",
"the",
"normals",
"for",
"the",
"positions",
"according",
"to",
"the",
"indices",
".",
"This",
"assumes",
"that",
"the",
"positions",
"have",
"3",
"components",
"in",
"the",
"x",
"y",
"z",
"order",
".",
"The",
"normals",
"are",
"stored",
"as",
... | train | https://github.com/flow/caustic/blob/88652fcf0621ce158a0e92ce4c570ed6b1f6fca9/api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java#L142-L146 |
yangjm/winlet | utils/src/main/java/com/aggrepoint/utils/CollectionUtils.java | CollectionUtils.toHashMap | public static <T, K> HashMap<K, T> toHashMap(Collection<T> entities,
Function<T, K> keyMapper) {
return toMap(entities, keyMapper, HashMap<K, T>::new);
} | java | public static <T, K> HashMap<K, T> toHashMap(Collection<T> entities,
Function<T, K> keyMapper) {
return toMap(entities, keyMapper, HashMap<K, T>::new);
} | [
"public",
"static",
"<",
"T",
",",
"K",
">",
"HashMap",
"<",
"K",
",",
"T",
">",
"toHashMap",
"(",
"Collection",
"<",
"T",
">",
"entities",
",",
"Function",
"<",
"T",
",",
"K",
">",
"keyMapper",
")",
"{",
"return",
"toMap",
"(",
"entities",
",",
... | Convert a collection to HashMap, The key is decided by keyMapper, value
is the object in collection
@param entities
@param keyMapper
@return | [
"Convert",
"a",
"collection",
"to",
"HashMap",
"The",
"key",
"is",
"decided",
"by",
"keyMapper",
"value",
"is",
"the",
"object",
"in",
"collection"
] | train | https://github.com/yangjm/winlet/blob/2126236f56858e283fa6ad69fe9279ee30f47b67/utils/src/main/java/com/aggrepoint/utils/CollectionUtils.java#L98-L101 |
UrielCh/ovh-java-sdk | ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java | ApiOvhHorizonView.serviceName_customerNetwork_customerNetworkId_GET | public OvhCustomerNetwork serviceName_customerNetwork_customerNetworkId_GET(String serviceName, Long customerNetworkId) throws IOException {
String qPath = "/horizonView/{serviceName}/customerNetwork/{customerNetworkId}";
StringBuilder sb = path(qPath, serviceName, customerNetworkId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhCustomerNetwork.class);
} | java | public OvhCustomerNetwork serviceName_customerNetwork_customerNetworkId_GET(String serviceName, Long customerNetworkId) throws IOException {
String qPath = "/horizonView/{serviceName}/customerNetwork/{customerNetworkId}";
StringBuilder sb = path(qPath, serviceName, customerNetworkId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhCustomerNetwork.class);
} | [
"public",
"OvhCustomerNetwork",
"serviceName_customerNetwork_customerNetworkId_GET",
"(",
"String",
"serviceName",
",",
"Long",
"customerNetworkId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/horizonView/{serviceName}/customerNetwork/{customerNetworkId}\"",
";",... | Get this object properties
REST: GET /horizonView/{serviceName}/customerNetwork/{customerNetworkId}
@param serviceName [required] Domain of the service
@param customerNetworkId [required] Customer Network id | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java#L431-L436 |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java | UserDefinedTypeBuilder.withField | public UserDefinedTypeBuilder withField(CqlIdentifier name, DataType type) {
fieldNames.add(name);
fieldTypes.add(type);
return this;
} | java | public UserDefinedTypeBuilder withField(CqlIdentifier name, DataType type) {
fieldNames.add(name);
fieldTypes.add(type);
return this;
} | [
"public",
"UserDefinedTypeBuilder",
"withField",
"(",
"CqlIdentifier",
"name",
",",
"DataType",
"type",
")",
"{",
"fieldNames",
".",
"add",
"(",
"name",
")",
";",
"fieldTypes",
".",
"add",
"(",
"type",
")",
";",
"return",
"this",
";",
"}"
] | Adds a new field. The fields in the resulting type will be in the order of the calls to this
method. | [
"Adds",
"a",
"new",
"field",
".",
"The",
"fields",
"in",
"the",
"resulting",
"type",
"will",
"be",
"in",
"the",
"order",
"of",
"the",
"calls",
"to",
"this",
"method",
"."
] | train | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java#L56-L60 |
upwork/java-upwork | src/com/Upwork/api/Routers/Workdays.java | Workdays.getByContract | public JSONObject getByContract(String contract, String fromDate, String tillDate, HashMap<String, String> params) throws JSONException {
return oClient.get("/team/v3/workdays/contracts/" + contract + "/" + fromDate + "," + tillDate, params);
} | java | public JSONObject getByContract(String contract, String fromDate, String tillDate, HashMap<String, String> params) throws JSONException {
return oClient.get("/team/v3/workdays/contracts/" + contract + "/" + fromDate + "," + tillDate, params);
} | [
"public",
"JSONObject",
"getByContract",
"(",
"String",
"contract",
",",
"String",
"fromDate",
",",
"String",
"tillDate",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"return",
"oClient",
".",
"get",
"(",
... | Get Workdays by Contract
@param contract Contract ID
@param fromDate Start date
@param tillDate End date
@param params (Optional) Parameters
@throws JSONException If error occurred
@return {@link JSONObject} | [
"Get",
"Workdays",
"by",
"Contract"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Workdays.java#L70-L72 |
playn/playn | core/src/playn/core/json/JsonObject.java | JsonObject.getObject | public Json.Object getObject(String key, Json.Object default_) {
Object o = get(key);
return (o instanceof JsonObject) ? (JsonObject)o : default_;
} | java | public Json.Object getObject(String key, Json.Object default_) {
Object o = get(key);
return (o instanceof JsonObject) ? (JsonObject)o : default_;
} | [
"public",
"Json",
".",
"Object",
"getObject",
"(",
"String",
"key",
",",
"Json",
".",
"Object",
"default_",
")",
"{",
"Object",
"o",
"=",
"get",
"(",
"key",
")",
";",
"return",
"(",
"o",
"instanceof",
"JsonObject",
")",
"?",
"(",
"JsonObject",
")",
"... | Returns the {@link JsonObject} at the given key, or the default if it does not exist or is the
wrong type. | [
"Returns",
"the",
"{"
] | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonObject.java#L156-L159 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForView | public boolean waitForView(int id){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+id+")");
}
return waitForView(id, 0, Timeout.getLargeTimeout(), true);
} | java | public boolean waitForView(int id){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+id+")");
}
return waitForView(id, 0, Timeout.getLargeTimeout(), true);
} | [
"public",
"boolean",
"waitForView",
"(",
"int",
"id",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"waitForView(\"",
"+",
"id",
"+",
"\")\"",
")",
";",
"}",
"return",
"... | Waits for a View matching the specified resource id. Default timeout is 20 seconds.
@param id the R.id of the {@link View} to wait for
@return {@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout | [
"Waits",
"for",
"a",
"View",
"matching",
"the",
"specified",
"resource",
"id",
".",
"Default",
"timeout",
"is",
"20",
"seconds",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L451-L457 |
googleads/googleads-java-lib | modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java | DateTimesHelper.dateToString | public String dateToString(D date) {
try {
return String.format(DATE_PATTERN,
(Integer) PropertyUtils.getProperty(date, "year"),
(Integer) PropertyUtils.getProperty(date, "month"),
(Integer) PropertyUtils.getProperty(date, "day"));
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not access class.", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not get field.", e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not get field.", e);
}
} | java | public String dateToString(D date) {
try {
return String.format(DATE_PATTERN,
(Integer) PropertyUtils.getProperty(date, "year"),
(Integer) PropertyUtils.getProperty(date, "month"),
(Integer) PropertyUtils.getProperty(date, "day"));
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not access class.", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not get field.", e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not get field.", e);
}
} | [
"public",
"String",
"dateToString",
"(",
"D",
"date",
")",
"{",
"try",
"{",
"return",
"String",
".",
"format",
"(",
"DATE_PATTERN",
",",
"(",
"Integer",
")",
"PropertyUtils",
".",
"getProperty",
"(",
"date",
",",
"\"year\"",
")",
",",
"(",
"Integer",
")"... | Returns string representation of this date.
@param date the date to stringify
@return a string representation of the {@code Date} in {@code yyyy-MM-dd} | [
"Returns",
"string",
"representation",
"of",
"this",
"date",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java#L129-L142 |
mapsforge/mapsforge | sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java | DatabaseUtils.blobFileDescriptorForQuery | public static ParcelFileDescriptor blobFileDescriptorForQuery(SQLiteDatabase db,
String query, String[] selectionArgs) {
SQLiteStatement prog = db.compileStatement(query);
try {
return blobFileDescriptorForQuery(prog, selectionArgs);
} finally {
prog.close();
}
} | java | public static ParcelFileDescriptor blobFileDescriptorForQuery(SQLiteDatabase db,
String query, String[] selectionArgs) {
SQLiteStatement prog = db.compileStatement(query);
try {
return blobFileDescriptorForQuery(prog, selectionArgs);
} finally {
prog.close();
}
} | [
"public",
"static",
"ParcelFileDescriptor",
"blobFileDescriptorForQuery",
"(",
"SQLiteDatabase",
"db",
",",
"String",
"query",
",",
"String",
"[",
"]",
"selectionArgs",
")",
"{",
"SQLiteStatement",
"prog",
"=",
"db",
".",
"compileStatement",
"(",
"query",
")",
";"... | Utility method to run the query on the db and return the blob value in the
first column of the first row.
@return A read-only file descriptor for a copy of the blob value. | [
"Utility",
"method",
"to",
"run",
"the",
"query",
"on",
"the",
"db",
"and",
"return",
"the",
"blob",
"value",
"in",
"the",
"first",
"column",
"of",
"the",
"first",
"row",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L878-L886 |
SeaCloudsEU/SeaCloudsPlatform | discoverer/src/main/java/eu/seaclouds/platform/discoverer/core/Offering.java | Offering.addProperty | public boolean addProperty(String propertyName, String property) {
boolean ret = this.properties.containsKey(propertyName);
this.properties.put(propertyName, property);
return ret;
} | java | public boolean addProperty(String propertyName, String property) {
boolean ret = this.properties.containsKey(propertyName);
this.properties.put(propertyName, property);
return ret;
} | [
"public",
"boolean",
"addProperty",
"(",
"String",
"propertyName",
",",
"String",
"property",
")",
"{",
"boolean",
"ret",
"=",
"this",
".",
"properties",
".",
"containsKey",
"(",
"propertyName",
")",
";",
"this",
".",
"properties",
".",
"put",
"(",
"property... | Used to add a new property to the offering
@param propertyName the name of the property
@param property the value of the property
@return true if the property was already present (and it has been replaced), false otherwise | [
"Used",
"to",
"add",
"a",
"new",
"property",
"to",
"the",
"offering"
] | train | https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/discoverer/src/main/java/eu/seaclouds/platform/discoverer/core/Offering.java#L56-L60 |
before/uadetector | modules/uadetector-core/src/main/java/net/sf/uadetector/internal/util/UrlUtil.java | UrlUtil.build | public static URL build(@Nonnull final String url) {
Check.notNull(url, "url");
URL ret = null;
try {
ret = new URL(url);
} catch (final MalformedURLException e) {
throw new IllegalStateOfArgumentException("The given string is not a valid URL: " + url, e);
}
return ret;
} | java | public static URL build(@Nonnull final String url) {
Check.notNull(url, "url");
URL ret = null;
try {
ret = new URL(url);
} catch (final MalformedURLException e) {
throw new IllegalStateOfArgumentException("The given string is not a valid URL: " + url, e);
}
return ret;
} | [
"public",
"static",
"URL",
"build",
"(",
"@",
"Nonnull",
"final",
"String",
"url",
")",
"{",
"Check",
".",
"notNull",
"(",
"url",
",",
"\"url\"",
")",
";",
"URL",
"ret",
"=",
"null",
";",
"try",
"{",
"ret",
"=",
"new",
"URL",
"(",
"url",
")",
";"... | Creates an {@code URL} instance from the given {@code String} representation.<br>
<br>
This method tunnels a {@link MalformedURLException} by an {@link IllegalStateOfArgumentException}.
@param url
{@code String} representation of an {@code URL}
@return new {@code URL} instance
@throws net.sf.qualitycheck.exception.IllegalNullArgumentException
if the given argument is {@code null}
@throws IllegalStateOfArgumentException
if the string representation of the given URL is invalid and a {@link MalformedURLException} occurs | [
"Creates",
"an",
"{",
"@code",
"URL",
"}",
"instance",
"from",
"the",
"given",
"{",
"@code",
"String",
"}",
"representation",
".",
"<br",
">",
"<br",
">",
"This",
"method",
"tunnels",
"a",
"{",
"@link",
"MalformedURLException",
"}",
"by",
"an",
"{",
"@li... | train | https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/internal/util/UrlUtil.java#L56-L66 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.eachRow | public void eachRow(GString gstring, @ClosureParams(value=SimpleType.class, options="groovy.sql.GroovyResultSet") Closure closure) throws SQLException {
eachRow(gstring, null, closure);
} | java | public void eachRow(GString gstring, @ClosureParams(value=SimpleType.class, options="groovy.sql.GroovyResultSet") Closure closure) throws SQLException {
eachRow(gstring, null, closure);
} | [
"public",
"void",
"eachRow",
"(",
"GString",
"gstring",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"groovy.sql.GroovyResultSet\"",
")",
"Closure",
"closure",
")",
"throws",
"SQLException",
"{",
"eachRow",
"("... | Performs the given SQL query calling the given Closure with each row of the result set.
The row will be a <code>GroovyResultSet</code> which is a <code>ResultSet</code>
that supports accessing the fields using property style notation and ordinal index values.
The query may contain GString expressions.
<p>
Example usage:
<pre>
def location = 25
sql.eachRow("select * from PERSON where location_id {@code <} $location") { row {@code ->}
println row.firstname
}
</pre>
<p>
Resource handling is performed automatically where appropriate.
@param gstring a GString containing the SQL query with embedded params
@param closure called for each row with a GroovyResultSet
@throws SQLException if a database access error occurs
@see #expand(Object) | [
"Performs",
"the",
"given",
"SQL",
"query",
"calling",
"the",
"given",
"Closure",
"with",
"each",
"row",
"of",
"the",
"result",
"set",
".",
"The",
"row",
"will",
"be",
"a",
"<code",
">",
"GroovyResultSet<",
"/",
"code",
">",
"which",
"is",
"a",
"<code",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L1651-L1653 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java | PolylineSplitMerge.maximumDistance | static int maximumDistance(List<Point2D_I32> contour , int indexA , int indexB ) {
Point2D_I32 a = contour.get(indexA);
Point2D_I32 b = contour.get(indexB);
int best = -1;
double bestDistance = -Double.MAX_VALUE;
for (int i = 0; i < contour.size(); i++) {
Point2D_I32 c = contour.get(i);
// can't sum sq distance because some skinny shapes it maximizes one and not the other
// double d = Math.sqrt(distanceSq(a,c)) + Math.sqrt(distanceSq(b,c));
double d = distanceAbs(a,c) + distanceAbs(b,c);
if( d > bestDistance ) {
bestDistance = d;
best = i;
}
}
return best;
} | java | static int maximumDistance(List<Point2D_I32> contour , int indexA , int indexB ) {
Point2D_I32 a = contour.get(indexA);
Point2D_I32 b = contour.get(indexB);
int best = -1;
double bestDistance = -Double.MAX_VALUE;
for (int i = 0; i < contour.size(); i++) {
Point2D_I32 c = contour.get(i);
// can't sum sq distance because some skinny shapes it maximizes one and not the other
// double d = Math.sqrt(distanceSq(a,c)) + Math.sqrt(distanceSq(b,c));
double d = distanceAbs(a,c) + distanceAbs(b,c);
if( d > bestDistance ) {
bestDistance = d;
best = i;
}
}
return best;
} | [
"static",
"int",
"maximumDistance",
"(",
"List",
"<",
"Point2D_I32",
">",
"contour",
",",
"int",
"indexA",
",",
"int",
"indexB",
")",
"{",
"Point2D_I32",
"a",
"=",
"contour",
".",
"get",
"(",
"indexA",
")",
";",
"Point2D_I32",
"b",
"=",
"contour",
".",
... | Finds the point in the contour which maximizes the distance between points A
and B.
@param contour List of all pointsi n the contour
@param indexA Index of point A
@param indexB Index of point B
@return Index of maximal distant point | [
"Finds",
"the",
"point",
"in",
"the",
"contour",
"which",
"maximizes",
"the",
"distance",
"between",
"points",
"A",
"and",
"B",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java#L597-L616 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.getUserAlias | private UserAlias getUserAlias(Object attribute)
{
if (m_userAlias != null)
{
return m_userAlias;
}
if (!(attribute instanceof String))
{
return null;
}
if (m_alias == null)
{
return null;
}
if (m_aliasPath == null)
{
boolean allPathsAliased = true;
return new UserAlias(m_alias, (String)attribute, allPathsAliased);
}
return new UserAlias(m_alias, (String)attribute, m_aliasPath);
} | java | private UserAlias getUserAlias(Object attribute)
{
if (m_userAlias != null)
{
return m_userAlias;
}
if (!(attribute instanceof String))
{
return null;
}
if (m_alias == null)
{
return null;
}
if (m_aliasPath == null)
{
boolean allPathsAliased = true;
return new UserAlias(m_alias, (String)attribute, allPathsAliased);
}
return new UserAlias(m_alias, (String)attribute, m_aliasPath);
} | [
"private",
"UserAlias",
"getUserAlias",
"(",
"Object",
"attribute",
")",
"{",
"if",
"(",
"m_userAlias",
"!=",
"null",
")",
"{",
"return",
"m_userAlias",
";",
"}",
"if",
"(",
"!",
"(",
"attribute",
"instanceof",
"String",
")",
")",
"{",
"return",
"null",
... | Retrieves or if necessary, creates a user alias to be used
by a child criteria
@param attribute The alias to set | [
"Retrieves",
"or",
"if",
"necessary",
"creates",
"a",
"user",
"alias",
"to",
"be",
"used",
"by",
"a",
"child",
"criteria"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L1055-L1075 |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjector.java | LifecycleInjector.createInjector | public Injector createInjector(Collection<Module> additionalModules)
{
List<Module> localModules = Lists.newArrayList();
// Add the discovered modules FIRST. The discovered modules
// are added, and will subsequently be configured, in module dependency
// order which will ensure that any singletons bound in these modules
// will be created in the same order as the bind() calls are made.
// Note that the singleton ordering is only guaranteed for
// singleton scope.
//Add the LifecycleListener module
localModules.add(new LifecycleListenerModule());
localModules.add(new AbstractModule() {
@Override
public void configure() {
if (requireExplicitBindings) {
binder().requireExplicitBindings();
}
}
});
if ( additionalModules != null )
{
localModules.addAll(additionalModules);
}
localModules.addAll(modules);
// Finally, add the AutoBind module, which will use classpath scanning
// to creating singleton bindings. These singletons will be instantiated
// in an indeterminate order but are guaranteed to occur AFTER singletons
// bound in any of the discovered modules.
if ( !ignoreAllClasses )
{
Collection<Class<?>> localIgnoreClasses = Sets.newHashSet(ignoreClasses);
localModules.add(new InternalAutoBindModule(injector, scanner, localIgnoreClasses));
}
return createChildInjector(localModules);
} | java | public Injector createInjector(Collection<Module> additionalModules)
{
List<Module> localModules = Lists.newArrayList();
// Add the discovered modules FIRST. The discovered modules
// are added, and will subsequently be configured, in module dependency
// order which will ensure that any singletons bound in these modules
// will be created in the same order as the bind() calls are made.
// Note that the singleton ordering is only guaranteed for
// singleton scope.
//Add the LifecycleListener module
localModules.add(new LifecycleListenerModule());
localModules.add(new AbstractModule() {
@Override
public void configure() {
if (requireExplicitBindings) {
binder().requireExplicitBindings();
}
}
});
if ( additionalModules != null )
{
localModules.addAll(additionalModules);
}
localModules.addAll(modules);
// Finally, add the AutoBind module, which will use classpath scanning
// to creating singleton bindings. These singletons will be instantiated
// in an indeterminate order but are guaranteed to occur AFTER singletons
// bound in any of the discovered modules.
if ( !ignoreAllClasses )
{
Collection<Class<?>> localIgnoreClasses = Sets.newHashSet(ignoreClasses);
localModules.add(new InternalAutoBindModule(injector, scanner, localIgnoreClasses));
}
return createChildInjector(localModules);
} | [
"public",
"Injector",
"createInjector",
"(",
"Collection",
"<",
"Module",
">",
"additionalModules",
")",
"{",
"List",
"<",
"Module",
">",
"localModules",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"// Add the discovered modules FIRST. The discovered modules",
... | Create the main injector
@param additionalModules any additional modules
@return injector | [
"Create",
"the",
"main",
"injector"
] | train | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjector.java#L372-L412 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java | ApiOvhEmailpro.service_account_email_fullAccess_allowedAccountId_GET | public OvhAccountFullAccess service_account_email_fullAccess_allowedAccountId_GET(String service, String email, Long allowedAccountId) throws IOException {
String qPath = "/email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}";
StringBuilder sb = path(qPath, service, email, allowedAccountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAccountFullAccess.class);
} | java | public OvhAccountFullAccess service_account_email_fullAccess_allowedAccountId_GET(String service, String email, Long allowedAccountId) throws IOException {
String qPath = "/email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}";
StringBuilder sb = path(qPath, service, email, allowedAccountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAccountFullAccess.class);
} | [
"public",
"OvhAccountFullAccess",
"service_account_email_fullAccess_allowedAccountId_GET",
"(",
"String",
"service",
",",
"String",
"email",
",",
"Long",
"allowedAccountId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/pro/{service}/account/{email}/fullA... | Get this object properties
REST: GET /email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}
@param service [required] The internal name of your pro organization
@param email [required] Default email for this mailbox
@param allowedAccountId [required] Account id to give full access
API beta | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L337-L342 |
groovy/groovy-core | src/main/groovy/lang/GroovyClassLoader.java | GroovyClassLoader.recompile | protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException {
if (source != null) {
// found a source, compile it if newer
if ((oldClass != null && isSourceNewer(source, oldClass)) || (oldClass == null)) {
synchronized (sourceCache) {
String name = source.toExternalForm();
sourceCache.remove(name);
if (isFile(source)) {
try {
return parseClass(new GroovyCodeSource(new File(source.toURI()), config.getSourceEncoding()));
} catch (URISyntaxException e) {
// do nothing and fall back to the other version
}
}
return parseClass(source.openStream(), name);
}
}
}
return oldClass;
} | java | protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException {
if (source != null) {
// found a source, compile it if newer
if ((oldClass != null && isSourceNewer(source, oldClass)) || (oldClass == null)) {
synchronized (sourceCache) {
String name = source.toExternalForm();
sourceCache.remove(name);
if (isFile(source)) {
try {
return parseClass(new GroovyCodeSource(new File(source.toURI()), config.getSourceEncoding()));
} catch (URISyntaxException e) {
// do nothing and fall back to the other version
}
}
return parseClass(source.openStream(), name);
}
}
}
return oldClass;
} | [
"protected",
"Class",
"recompile",
"(",
"URL",
"source",
",",
"String",
"className",
",",
"Class",
"oldClass",
")",
"throws",
"CompilationFailedException",
",",
"IOException",
"{",
"if",
"(",
"source",
"!=",
"null",
")",
"{",
"// found a source, compile it if newer"... | (Re)Compiles the given source.
This method starts the compilation of a given source, if
the source has changed since the class was created. For
this isSourceNewer is called.
@param source the source pointer for the compilation
@param className the name of the class to be generated
@param oldClass a possible former class
@return the old class if the source wasn't new enough, the new class else
@throws CompilationFailedException if the compilation failed
@throws IOException if the source is not readable
@see #isSourceNewer(URL, Class) | [
"(",
"Re",
")",
"Compiles",
"the",
"given",
"source",
".",
"This",
"method",
"starts",
"the",
"compilation",
"of",
"a",
"given",
"source",
"if",
"the",
"source",
"has",
"changed",
"since",
"the",
"class",
"was",
"created",
".",
"For",
"this",
"isSourceNewe... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/GroovyClassLoader.java#L753-L772 |
CenturyLinkCloud/mdw | mdw-workflow/src/com/centurylink/mdw/workflow/activity/validate/SwaggerValidatorActivity.java | SwaggerValidatorActivity.handleResult | protected Object handleResult(Result result) throws ActivityException {
ServiceValuesAccess serviceValues = getRuntimeContext().getServiceValues();
StatusResponse statusResponse;
if (result.isError()) {
logsevere("Validation error: " + result.getStatus().toString());
statusResponse = new StatusResponse(result.getWorstCode(), result.getStatus().getMessage());
String responseHeadersVarName = serviceValues.getResponseHeadersVariableName();
Map<String,String> responseHeaders = serviceValues.getResponseHeaders();
if (responseHeaders == null) {
Variable responseHeadersVar = getMainProcessDefinition().getVariable(responseHeadersVarName);
if (responseHeadersVar == null)
throw new ActivityException("Missing response headers variable: " + responseHeadersVarName);
responseHeaders = new HashMap<>();
}
responseHeaders.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(statusResponse.getStatus().getCode()));
setVariableValue(responseHeadersVarName, responseHeaders);
}
else {
statusResponse = new StatusResponse(com.centurylink.mdw.model.Status.OK, "Valid request");
}
String responseVariableName = serviceValues.getResponseVariableName();
Variable responseVariable = getMainProcessDefinition().getVariable(responseVariableName);
if (responseVariable == null)
throw new ActivityException("Missing response variable: " + responseVariableName);
Object responseObject;
if (responseVariable.getType().equals(Jsonable.class.getName()))
responseObject = statusResponse; // _type has not been set, so serialization would fail
else
responseObject = serviceValues.fromJson(responseVariableName, statusResponse.getJson());
setVariableValue(responseVariableName, responseObject);
return !result.isError();
} | java | protected Object handleResult(Result result) throws ActivityException {
ServiceValuesAccess serviceValues = getRuntimeContext().getServiceValues();
StatusResponse statusResponse;
if (result.isError()) {
logsevere("Validation error: " + result.getStatus().toString());
statusResponse = new StatusResponse(result.getWorstCode(), result.getStatus().getMessage());
String responseHeadersVarName = serviceValues.getResponseHeadersVariableName();
Map<String,String> responseHeaders = serviceValues.getResponseHeaders();
if (responseHeaders == null) {
Variable responseHeadersVar = getMainProcessDefinition().getVariable(responseHeadersVarName);
if (responseHeadersVar == null)
throw new ActivityException("Missing response headers variable: " + responseHeadersVarName);
responseHeaders = new HashMap<>();
}
responseHeaders.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(statusResponse.getStatus().getCode()));
setVariableValue(responseHeadersVarName, responseHeaders);
}
else {
statusResponse = new StatusResponse(com.centurylink.mdw.model.Status.OK, "Valid request");
}
String responseVariableName = serviceValues.getResponseVariableName();
Variable responseVariable = getMainProcessDefinition().getVariable(responseVariableName);
if (responseVariable == null)
throw new ActivityException("Missing response variable: " + responseVariableName);
Object responseObject;
if (responseVariable.getType().equals(Jsonable.class.getName()))
responseObject = statusResponse; // _type has not been set, so serialization would fail
else
responseObject = serviceValues.fromJson(responseVariableName, statusResponse.getJson());
setVariableValue(responseVariableName, responseObject);
return !result.isError();
} | [
"protected",
"Object",
"handleResult",
"(",
"Result",
"result",
")",
"throws",
"ActivityException",
"{",
"ServiceValuesAccess",
"serviceValues",
"=",
"getRuntimeContext",
"(",
")",
".",
"getServiceValues",
"(",
")",
";",
"StatusResponse",
"statusResponse",
";",
"if",
... | Populates "response" variable with a default JSON status object. Can be overwritten by
custom logic in a downstream activity, or in a JsonRestService implementation. | [
"Populates",
"response",
"variable",
"with",
"a",
"default",
"JSON",
"status",
"object",
".",
"Can",
"be",
"overwritten",
"by",
"custom",
"logic",
"in",
"a",
"downstream",
"activity",
"or",
"in",
"a",
"JsonRestService",
"implementation",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/activity/validate/SwaggerValidatorActivity.java#L130-L161 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java | CassandraDataHandlerBase.setCollectionValue | private void setCollectionValue(Object entity, Object thriftColumnValue, Attribute attribute)
{
try
{
ByteBuffer valueByteBuffer = ByteBuffer.wrap((byte[]) thriftColumnValue);
if (Collection.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))
{
Class<?> genericClass = PropertyAccessorHelper.getGenericClass((Field) attribute.getJavaMember());
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator
.decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, genericClass, true));
}
else if (((Field) attribute.getJavaMember()).getType().isAssignableFrom(Map.class))
{
List<Class<?>> mapGenericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute
.getJavaMember());
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator
.decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, mapGenericClasses,
true));
}
}
catch (Exception e)
{
log.error("Error while setting field{} value via CQL, Caused by: .", attribute.getName(), e);
throw new PersistenceException(e);
}
} | java | private void setCollectionValue(Object entity, Object thriftColumnValue, Attribute attribute)
{
try
{
ByteBuffer valueByteBuffer = ByteBuffer.wrap((byte[]) thriftColumnValue);
if (Collection.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))
{
Class<?> genericClass = PropertyAccessorHelper.getGenericClass((Field) attribute.getJavaMember());
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator
.decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, genericClass, true));
}
else if (((Field) attribute.getJavaMember()).getType().isAssignableFrom(Map.class))
{
List<Class<?>> mapGenericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute
.getJavaMember());
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator
.decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, mapGenericClasses,
true));
}
}
catch (Exception e)
{
log.error("Error while setting field{} value via CQL, Caused by: .", attribute.getName(), e);
throw new PersistenceException(e);
}
} | [
"private",
"void",
"setCollectionValue",
"(",
"Object",
"entity",
",",
"Object",
"thriftColumnValue",
",",
"Attribute",
"attribute",
")",
"{",
"try",
"{",
"ByteBuffer",
"valueByteBuffer",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"(",
"byte",
"[",
"]",
")",
"thrift... | Populates collection field(s) into entity.
@param entity
the entity
@param thriftColumnValue
the thrift column value
@param attribute
the attribute | [
"Populates",
"collection",
"field",
"(",
"s",
")",
"into",
"entity",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java#L2569-L2599 |
exKAZUu/GameAIArena | src/main/java/net/exkazuu/gameaiarena/api/Point2.java | Point2.add | public Point2 add(Point2 that) {
return new Point2(x + that.x, y + that.y);
} | java | public Point2 add(Point2 that) {
return new Point2(x + that.x, y + that.y);
} | [
"public",
"Point2",
"add",
"(",
"Point2",
"that",
")",
"{",
"return",
"new",
"Point2",
"(",
"x",
"+",
"that",
".",
"x",
",",
"y",
"+",
"that",
".",
"y",
")",
";",
"}"
] | Point(this.x + that.x, this.y + that.y)となるPoint型を返します。
@param that このPoint型に加算するPoint型
@return このPoint型に引数のPoint型を加算した結果 | [
"Point",
"(",
"this",
".",
"x",
"+",
"that",
".",
"x",
"this",
".",
"y",
"+",
"that",
".",
"y",
")",
"となるPoint型を返します。"
] | train | https://github.com/exKAZUu/GameAIArena/blob/66894c251569fb763174654d6c262c5176dfcf48/src/main/java/net/exkazuu/gameaiarena/api/Point2.java#L91-L93 |
vkostyukov/la4j | src/main/java/org/la4j/Matrix.java | Matrix.insertColumn | public Matrix insertColumn(int j, Vector column) {
if (j > columns || j < 0) {
throw new IndexOutOfBoundsException("Illegal column number, must be 0.." + columns);
}
Matrix result;
if (rows == 0) {
result = blankOfShape(column.length(), columns + 1);
} else {
result = blankOfShape(rows, columns + 1);
}
for (int jj = 0; jj < j; jj++) {
result.setColumn(jj, getColumn(jj));
}
result.setColumn(j, column);
for (int jj = j; jj < columns; jj++) {
result.setColumn(jj + 1, getColumn(jj));
}
return result;
} | java | public Matrix insertColumn(int j, Vector column) {
if (j > columns || j < 0) {
throw new IndexOutOfBoundsException("Illegal column number, must be 0.." + columns);
}
Matrix result;
if (rows == 0) {
result = blankOfShape(column.length(), columns + 1);
} else {
result = blankOfShape(rows, columns + 1);
}
for (int jj = 0; jj < j; jj++) {
result.setColumn(jj, getColumn(jj));
}
result.setColumn(j, column);
for (int jj = j; jj < columns; jj++) {
result.setColumn(jj + 1, getColumn(jj));
}
return result;
} | [
"public",
"Matrix",
"insertColumn",
"(",
"int",
"j",
",",
"Vector",
"column",
")",
"{",
"if",
"(",
"j",
">",
"columns",
"||",
"j",
"<",
"0",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Illegal column number, must be 0..\"",
"+",
"columns",
... | Adds one column to matrix.
@param j the column index
@return matrix with column. | [
"Adds",
"one",
"column",
"to",
"matrix",
"."
] | train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrix.java#L1075-L1098 |
kiegroup/drools | kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/ItemDefinitionDependenciesSorter.java | ItemDefinitionDependenciesSorter.dfVisit | private void dfVisit(ItemDefinition node, List<ItemDefinition> allNodes, Collection<ItemDefinition> visited, List<ItemDefinition> dfv) {
visited.add(node);
List<ItemDefinition> neighbours = allNodes.stream()
.filter(n -> !n.getName().equals(node.getName())) // filter out `node`
.filter(n -> recurseFind(node, new QName(modelNamespace, n.getName()))) // I pick from allNodes, those referenced by this `node`. Only neighbours of `node`, because N is referenced by NODE.
.collect(Collectors.toList());
for (ItemDefinition n : neighbours) {
if (!visited.contains(n)) {
dfVisit(n, allNodes, visited, dfv);
}
}
dfv.add(node);
} | java | private void dfVisit(ItemDefinition node, List<ItemDefinition> allNodes, Collection<ItemDefinition> visited, List<ItemDefinition> dfv) {
visited.add(node);
List<ItemDefinition> neighbours = allNodes.stream()
.filter(n -> !n.getName().equals(node.getName())) // filter out `node`
.filter(n -> recurseFind(node, new QName(modelNamespace, n.getName()))) // I pick from allNodes, those referenced by this `node`. Only neighbours of `node`, because N is referenced by NODE.
.collect(Collectors.toList());
for (ItemDefinition n : neighbours) {
if (!visited.contains(n)) {
dfVisit(n, allNodes, visited, dfv);
}
}
dfv.add(node);
} | [
"private",
"void",
"dfVisit",
"(",
"ItemDefinition",
"node",
",",
"List",
"<",
"ItemDefinition",
">",
"allNodes",
",",
"Collection",
"<",
"ItemDefinition",
">",
"visited",
",",
"List",
"<",
"ItemDefinition",
">",
"dfv",
")",
"{",
"visited",
".",
"add",
"(",
... | Performs a depth first visit, but keeping a separate reference of visited/visiting nodes, _also_ to avoid potential issues of circularities. | [
"Performs",
"a",
"depth",
"first",
"visit",
"but",
"keeping",
"a",
"separate",
"reference",
"of",
"visited",
"/",
"visiting",
"nodes",
"_also_",
"to",
"avoid",
"potential",
"issues",
"of",
"circularities",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/ItemDefinitionDependenciesSorter.java#L58-L72 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/SerializationUtils.java | SerializationUtils.deserializeState | public static <T extends State> void deserializeState(FileSystem fs, Path jobStateFilePath, T state)
throws IOException {
try (InputStream is = fs.open(jobStateFilePath)) {
deserializeStateFromInputStream(is, state);
}
} | java | public static <T extends State> void deserializeState(FileSystem fs, Path jobStateFilePath, T state)
throws IOException {
try (InputStream is = fs.open(jobStateFilePath)) {
deserializeStateFromInputStream(is, state);
}
} | [
"public",
"static",
"<",
"T",
"extends",
"State",
">",
"void",
"deserializeState",
"(",
"FileSystem",
"fs",
",",
"Path",
"jobStateFilePath",
",",
"T",
"state",
")",
"throws",
"IOException",
"{",
"try",
"(",
"InputStream",
"is",
"=",
"fs",
".",
"open",
"(",... | Deserialize/read a {@link State} instance from a file.
@param fs the {@link FileSystem} instance for opening the file
@param jobStateFilePath the path to the file
@param state an empty {@link State} instance to deserialize into
@param <T> the {@link State} object type
@throws IOException if it fails to deserialize the {@link State} instance | [
"Deserialize",
"/",
"read",
"a",
"{",
"@link",
"State",
"}",
"instance",
"from",
"a",
"file",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/SerializationUtils.java#L173-L178 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java | CPMeasurementUnitPersistenceImpl.findByG_P_T | @Override
public List<CPMeasurementUnit> findByG_P_T(long groupId, boolean primary,
int type, int start, int end) {
return findByG_P_T(groupId, primary, type, start, end, null);
} | java | @Override
public List<CPMeasurementUnit> findByG_P_T(long groupId, boolean primary,
int type, int start, int end) {
return findByG_P_T(groupId, primary, type, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPMeasurementUnit",
">",
"findByG_P_T",
"(",
"long",
"groupId",
",",
"boolean",
"primary",
",",
"int",
"type",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByG_P_T",
"(",
"groupId",
",",
"primary... | Returns a range of all the cp measurement units where groupId = ? and primary = ? and type = ?.
<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 CPMeasurementUnitModelImpl}. 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 primary the primary
@param type the type
@param start the lower bound of the range of cp measurement units
@param end the upper bound of the range of cp measurement units (not inclusive)
@return the range of matching cp measurement units | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"measurement",
"units",
"where",
"groupId",
"=",
"?",
";",
"and",
"primary",
"=",
"?",
";",
"and",
"type",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L2872-L2876 |
aws/aws-sdk-java | aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/ApplicationResponse.java | ApplicationResponse.withTags | public ApplicationResponse withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public ApplicationResponse withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"ApplicationResponse",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | The Tags for the application.
@param tags
The Tags for the application.
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"Tags",
"for",
"the",
"application",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/ApplicationResponse.java#L169-L172 |
Azure/azure-sdk-for-java | storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java | StorageAccountsInner.createOrUpdateManagementPoliciesAsync | public ServiceFuture<StorageAccountManagementPoliciesInner> createOrUpdateManagementPoliciesAsync(String resourceGroupName, String accountName, Object policy, final ServiceCallback<StorageAccountManagementPoliciesInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName, policy), serviceCallback);
} | java | public ServiceFuture<StorageAccountManagementPoliciesInner> createOrUpdateManagementPoliciesAsync(String resourceGroupName, String accountName, Object policy, final ServiceCallback<StorageAccountManagementPoliciesInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName, policy), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"StorageAccountManagementPoliciesInner",
">",
"createOrUpdateManagementPoliciesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"Object",
"policy",
",",
"final",
"ServiceCallback",
"<",
"StorageAccountManagementPolic... | Sets the data policy rules associated with the specified storage account.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@param policy The Storage Account ManagementPolicies Rules, in JSON format. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Sets",
"the",
"data",
"policy",
"rules",
"associated",
"with",
"the",
"specified",
"storage",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L1387-L1389 |
alexvasilkov/GestureViews | library/src/main/java/com/alexvasilkov/gestures/utils/GravityUtils.java | GravityUtils.getMovementAreaPosition | public static void getMovementAreaPosition(Settings settings, Rect out) {
tmpRect1.set(0, 0, settings.getViewportW(), settings.getViewportH());
Gravity.apply(settings.getGravity(),
settings.getMovementAreaW(), settings.getMovementAreaH(), tmpRect1, out);
} | java | public static void getMovementAreaPosition(Settings settings, Rect out) {
tmpRect1.set(0, 0, settings.getViewportW(), settings.getViewportH());
Gravity.apply(settings.getGravity(),
settings.getMovementAreaW(), settings.getMovementAreaH(), tmpRect1, out);
} | [
"public",
"static",
"void",
"getMovementAreaPosition",
"(",
"Settings",
"settings",
",",
"Rect",
"out",
")",
"{",
"tmpRect1",
".",
"set",
"(",
"0",
",",
"0",
",",
"settings",
".",
"getViewportW",
"(",
")",
",",
"settings",
".",
"getViewportH",
"(",
")",
... | Calculates movement area position within viewport area with gravity applied.
@param settings Image settings
@param out Output rectangle | [
"Calculates",
"movement",
"area",
"position",
"within",
"viewport",
"area",
"with",
"gravity",
"applied",
"."
] | train | https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/library/src/main/java/com/alexvasilkov/gestures/utils/GravityUtils.java#L61-L65 |
carewebframework/carewebframework-vista | org.carewebframework.vista.plugin-parent/org.carewebframework.vista.plugin.notification/src/main/java/org/carewebframework/vista/plugin/notification/PriorityRenderer.java | PriorityRenderer.getLabel | private static String getLabel(String name, Priority priority) {
return priority == null ? null : Labels.getLabel("vistanotification.priority." + name + "." + priority.name());
} | java | private static String getLabel(String name, Priority priority) {
return priority == null ? null : Labels.getLabel("vistanotification.priority." + name + "." + priority.name());
} | [
"private",
"static",
"String",
"getLabel",
"(",
"String",
"name",
",",
"Priority",
"priority",
")",
"{",
"return",
"priority",
"==",
"null",
"?",
"null",
":",
"Labels",
".",
"getLabel",
"(",
"\"vistanotification.priority.\"",
"+",
"name",
"+",
"\".\"",
"+",
... | Returns the label property for the specified attribute name and priority.
@param name The attribute name.
@param priority Priority value
@return The label value. | [
"Returns",
"the",
"label",
"property",
"for",
"the",
"specified",
"attribute",
"name",
"and",
"priority",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.plugin-parent/org.carewebframework.vista.plugin.notification/src/main/java/org/carewebframework/vista/plugin/notification/PriorityRenderer.java#L76-L78 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/internal/http/JsonErrorMessageParser.java | JsonErrorMessageParser.parseErrorMessage | public String parseErrorMessage(HttpResponse httpResponse, JsonNode jsonNode) {
// If X_AMZN_ERROR_MESSAGE is present, prefer that. Otherwise check the JSON body.
final String headerMessage = httpResponse.getHeader(X_AMZN_ERROR_MESSAGE);
if (headerMessage != null) {
return headerMessage;
}
for (String field : errorMessageJsonLocations) {
JsonNode value = jsonNode.get(field);
if (value != null && value.isTextual()) {
return value.asText();
}
}
return null;
} | java | public String parseErrorMessage(HttpResponse httpResponse, JsonNode jsonNode) {
// If X_AMZN_ERROR_MESSAGE is present, prefer that. Otherwise check the JSON body.
final String headerMessage = httpResponse.getHeader(X_AMZN_ERROR_MESSAGE);
if (headerMessage != null) {
return headerMessage;
}
for (String field : errorMessageJsonLocations) {
JsonNode value = jsonNode.get(field);
if (value != null && value.isTextual()) {
return value.asText();
}
}
return null;
} | [
"public",
"String",
"parseErrorMessage",
"(",
"HttpResponse",
"httpResponse",
",",
"JsonNode",
"jsonNode",
")",
"{",
"// If X_AMZN_ERROR_MESSAGE is present, prefer that. Otherwise check the JSON body.",
"final",
"String",
"headerMessage",
"=",
"httpResponse",
".",
"getHeader",
... | Parse the error message from the response.
@return Error Code of exceptional response or null if it can't be determined | [
"Parse",
"the",
"error",
"message",
"from",
"the",
"response",
"."
] | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/internal/http/JsonErrorMessageParser.java#L70-L83 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/las/databases/LasSourcesTable.java | LasSourcesTable.updateMinMaxIntensity | public static void updateMinMaxIntensity( ASpatialDb db, long sourceId, double minIntens, double maxIntens )
throws Exception {
String sql = "UPDATE " + TABLENAME//
+ " SET " + COLUMN_MININTENSITY + "=" + minIntens + ", " + COLUMN_MAXINTENSITY + "=" + maxIntens + //
" WHERE " + COLUMN_ID + "=" + sourceId;
db.executeInsertUpdateDeleteSql(sql);
} | java | public static void updateMinMaxIntensity( ASpatialDb db, long sourceId, double minIntens, double maxIntens )
throws Exception {
String sql = "UPDATE " + TABLENAME//
+ " SET " + COLUMN_MININTENSITY + "=" + minIntens + ", " + COLUMN_MAXINTENSITY + "=" + maxIntens + //
" WHERE " + COLUMN_ID + "=" + sourceId;
db.executeInsertUpdateDeleteSql(sql);
} | [
"public",
"static",
"void",
"updateMinMaxIntensity",
"(",
"ASpatialDb",
"db",
",",
"long",
"sourceId",
",",
"double",
"minIntens",
",",
"double",
"maxIntens",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"UPDATE \"",
"+",
"TABLENAME",
"//",
"+",
"\... | Update the intensity values.
@param db the db.
@param sourceId the source to update.
@param minIntens the min value.
@param maxIntens the max value.
@throws Exception | [
"Update",
"the",
"intensity",
"values",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/databases/LasSourcesTable.java#L125-L131 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.verify | public boolean verify(Sha256Hash sigHash, ECDSASignature signature) {
return ECKey.verify(sigHash.getBytes(), signature, getPubKey());
} | java | public boolean verify(Sha256Hash sigHash, ECDSASignature signature) {
return ECKey.verify(sigHash.getBytes(), signature, getPubKey());
} | [
"public",
"boolean",
"verify",
"(",
"Sha256Hash",
"sigHash",
",",
"ECDSASignature",
"signature",
")",
"{",
"return",
"ECKey",
".",
"verify",
"(",
"sigHash",
".",
"getBytes",
"(",
")",
",",
"signature",
",",
"getPubKey",
"(",
")",
")",
";",
"}"
] | Verifies the given R/S pair (signature) against a hash using the public key. | [
"Verifies",
"the",
"given",
"R",
"/",
"S",
"pair",
"(",
"signature",
")",
"against",
"a",
"hash",
"using",
"the",
"public",
"key",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L766-L768 |
rapid7/conqueso-client-java | src/main/java/com/rapid7/conqueso/client/ConquesoClient.java | ConquesoClient.getPropertyValue | public String getPropertyValue(String key) {
checkArgument(!Strings.isNullOrEmpty(key), "key");
String errorMessage = String.format("Failed to retrieve %s property from Conqueso server: %s",
key, conquesoUrl.toExternalForm());
return readStringFromUrl("properties/" + key, errorMessage);
} | java | public String getPropertyValue(String key) {
checkArgument(!Strings.isNullOrEmpty(key), "key");
String errorMessage = String.format("Failed to retrieve %s property from Conqueso server: %s",
key, conquesoUrl.toExternalForm());
return readStringFromUrl("properties/" + key, errorMessage);
} | [
"public",
"String",
"getPropertyValue",
"(",
"String",
"key",
")",
"{",
"checkArgument",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"key",
")",
",",
"\"key\"",
")",
";",
"String",
"errorMessage",
"=",
"String",
".",
"format",
"(",
"\"Failed to retrieve %s... | Retrieve the latest value for the given property key from the Conqueso Server, returned
as a String.
@param key the property key to look up
@return the latest property value
@throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server. | [
"Retrieve",
"the",
"latest",
"value",
"for",
"the",
"given",
"property",
"key",
"from",
"the",
"Conqueso",
"Server",
"returned",
"as",
"a",
"String",
"."
] | train | https://github.com/rapid7/conqueso-client-java/blob/fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2/src/main/java/com/rapid7/conqueso/client/ConquesoClient.java#L419-L426 |
ivanceras/orm | src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java | SynchronousEntityManager.insert | @Override
public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys) throws DatabaseException{
ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName());
if(excludePrimaryKeys){
dao.add_IgnoreColumn( model.getPrimaryAttributes());
}
return insertRecord(dao, model, true);
} | java | @Override
public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys) throws DatabaseException{
ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName());
if(excludePrimaryKeys){
dao.add_IgnoreColumn( model.getPrimaryAttributes());
}
return insertRecord(dao, model, true);
} | [
"@",
"Override",
"public",
"<",
"T",
"extends",
"DAO",
">",
"T",
"insert",
"(",
"DAO",
"dao",
",",
"boolean",
"excludePrimaryKeys",
")",
"throws",
"DatabaseException",
"{",
"ModelDef",
"model",
"=",
"db",
".",
"getModelMetaDataDefinition",
"(",
")",
".",
"ge... | The primary keys should have defaults on the database to make this work | [
"The",
"primary",
"keys",
"should",
"have",
"defaults",
"on",
"the",
"database",
"to",
"make",
"this",
"work"
] | train | https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java#L280-L287 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/ArrayListIterate.java | ArrayListIterate.reverseForEach | public static <T> void reverseForEach(ArrayList<T> list, Procedure<? super T> procedure)
{
if (!list.isEmpty())
{
ArrayListIterate.forEach(list, list.size() - 1, 0, procedure);
}
} | java | public static <T> void reverseForEach(ArrayList<T> list, Procedure<? super T> procedure)
{
if (!list.isEmpty())
{
ArrayListIterate.forEach(list, list.size() - 1, 0, procedure);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"reverseForEach",
"(",
"ArrayList",
"<",
"T",
">",
"list",
",",
"Procedure",
"<",
"?",
"super",
"T",
">",
"procedure",
")",
"{",
"if",
"(",
"!",
"list",
".",
"isEmpty",
"(",
")",
")",
"{",
"ArrayListIterate"... | Reverses over the List in reverse order executing the Procedure for each element | [
"Reverses",
"over",
"the",
"List",
"in",
"reverse",
"order",
"executing",
"the",
"Procedure",
"for",
"each",
"element"
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/ArrayListIterate.java#L783-L789 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java | TransliteratorParser.checkVariableRange | private void checkVariableRange(int ch, String rule, int start) {
if (ch >= curData.variablesBase && ch < variableLimit) {
syntaxError("Variable range character in rule", rule, start);
}
} | java | private void checkVariableRange(int ch, String rule, int start) {
if (ch >= curData.variablesBase && ch < variableLimit) {
syntaxError("Variable range character in rule", rule, start);
}
} | [
"private",
"void",
"checkVariableRange",
"(",
"int",
"ch",
",",
"String",
"rule",
",",
"int",
"start",
")",
"{",
"if",
"(",
"ch",
">=",
"curData",
".",
"variablesBase",
"&&",
"ch",
"<",
"variableLimit",
")",
"{",
"syntaxError",
"(",
"\"Variable range charact... | Assert that the given character is NOT within the variable range.
If it is, signal an error. This is neccesary to ensure that the
variable range does not overlap characters used in a rule. | [
"Assert",
"that",
"the",
"given",
"character",
"is",
"NOT",
"within",
"the",
"variable",
"range",
".",
"If",
"it",
"is",
"signal",
"an",
"error",
".",
"This",
"is",
"neccesary",
"to",
"ensure",
"that",
"the",
"variable",
"range",
"does",
"not",
"overlap",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java#L1332-L1336 |
brianwhu/xillium | base/src/main/java/org/xillium/base/util/Objects.java | Objects.getProperty | public static Object getProperty(Object object, String name) throws NoSuchFieldException {
try {
Matcher matcher = ARRAY_INDEX.matcher(name);
if (matcher.matches()) {
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
return Array.get(object, Integer.parseInt(matcher.group(2)));
} else {
return ((List)object).get(Integer.parseInt(matcher.group(2)));
}
} else {
int dot = name.lastIndexOf('.');
if (dot > 0) {
object = getProperty(object, name.substring(0, dot));
name = name.substring(dot + 1);
}
return Beans.getKnownField(object.getClass(), name).get(object);
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | java | public static Object getProperty(Object object, String name) throws NoSuchFieldException {
try {
Matcher matcher = ARRAY_INDEX.matcher(name);
if (matcher.matches()) {
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
return Array.get(object, Integer.parseInt(matcher.group(2)));
} else {
return ((List)object).get(Integer.parseInt(matcher.group(2)));
}
} else {
int dot = name.lastIndexOf('.');
if (dot > 0) {
object = getProperty(object, name.substring(0, dot));
name = name.substring(dot + 1);
}
return Beans.getKnownField(object.getClass(), name).get(object);
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | [
"public",
"static",
"Object",
"getProperty",
"(",
"Object",
"object",
",",
"String",
"name",
")",
"throws",
"NoSuchFieldException",
"{",
"try",
"{",
"Matcher",
"matcher",
"=",
"ARRAY_INDEX",
".",
"matcher",
"(",
"name",
")",
";",
"if",
"(",
"matcher",
".",
... | Reports a property.
@param object the target object
@param name a dot-separated path to the property
@return the property value
@throws NoSuchFieldException if the property is not found | [
"Reports",
"a",
"property",
"."
] | train | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/util/Objects.java#L26-L49 |
DDTH/ddth-dao | ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java | BaseDao.putToCache | protected void putToCache(String cacheName, String key, Object value) {
putToCache(cacheName, key, value, 0);
} | java | protected void putToCache(String cacheName, String key, Object value) {
putToCache(cacheName, key, value, 0);
} | [
"protected",
"void",
"putToCache",
"(",
"String",
"cacheName",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"putToCache",
"(",
"cacheName",
",",
"key",
",",
"value",
",",
"0",
")",
";",
"}"
] | Puts an entry to cache, with default TTL.
@param cacheName
@param key
@param value | [
"Puts",
"an",
"entry",
"to",
"cache",
"with",
"default",
"TTL",
"."
] | train | https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java#L162-L164 |
softindex/datakernel | core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java | ByteBufQueue.drainTo | public int drainTo(@NotNull byte[] dest, int destOffset, int maxSize) {
int s = maxSize;
while (hasRemaining()) {
ByteBuf buf = bufs[first];
int remaining = buf.readRemaining();
if (s < remaining) {
arraycopy(buf.array(), buf.head(), dest, destOffset, s);
buf.moveHead(s);
return maxSize;
} else {
arraycopy(buf.array(), buf.head(), dest, destOffset, remaining);
buf.recycle();
first = next(first);
s -= remaining;
destOffset += remaining;
}
}
return maxSize - s;
} | java | public int drainTo(@NotNull byte[] dest, int destOffset, int maxSize) {
int s = maxSize;
while (hasRemaining()) {
ByteBuf buf = bufs[first];
int remaining = buf.readRemaining();
if (s < remaining) {
arraycopy(buf.array(), buf.head(), dest, destOffset, s);
buf.moveHead(s);
return maxSize;
} else {
arraycopy(buf.array(), buf.head(), dest, destOffset, remaining);
buf.recycle();
first = next(first);
s -= remaining;
destOffset += remaining;
}
}
return maxSize - s;
} | [
"public",
"int",
"drainTo",
"(",
"@",
"NotNull",
"byte",
"[",
"]",
"dest",
",",
"int",
"destOffset",
",",
"int",
"maxSize",
")",
"{",
"int",
"s",
"=",
"maxSize",
";",
"while",
"(",
"hasRemaining",
"(",
")",
")",
"{",
"ByteBuf",
"buf",
"=",
"bufs",
... | Adds {@code maxSize} bytes from this queue to {@code dest} if queue
contains more than {@code maxSize} bytes. Otherwise adds all
bytes from queue to {@code dest}. In both cases increases queue's
position to the number of drained bytes.
@param dest array to drain to
@param destOffset start position for adding to dest
@param maxSize number of bytes for adding
@return number of drained bytes | [
"Adds",
"{",
"@code",
"maxSize",
"}",
"bytes",
"from",
"this",
"queue",
"to",
"{",
"@code",
"dest",
"}",
"if",
"queue",
"contains",
"more",
"than",
"{",
"@code",
"maxSize",
"}",
"bytes",
".",
"Otherwise",
"adds",
"all",
"bytes",
"from",
"queue",
"to",
... | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java#L520-L538 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java | ComponentFactory.newMultiLineLabel | public static <T> MultiLineLabel newMultiLineLabel(final String id, final IModel<T> model)
{
final MultiLineLabel multiLineLabel = new MultiLineLabel(id, model);
multiLineLabel.setOutputMarkupId(true);
return multiLineLabel;
} | java | public static <T> MultiLineLabel newMultiLineLabel(final String id, final IModel<T> model)
{
final MultiLineLabel multiLineLabel = new MultiLineLabel(id, model);
multiLineLabel.setOutputMarkupId(true);
return multiLineLabel;
} | [
"public",
"static",
"<",
"T",
">",
"MultiLineLabel",
"newMultiLineLabel",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"T",
">",
"model",
")",
"{",
"final",
"MultiLineLabel",
"multiLineLabel",
"=",
"new",
"MultiLineLabel",
"(",
"id",
",",
"mode... | Factory method for create a new {@link MultiLineLabel}.
@param <T>
the generic type of the model
@param id
the id
@param model
the {@link IModel} of the {@link MultiLineLabel}.
@return the new {@link MultiLineLabel}. | [
"Factory",
"method",
"for",
"create",
"a",
"new",
"{",
"@link",
"MultiLineLabel",
"}",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java#L520-L525 |
Azure/azure-sdk-for-java | sql/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/sql/v2018_06_01_preview/implementation/ServerVulnerabilityAssessmentsInner.java | ServerVulnerabilityAssessmentsInner.listByServerAsync | public Observable<Page<ServerVulnerabilityAssessmentInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<ServerVulnerabilityAssessmentInner>>, Page<ServerVulnerabilityAssessmentInner>>() {
@Override
public Page<ServerVulnerabilityAssessmentInner> call(ServiceResponse<Page<ServerVulnerabilityAssessmentInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ServerVulnerabilityAssessmentInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<ServerVulnerabilityAssessmentInner>>, Page<ServerVulnerabilityAssessmentInner>>() {
@Override
public Page<ServerVulnerabilityAssessmentInner> call(ServiceResponse<Page<ServerVulnerabilityAssessmentInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ServerVulnerabilityAssessmentInner",
">",
">",
"listByServerAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
")",
"{",
"return",
"listByServerWithServiceResponseAsync",
"(",
"resourceGrou... | Lists the vulnerability assessment policies associated with a server.
@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.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ServerVulnerabilityAssessmentInner> object | [
"Lists",
"the",
"vulnerability",
"assessment",
"policies",
"associated",
"with",
"a",
"server",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/sql/v2018_06_01_preview/implementation/ServerVulnerabilityAssessmentsInner.java#L405-L413 |
citrusframework/citrus | modules/citrus-docker/src/main/java/com/consol/citrus/docker/config/xml/DockerExecuteActionParser.java | DockerExecuteActionParser.createCommand | private DockerCommand createCommand(Class<? extends DockerCommand> commandType) {
try {
return commandType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new BeanCreationException("Failed to create Docker command of type: " + commandType, e);
}
} | java | private DockerCommand createCommand(Class<? extends DockerCommand> commandType) {
try {
return commandType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new BeanCreationException("Failed to create Docker command of type: " + commandType, e);
}
} | [
"private",
"DockerCommand",
"createCommand",
"(",
"Class",
"<",
"?",
"extends",
"DockerCommand",
">",
"commandType",
")",
"{",
"try",
"{",
"return",
"commandType",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"|",
"IllegalAcces... | Creates new Docker command instance of given type.
@param commandType
@return | [
"Creates",
"new",
"Docker",
"command",
"instance",
"of",
"given",
"type",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-docker/src/main/java/com/consol/citrus/docker/config/xml/DockerExecuteActionParser.java#L110-L116 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/CommentAttachmentResourcesImpl.java | CommentAttachmentResourcesImpl.attachFile | public Attachment attachFile(long sheetId, long commentId, File file, String contentType) throws FileNotFoundException,
SmartsheetException {
Util.throwIfNull(sheetId, commentId, file, contentType);
Util.throwIfEmpty(contentType);
return attachFile(sheetId, commentId, new FileInputStream(file), contentType, file.length(), file.getName());
} | java | public Attachment attachFile(long sheetId, long commentId, File file, String contentType) throws FileNotFoundException,
SmartsheetException {
Util.throwIfNull(sheetId, commentId, file, contentType);
Util.throwIfEmpty(contentType);
return attachFile(sheetId, commentId, new FileInputStream(file), contentType, file.length(), file.getName());
} | [
"public",
"Attachment",
"attachFile",
"(",
"long",
"sheetId",
",",
"long",
"commentId",
",",
"File",
"file",
",",
"String",
"contentType",
")",
"throws",
"FileNotFoundException",
",",
"SmartsheetException",
"{",
"Util",
".",
"throwIfNull",
"(",
"sheetId",
",",
"... | Attach a file to a comment with simple upload.
It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/comments/{commentId}/attachments
@param sheetId the id of the sheet
@param commentId the id of the comment
@param file the file to attach
@param contentType the content type of the file
@return the created attachment
@throws FileNotFoundException the file not found exception
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | [
"Attach",
"a",
"file",
"to",
"a",
"comment",
"with",
"simple",
"upload",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/CommentAttachmentResourcesImpl.java#L81-L87 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java | WSRdbManagedConnectionImpl.initializeConnectionProperties | private void initializeConnectionProperties() throws ResourceException {
try {
// Retrieve the default values for all Connection properties.
// Save the default values for when null is specified in the CRI.
// - get the default values from the JDBC driver
if (rrsTransactional)
{
currentAutoCommit = defaultAutoCommit = true;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
Tr.debug(this, tc, "MCF is rrsTransactional: forcing currentAutoCommit and defaultAutoCommit to true");
}
}
else
{
currentAutoCommit = defaultAutoCommit = sqlConn.getAutoCommit();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
Tr.debug(this, tc, "MCF is NOT rrsTransactional: setting currentAutoCommit and defaultAutoCommit to " + defaultAutoCommit + " from underlying Connection");
}
}
defaultCatalog = sqlConn.getCatalog();
defaultReadOnly = mcf.supportsIsReadOnly ? sqlConn.isReadOnly() : false;
defaultTypeMap = getTypeMapSafely();
currentShardingKey = initialShardingKey = cri.ivShardingKey;
currentSuperShardingKey = initialSuperShardingKey = cri.ivSuperShardingKey;
currentSchema = defaultSchema = getSchemaSafely();
currentNetworkTimeout = defaultNetworkTimeout = getNetworkTimeoutSafely();
currentHoldability = defaultHoldability;
currentTransactionIsolation = sqlConn.getTransactionIsolation();
} catch (SQLException sqlX) {
FFDCFilter.processException(sqlX,
getClass().getName() + ".initializeConnectionProperties", "381", this);
throw new DataStoreAdapterException("DSA_ERROR", sqlX, getClass());
}
} | java | private void initializeConnectionProperties() throws ResourceException {
try {
// Retrieve the default values for all Connection properties.
// Save the default values for when null is specified in the CRI.
// - get the default values from the JDBC driver
if (rrsTransactional)
{
currentAutoCommit = defaultAutoCommit = true;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
Tr.debug(this, tc, "MCF is rrsTransactional: forcing currentAutoCommit and defaultAutoCommit to true");
}
}
else
{
currentAutoCommit = defaultAutoCommit = sqlConn.getAutoCommit();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
Tr.debug(this, tc, "MCF is NOT rrsTransactional: setting currentAutoCommit and defaultAutoCommit to " + defaultAutoCommit + " from underlying Connection");
}
}
defaultCatalog = sqlConn.getCatalog();
defaultReadOnly = mcf.supportsIsReadOnly ? sqlConn.isReadOnly() : false;
defaultTypeMap = getTypeMapSafely();
currentShardingKey = initialShardingKey = cri.ivShardingKey;
currentSuperShardingKey = initialSuperShardingKey = cri.ivSuperShardingKey;
currentSchema = defaultSchema = getSchemaSafely();
currentNetworkTimeout = defaultNetworkTimeout = getNetworkTimeoutSafely();
currentHoldability = defaultHoldability;
currentTransactionIsolation = sqlConn.getTransactionIsolation();
} catch (SQLException sqlX) {
FFDCFilter.processException(sqlX,
getClass().getName() + ".initializeConnectionProperties", "381", this);
throw new DataStoreAdapterException("DSA_ERROR", sqlX, getClass());
}
} | [
"private",
"void",
"initializeConnectionProperties",
"(",
")",
"throws",
"ResourceException",
"{",
"try",
"{",
"// Retrieve the default values for all Connection properties. ",
"// Save the default values for when null is specified in the CRI. ",
"// - get the default values from the JDBC dr... | Initialize all Connection properties for the ManagedConnection. The current values (and
previous values if applicable) should be retrieved from the underlying connection.
Requested values and initially requested values should be taken from the
ConnectionRequestInfo.
@throws ResourceException if an error occurs retrieving default values. | [
"Initialize",
"all",
"Connection",
"properties",
"for",
"the",
"ManagedConnection",
".",
"The",
"current",
"values",
"(",
"and",
"previous",
"values",
"if",
"applicable",
")",
"should",
"be",
"retrieved",
"from",
"the",
"underlying",
"connection",
".",
"Requested"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java#L1001-L1039 |
greenmail-mail-test/greenmail | greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMail.java | GreenMail.waitForIncomingEmail | @Override
public boolean waitForIncomingEmail(long timeout, int emailCount) {
final CountDownLatch waitObject = managers.getSmtpManager().createAndAddNewWaitObject(emailCount);
final long endTime = System.currentTimeMillis() + timeout;
while (waitObject.getCount() > 0) {
final long waitTime = endTime - System.currentTimeMillis();
if (waitTime < 0L) {
return waitObject.getCount() == 0;
}
try {
waitObject.await(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Continue loop, in case of premature interruption
}
}
return waitObject.getCount() == 0;
} | java | @Override
public boolean waitForIncomingEmail(long timeout, int emailCount) {
final CountDownLatch waitObject = managers.getSmtpManager().createAndAddNewWaitObject(emailCount);
final long endTime = System.currentTimeMillis() + timeout;
while (waitObject.getCount() > 0) {
final long waitTime = endTime - System.currentTimeMillis();
if (waitTime < 0L) {
return waitObject.getCount() == 0;
}
try {
waitObject.await(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Continue loop, in case of premature interruption
}
}
return waitObject.getCount() == 0;
} | [
"@",
"Override",
"public",
"boolean",
"waitForIncomingEmail",
"(",
"long",
"timeout",
",",
"int",
"emailCount",
")",
"{",
"final",
"CountDownLatch",
"waitObject",
"=",
"managers",
".",
"getSmtpManager",
"(",
")",
".",
"createAndAddNewWaitObject",
"(",
"emailCount",
... | ~ Convenience Methods, often needed while testing --------------------------------------------------------------- | [
"~",
"Convenience",
"Methods",
"often",
"needed",
"while",
"testing",
"---------------------------------------------------------------"
] | train | https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMail.java#L194-L210 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/VisualizationTree.java | VisualizationTree.findNewSiblings | public static <A extends Result, B extends VisualizationItem> void findNewSiblings(VisualizerContext context, Object start, Class<? super A> type1, Class<? super B> type2, BiConsumer<A, B> handler) {
// Search start in first hierarchy:
final ResultHierarchy hier = context.getHierarchy();
final Hierarchy<Object> vistree = context.getVisHierarchy();
if(start instanceof Result) {
// New result:
for(It<A> it1 = hier.iterDescendantsSelf((Result) start).filter(type1); it1.valid(); it1.advance()) {
final A result = it1.get();
// Existing visualization:
for(It<B> it2 = vistree.iterDescendantsSelf(context.getBaseResult()).filter(type2); it2.valid(); it2.advance()) {
handler.accept(result, it2.get());
}
}
}
// New visualization:
for(It<B> it2 = vistree.iterDescendantsSelf(start).filter(type2); it2.valid(); it2.advance()) {
final B vis = it2.get();
// Existing result:
for(It<A> it1 = hier.iterAll().filter(type1); it1.valid(); it1.advance()) {
handler.accept(it1.get(), vis);
}
}
} | java | public static <A extends Result, B extends VisualizationItem> void findNewSiblings(VisualizerContext context, Object start, Class<? super A> type1, Class<? super B> type2, BiConsumer<A, B> handler) {
// Search start in first hierarchy:
final ResultHierarchy hier = context.getHierarchy();
final Hierarchy<Object> vistree = context.getVisHierarchy();
if(start instanceof Result) {
// New result:
for(It<A> it1 = hier.iterDescendantsSelf((Result) start).filter(type1); it1.valid(); it1.advance()) {
final A result = it1.get();
// Existing visualization:
for(It<B> it2 = vistree.iterDescendantsSelf(context.getBaseResult()).filter(type2); it2.valid(); it2.advance()) {
handler.accept(result, it2.get());
}
}
}
// New visualization:
for(It<B> it2 = vistree.iterDescendantsSelf(start).filter(type2); it2.valid(); it2.advance()) {
final B vis = it2.get();
// Existing result:
for(It<A> it1 = hier.iterAll().filter(type1); it1.valid(); it1.advance()) {
handler.accept(it1.get(), vis);
}
}
} | [
"public",
"static",
"<",
"A",
"extends",
"Result",
",",
"B",
"extends",
"VisualizationItem",
">",
"void",
"findNewSiblings",
"(",
"VisualizerContext",
"context",
",",
"Object",
"start",
",",
"Class",
"<",
"?",
"super",
"A",
">",
"type1",
",",
"Class",
"<",
... | Process new result combinations of an object type1 (in first hierarchy) and
any child of type2 (in second hierarchy)
This is a bit painful, because we have two hierarchies with different
types: results, and visualizations.
@param context Context
@param start Starting point
@param type1 First type, in first hierarchy
@param type2 Second type, in second hierarchy
@param handler Handler | [
"Process",
"new",
"result",
"combinations",
"of",
"an",
"object",
"type1",
"(",
"in",
"first",
"hierarchy",
")",
"and",
"any",
"child",
"of",
"type2",
"(",
"in",
"second",
"hierarchy",
")"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/VisualizationTree.java#L147-L169 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cp/internal/raft/impl/state/RaftState.java | RaftState.updateGroupMembers | public void updateGroupMembers(long logIndex, Collection<Endpoint> members) {
assert committedGroupMembers == lastGroupMembers
: "Cannot update group members to: " + members + " at log index: " + logIndex + " because last group members: "
+ lastGroupMembers + " is different than committed group members: " + committedGroupMembers;
assert lastGroupMembers.index() < logIndex
: "Cannot update group members to: " + members + " at log index: " + logIndex + " because last group members: "
+ lastGroupMembers + " has a bigger log index.";
RaftGroupMembers newGroupMembers = new RaftGroupMembers(logIndex, members, localEndpoint);
committedGroupMembers = lastGroupMembers;
lastGroupMembers = newGroupMembers;
if (leaderState != null) {
for (Endpoint endpoint : members) {
if (!committedGroupMembers.isKnownMember(endpoint)) {
leaderState.add(endpoint, log.lastLogOrSnapshotIndex());
}
}
for (Endpoint endpoint : committedGroupMembers.remoteMembers()) {
if (!members.contains(endpoint)) {
leaderState.remove(endpoint);
}
}
}
} | java | public void updateGroupMembers(long logIndex, Collection<Endpoint> members) {
assert committedGroupMembers == lastGroupMembers
: "Cannot update group members to: " + members + " at log index: " + logIndex + " because last group members: "
+ lastGroupMembers + " is different than committed group members: " + committedGroupMembers;
assert lastGroupMembers.index() < logIndex
: "Cannot update group members to: " + members + " at log index: " + logIndex + " because last group members: "
+ lastGroupMembers + " has a bigger log index.";
RaftGroupMembers newGroupMembers = new RaftGroupMembers(logIndex, members, localEndpoint);
committedGroupMembers = lastGroupMembers;
lastGroupMembers = newGroupMembers;
if (leaderState != null) {
for (Endpoint endpoint : members) {
if (!committedGroupMembers.isKnownMember(endpoint)) {
leaderState.add(endpoint, log.lastLogOrSnapshotIndex());
}
}
for (Endpoint endpoint : committedGroupMembers.remoteMembers()) {
if (!members.contains(endpoint)) {
leaderState.remove(endpoint);
}
}
}
} | [
"public",
"void",
"updateGroupMembers",
"(",
"long",
"logIndex",
",",
"Collection",
"<",
"Endpoint",
">",
"members",
")",
"{",
"assert",
"committedGroupMembers",
"==",
"lastGroupMembers",
":",
"\"Cannot update group members to: \"",
"+",
"members",
"+",
"\" at log index... | Initializes the last applied group members with the members and logIndex.
This method expects there's no uncommitted membership changes, committed members are the same as
the last applied members.
Leader state is updated for the members which don't exist in committed members and committed members
those don't exist in latest applied members are removed.
@param logIndex log index of membership change
@param members latest applied members | [
"Initializes",
"the",
"last",
"applied",
"group",
"members",
"with",
"the",
"members",
"and",
"logIndex",
".",
"This",
"method",
"expects",
"there",
"s",
"no",
"uncommitted",
"membership",
"changes",
"committed",
"members",
"are",
"the",
"same",
"as",
"the",
"... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/raft/impl/state/RaftState.java#L384-L409 |
bwkimmel/java-util | src/main/java/ca/eandb/util/io/FileUtil.java | FileUtil.prune | public static void prune(File file, File root) {
while (!file.equals(root) && file.delete()) {
file = file.getParentFile();
}
} | java | public static void prune(File file, File root) {
while (!file.equals(root) && file.delete()) {
file = file.getParentFile();
}
} | [
"public",
"static",
"void",
"prune",
"(",
"File",
"file",
",",
"File",
"root",
")",
"{",
"while",
"(",
"!",
"file",
".",
"equals",
"(",
"root",
")",
"&&",
"file",
".",
"delete",
"(",
")",
")",
"{",
"file",
"=",
"file",
".",
"getParentFile",
"(",
... | Removes a file or directory and its ancestors up to, but not including
the specified directory, until a non-empty directory is reached.
@param file The file or directory at which to start pruning.
@param root The directory at which to stop pruning. | [
"Removes",
"a",
"file",
"or",
"directory",
"and",
"its",
"ancestors",
"up",
"to",
"but",
"not",
"including",
"the",
"specified",
"directory",
"until",
"a",
"non",
"-",
"empty",
"directory",
"is",
"reached",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/io/FileUtil.java#L212-L216 |
Samsung/GearVRf | GVRf/Extensions/gvrf-physics/src/main/java/org/gearvrf/physics/GVRRigidBody.java | GVRRigidBody.setAngularFactor | public void setAngularFactor(float x, float y, float z) {
Native3DRigidBody.setAngularFactor(getNative(), x, y, z);
} | java | public void setAngularFactor(float x, float y, float z) {
Native3DRigidBody.setAngularFactor(getNative(), x, y, z);
} | [
"public",
"void",
"setAngularFactor",
"(",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"Native3DRigidBody",
".",
"setAngularFactor",
"(",
"getNative",
"(",
")",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"}"
] | Sets an angular factor [X, Y, Z] that influences torque on this {@linkplain GVRRigidBody rigid body}
@param x factor on the 'X' axis.
@param y factor on the 'Y' axis.
@param z factor on the 'Z' axis. | [
"Sets",
"an",
"angular",
"factor",
"[",
"X",
"Y",
"Z",
"]",
"that",
"influences",
"torque",
"on",
"this",
"{",
"@linkplain",
"GVRRigidBody",
"rigid",
"body",
"}"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/gvrf-physics/src/main/java/org/gearvrf/physics/GVRRigidBody.java#L330-L332 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.java | OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLTransitiveObjectPropertyAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLTransitiveObjectPropertyAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLTransitiveObjectPropertyAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}... | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.java#L74-L77 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/collections/spatial/RTree.java | RTree.chooseLeaf | private Node chooseLeaf(Node node, Point point)
{
node.addToBitmapIndex(point);
if (node.isLeaf()) {
return node;
}
double minCost = Double.POSITIVE_INFINITY;
Node optimal = node.getChildren().get(0);
for (Node child : node.getChildren()) {
double cost = RTreeUtils.getExpansionCost(child, point);
if (cost < minCost) {
minCost = cost;
optimal = child;
} else if (cost == minCost) {
// Resolve ties by choosing the entry with the rectangle of smallest area
if (child.getArea() < optimal.getArea()) {
optimal = child;
}
}
}
return chooseLeaf(optimal, point);
} | java | private Node chooseLeaf(Node node, Point point)
{
node.addToBitmapIndex(point);
if (node.isLeaf()) {
return node;
}
double minCost = Double.POSITIVE_INFINITY;
Node optimal = node.getChildren().get(0);
for (Node child : node.getChildren()) {
double cost = RTreeUtils.getExpansionCost(child, point);
if (cost < minCost) {
minCost = cost;
optimal = child;
} else if (cost == minCost) {
// Resolve ties by choosing the entry with the rectangle of smallest area
if (child.getArea() < optimal.getArea()) {
optimal = child;
}
}
}
return chooseLeaf(optimal, point);
} | [
"private",
"Node",
"chooseLeaf",
"(",
"Node",
"node",
",",
"Point",
"point",
")",
"{",
"node",
".",
"addToBitmapIndex",
"(",
"point",
")",
";",
"if",
"(",
"node",
".",
"isLeaf",
"(",
")",
")",
"{",
"return",
"node",
";",
"}",
"double",
"minCost",
"="... | This description is from the original paper.
Algorithm ChooseLeaf. Select a leaf node in which to place a new index entry E.
CL1. [Initialize]. Set N to be the root node.
CL2. [Leaf check]. If N is a leaf, return N.
CL3. [Choose subtree]. If N is not a leaf, let F be the entry in N whose rectangle
FI needs least enlargement to include EI. Resolve ties by choosing the entry with the rectangle
of smallest area.
CL4. [Descend until a leaf is reached]. Set N to be the child node pointed to by Fp and repeated from CL2.
@param node - current node to evaluate
@param point - point to insert
@return - leafNode where point can be inserted | [
"This",
"description",
"is",
"from",
"the",
"original",
"paper",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/collections/spatial/RTree.java#L149-L173 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/ImagesInner.java | ImagesInner.updateAsync | public Observable<ImageInner> updateAsync(String resourceGroupName, String imageName, ImageUpdate parameters) {
return updateWithServiceResponseAsync(resourceGroupName, imageName, parameters).map(new Func1<ServiceResponse<ImageInner>, ImageInner>() {
@Override
public ImageInner call(ServiceResponse<ImageInner> response) {
return response.body();
}
});
} | java | public Observable<ImageInner> updateAsync(String resourceGroupName, String imageName, ImageUpdate parameters) {
return updateWithServiceResponseAsync(resourceGroupName, imageName, parameters).map(new Func1<ServiceResponse<ImageInner>, ImageInner>() {
@Override
public ImageInner call(ServiceResponse<ImageInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ImageInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"imageName",
",",
"ImageUpdate",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"imageName",
",",
"par... | Update an image.
@param resourceGroupName The name of the resource group.
@param imageName The name of the image.
@param parameters Parameters supplied to the Update Image operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Update",
"an",
"image",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/ImagesInner.java#L325-L332 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DcosSpec.java | DcosSpec.getUnusedNode | @Given("^I save the IP of an unused node in hosts '(.+?)' in the in environment variable '(.+?)'?$")
public void getUnusedNode(String hosts, String envVar) throws Exception {
Set<String> hostList = new HashSet(Arrays.asList(hosts.split(",")));
//Get the list of currently used hosts
commonspec.executeCommand("dcos task | awk '{print $2}'", 0, null);
String results = commonspec.getRemoteSSHConnection().getResult();
Set<String> usedHosts = new HashSet(Arrays.asList(results.replaceAll("\r", "").split("\n")));
//We get the nodes not being used
hostList.removeAll(usedHosts);
if (hostList.size() == 0) {
throw new IllegalStateException("No unused nodes in the cluster.");
} else {
//Pick the first available node
ThreadProperty.set(envVar, hostList.iterator().next());
}
} | java | @Given("^I save the IP of an unused node in hosts '(.+?)' in the in environment variable '(.+?)'?$")
public void getUnusedNode(String hosts, String envVar) throws Exception {
Set<String> hostList = new HashSet(Arrays.asList(hosts.split(",")));
//Get the list of currently used hosts
commonspec.executeCommand("dcos task | awk '{print $2}'", 0, null);
String results = commonspec.getRemoteSSHConnection().getResult();
Set<String> usedHosts = new HashSet(Arrays.asList(results.replaceAll("\r", "").split("\n")));
//We get the nodes not being used
hostList.removeAll(usedHosts);
if (hostList.size() == 0) {
throw new IllegalStateException("No unused nodes in the cluster.");
} else {
//Pick the first available node
ThreadProperty.set(envVar, hostList.iterator().next());
}
} | [
"@",
"Given",
"(",
"\"^I save the IP of an unused node in hosts '(.+?)' in the in environment variable '(.+?)'?$\"",
")",
"public",
"void",
"getUnusedNode",
"(",
"String",
"hosts",
",",
"String",
"envVar",
")",
"throws",
"Exception",
"{",
"Set",
"<",
"String",
">",
"hostL... | Checks if there are any unused nodes in the cluster and returns the IP of one of them.
REQUIRES A PREVIOUSLY-ESTABLISHED SSH CONNECTION TO DCOS-CLI TO WORK
@param hosts: list of IPs that will be investigated
@param envVar: environment variable name
@throws Exception | [
"Checks",
"if",
"there",
"are",
"any",
"unused",
"nodes",
"in",
"the",
"cluster",
"and",
"returns",
"the",
"IP",
"of",
"one",
"of",
"them",
".",
"REQUIRES",
"A",
"PREVIOUSLY",
"-",
"ESTABLISHED",
"SSH",
"CONNECTION",
"TO",
"DCOS",
"-",
"CLI",
"TO",
"WORK... | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L126-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/MessageMap.java | MessageMap.getMultiChoice | static BigInteger getMultiChoice(int[] choices, JSchema schema) throws JMFUninitializedAccessException {
if (choices == null || choices.length == 0)
return BigInteger.ZERO;
JSType topType = (JSType)schema.getJMFType();
if (topType instanceof JSVariant)
return getMultiChoice(choices, schema, (JSVariant)topType);
else if (topType instanceof JSTuple)
return getMultiChoice(choices, schema, ((JSTuple)topType).getDominatedVariants());
else
// If topType is JSRepeated, JSDynamic, JSEnum, or JSPrimitive there can be no unboxed
// variants at top level.
return BigInteger.ZERO;
} | java | static BigInteger getMultiChoice(int[] choices, JSchema schema) throws JMFUninitializedAccessException {
if (choices == null || choices.length == 0)
return BigInteger.ZERO;
JSType topType = (JSType)schema.getJMFType();
if (topType instanceof JSVariant)
return getMultiChoice(choices, schema, (JSVariant)topType);
else if (topType instanceof JSTuple)
return getMultiChoice(choices, schema, ((JSTuple)topType).getDominatedVariants());
else
// If topType is JSRepeated, JSDynamic, JSEnum, or JSPrimitive there can be no unboxed
// variants at top level.
return BigInteger.ZERO;
} | [
"static",
"BigInteger",
"getMultiChoice",
"(",
"int",
"[",
"]",
"choices",
",",
"JSchema",
"schema",
")",
"throws",
"JMFUninitializedAccessException",
"{",
"if",
"(",
"choices",
"==",
"null",
"||",
"choices",
".",
"length",
"==",
"0",
")",
"return",
"BigIntege... | The getMultiChoice subroutine is the inverse of setChoices: given a vector of
specific choices, it recursively computes the multiChoice code | [
"The",
"getMultiChoice",
"subroutine",
"is",
"the",
"inverse",
"of",
"setChoices",
":",
"given",
"a",
"vector",
"of",
"specific",
"choices",
"it",
"recursively",
"computes",
"the",
"multiChoice",
"code"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/MessageMap.java#L179-L191 |
aws/aws-sdk-java | aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java | ValidationContext.assertNotEmpty | public void assertNotEmpty(Map<?, ?> map, String propertyName) {
if (map == null || map.size() == 0) {
problemReporter.report(new Problem(this, String.format("%s requires one or more entries", propertyName)));
}
} | java | public void assertNotEmpty(Map<?, ?> map, String propertyName) {
if (map == null || map.size() == 0) {
problemReporter.report(new Problem(this, String.format("%s requires one or more entries", propertyName)));
}
} | [
"public",
"void",
"assertNotEmpty",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"map",
",",
"String",
"propertyName",
")",
"{",
"if",
"(",
"map",
"==",
"null",
"||",
"map",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"problemReporter",
".",
"report",
"(",... | Asserts the map is not null and not empty, reporting to {@link ProblemReporter} with this context if it is.
@param map Map to assert on.
@param propertyName Name of property. | [
"Asserts",
"the",
"map",
"is",
"not",
"null",
"and",
"not",
"empty",
"reporting",
"to",
"{",
"@link",
"ProblemReporter",
"}",
"with",
"this",
"context",
"if",
"it",
"is",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java#L102-L106 |
mfornos/humanize | humanize-icu/src/main/java/humanize/ICUHumanize.java | ICUHumanize.formatDate | public static String formatDate(final int style, final Date value)
{
return context.get().formatDate(style, value);
} | java | public static String formatDate(final int style, final Date value)
{
return context.get().formatDate(style, value);
} | [
"public",
"static",
"String",
"formatDate",
"(",
"final",
"int",
"style",
",",
"final",
"Date",
"value",
")",
"{",
"return",
"context",
".",
"get",
"(",
")",
".",
"formatDate",
"(",
"style",
",",
"value",
")",
";",
"}"
] | <p>
Formats the given date with the specified style.
</p>
@param style
DateFormat style
@param value
Date to be formatted
@return String representation of the date | [
"<p",
">",
"Formats",
"the",
"given",
"date",
"with",
"the",
"specified",
"style",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L747-L752 |
korpling/ANNIS | annis-widgets/src/main/java/annis/gui/components/ScreenshotMaker.java | ScreenshotMaker.parseAndCallback | private void parseAndCallback(String rawImage, ScreenshotCallback callback)
{
if(callback == null)
{
return;
}
// find the mime type
final String[] typeInfoAndData = rawImage.split(",");
String[] mimeAndEncoding = typeInfoAndData[0].replaceFirst("data:", "").split(";");
if(typeInfoAndData.length == 2 &&
mimeAndEncoding.length == 2
&& "base64".equalsIgnoreCase(mimeAndEncoding[1]))
{
byte[] result = Base64.decodeBase64(typeInfoAndData[1]);
callback.screenshotReceived(result, mimeAndEncoding[0]);
}
} | java | private void parseAndCallback(String rawImage, ScreenshotCallback callback)
{
if(callback == null)
{
return;
}
// find the mime type
final String[] typeInfoAndData = rawImage.split(",");
String[] mimeAndEncoding = typeInfoAndData[0].replaceFirst("data:", "").split(";");
if(typeInfoAndData.length == 2 &&
mimeAndEncoding.length == 2
&& "base64".equalsIgnoreCase(mimeAndEncoding[1]))
{
byte[] result = Base64.decodeBase64(typeInfoAndData[1]);
callback.screenshotReceived(result, mimeAndEncoding[0]);
}
} | [
"private",
"void",
"parseAndCallback",
"(",
"String",
"rawImage",
",",
"ScreenshotCallback",
"callback",
")",
"{",
"if",
"(",
"callback",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// find the mime type",
"final",
"String",
"[",
"]",
"typeInfoAndData",
"=",
... | Takes a raw string representing the result of the toDataURL() function
of the HTML5 canvas and calls the callback with a proper mime type
and the bytes of the image.
@see <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl">http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl</
@param rawImage The encoded image
@param callback The callback to call with the result.
@return | [
"Takes",
"a",
"raw",
"string",
"representing",
"the",
"result",
"of",
"the",
"toDataURL",
"()",
"function",
"of",
"the",
"HTML5",
"canvas",
"and",
"calls",
"the",
"callback",
"with",
"a",
"proper",
"mime",
"type",
"and",
"the",
"bytes",
"of",
"the",
"image... | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-widgets/src/main/java/annis/gui/components/ScreenshotMaker.java#L69-L87 |
joniles/mpxj | src/main/java/net/sf/mpxj/planner/PlannerWriter.java | PlannerWriter.writeTask | private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException
{
net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();
taskList.add(plannerTask);
plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));
plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));
plannerTask.setName(getString(mpxjTask.getName()));
plannerTask.setNote(mpxjTask.getNotes());
plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));
plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));
plannerTask.setScheduling(getScheduling(mpxjTask.getType()));
plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));
if (mpxjTask.getMilestone())
{
plannerTask.setType("milestone");
}
else
{
plannerTask.setType("normal");
}
plannerTask.setWork(getDurationString(mpxjTask.getWork()));
plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));
ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();
if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)
{
Constraint plannerConstraint = m_factory.createConstraint();
plannerTask.setConstraint(plannerConstraint);
if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)
{
plannerConstraint.setType("start-no-earlier-than");
}
else
{
if (mpxjConstraintType == ConstraintType.MUST_START_ON)
{
plannerConstraint.setType("must-start-on");
}
}
plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));
}
//
// Write predecessors
//
writePredecessors(mpxjTask, plannerTask);
m_eventManager.fireTaskWrittenEvent(mpxjTask);
//
// Write child tasks
//
List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();
for (Task task : mpxjTask.getChildTasks())
{
writeTask(task, childTaskList);
}
} | java | private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException
{
net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();
taskList.add(plannerTask);
plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));
plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));
plannerTask.setName(getString(mpxjTask.getName()));
plannerTask.setNote(mpxjTask.getNotes());
plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));
plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));
plannerTask.setScheduling(getScheduling(mpxjTask.getType()));
plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));
if (mpxjTask.getMilestone())
{
plannerTask.setType("milestone");
}
else
{
plannerTask.setType("normal");
}
plannerTask.setWork(getDurationString(mpxjTask.getWork()));
plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));
ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();
if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)
{
Constraint plannerConstraint = m_factory.createConstraint();
plannerTask.setConstraint(plannerConstraint);
if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)
{
plannerConstraint.setType("start-no-earlier-than");
}
else
{
if (mpxjConstraintType == ConstraintType.MUST_START_ON)
{
plannerConstraint.setType("must-start-on");
}
}
plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));
}
//
// Write predecessors
//
writePredecessors(mpxjTask, plannerTask);
m_eventManager.fireTaskWrittenEvent(mpxjTask);
//
// Write child tasks
//
List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();
for (Task task : mpxjTask.getChildTasks())
{
writeTask(task, childTaskList);
}
} | [
"private",
"void",
"writeTask",
"(",
"Task",
"mpxjTask",
",",
"List",
"<",
"net",
".",
"sf",
".",
"mpxj",
".",
"planner",
".",
"schema",
".",
"Task",
">",
"taskList",
")",
"throws",
"JAXBException",
"{",
"net",
".",
"sf",
".",
"mpxj",
".",
"planner",
... | This method writes data for a single task to a Planner file.
@param mpxjTask MPXJ Task instance
@param taskList list of child tasks for current parent | [
"This",
"method",
"writes",
"data",
"for",
"a",
"single",
"task",
"to",
"a",
"Planner",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/planner/PlannerWriter.java#L437-L495 |
gitblit/fathom | fathom-security/src/main/java/fathom/realm/Account.java | Account.checkRoles | public void checkRoles(String... roleIdentifiers) throws AuthorizationException {
if (!hasRoles(roleIdentifiers)) {
throw new AuthorizationException("'{}' does not have the roles {}", toString(), Arrays.toString(roleIdentifiers));
}
} | java | public void checkRoles(String... roleIdentifiers) throws AuthorizationException {
if (!hasRoles(roleIdentifiers)) {
throw new AuthorizationException("'{}' does not have the roles {}", toString(), Arrays.toString(roleIdentifiers));
}
} | [
"public",
"void",
"checkRoles",
"(",
"String",
"...",
"roleIdentifiers",
")",
"throws",
"AuthorizationException",
"{",
"if",
"(",
"!",
"hasRoles",
"(",
"roleIdentifiers",
")",
")",
"{",
"throw",
"new",
"AuthorizationException",
"(",
"\"'{}' does not have the roles {}\... | Asserts this Account has all of the specified roles by returning quietly if they do or throwing an
{@link fathom.authz.AuthorizationException} if they do not.
@param roleIdentifiers roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
@throws AuthorizationException fathom.authz.AuthorizationException
if this Account does not have all of the specified roles. | [
"Asserts",
"this",
"Account",
"has",
"all",
"of",
"the",
"specified",
"roles",
"by",
"returning",
"quietly",
"if",
"they",
"do",
"or",
"throwing",
"an",
"{",
"@link",
"fathom",
".",
"authz",
".",
"AuthorizationException",
"}",
"if",
"they",
"do",
"not",
".... | train | https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/realm/Account.java#L407-L411 |
elastic/elasticsearch-hadoop | mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/UpdateBulkFactory.java | UpdateBulkFactory.writeStrictFormatting | private void writeStrictFormatting(List<Object> list, Object paramExtractor, String scriptToUse) {
if (HAS_SCRIPT) {
/*
* {
* "script":{
* "inline": "...",
* "lang": "...",
* "params": ...,
* },
* "upsert": {...}
* }
*/
list.add(scriptToUse);
if (HAS_LANG) {
list.add(SCRIPT_LANG_5X);
}
if (paramExtractor != null) {
list.add(",\"params\":");
list.add(paramExtractor);
}
list.add("}");
if (UPSERT) {
list.add(",\"upsert\":");
}
} else {
/*
* {
* "doc_as_upsert": true,
* "doc": {...}
* }
*/
list.add("{");
if (UPSERT) {
list.add("\"doc_as_upsert\":true,");
}
list.add("\"doc\":");
}
} | java | private void writeStrictFormatting(List<Object> list, Object paramExtractor, String scriptToUse) {
if (HAS_SCRIPT) {
/*
* {
* "script":{
* "inline": "...",
* "lang": "...",
* "params": ...,
* },
* "upsert": {...}
* }
*/
list.add(scriptToUse);
if (HAS_LANG) {
list.add(SCRIPT_LANG_5X);
}
if (paramExtractor != null) {
list.add(",\"params\":");
list.add(paramExtractor);
}
list.add("}");
if (UPSERT) {
list.add(",\"upsert\":");
}
} else {
/*
* {
* "doc_as_upsert": true,
* "doc": {...}
* }
*/
list.add("{");
if (UPSERT) {
list.add("\"doc_as_upsert\":true,");
}
list.add("\"doc\":");
}
} | [
"private",
"void",
"writeStrictFormatting",
"(",
"List",
"<",
"Object",
">",
"list",
",",
"Object",
"paramExtractor",
",",
"String",
"scriptToUse",
")",
"{",
"if",
"(",
"HAS_SCRIPT",
")",
"{",
"/*\n * {\n * \"script\":{\n * \"inli... | Script format meant for versions 2.x to 5.x. Required format for 5.x and above.
@param list Consumer of snippets
@param paramExtractor Extracts parameters from documents or constants | [
"Script",
"format",
"meant",
"for",
"versions",
"2",
".",
"x",
"to",
"5",
".",
"x",
".",
"Required",
"format",
"for",
"5",
".",
"x",
"and",
"above",
"."
] | train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/UpdateBulkFactory.java#L175-L212 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java | TypeConverter.convertToLong | public static long convertToLong (@Nonnull final Object aSrcValue)
{
if (aSrcValue == null)
throw new TypeConverterException (long.class, EReason.NULL_SOURCE_NOT_ALLOWED);
final Long aValue = convert (aSrcValue, Long.class);
return aValue.longValue ();
} | java | public static long convertToLong (@Nonnull final Object aSrcValue)
{
if (aSrcValue == null)
throw new TypeConverterException (long.class, EReason.NULL_SOURCE_NOT_ALLOWED);
final Long aValue = convert (aSrcValue, Long.class);
return aValue.longValue ();
} | [
"public",
"static",
"long",
"convertToLong",
"(",
"@",
"Nonnull",
"final",
"Object",
"aSrcValue",
")",
"{",
"if",
"(",
"aSrcValue",
"==",
"null",
")",
"throw",
"new",
"TypeConverterException",
"(",
"long",
".",
"class",
",",
"EReason",
".",
"NULL_SOURCE_NOT_AL... | Convert the passed source value to long
@param aSrcValue
The source value. May not be <code>null</code>.
@return The converted value.
@throws TypeConverterException
if the source value is <code>null</code> or if no converter was
found or if the converter returned a <code>null</code> object.
@throws RuntimeException
If the converter itself throws an exception
@see TypeConverterProviderBestMatch | [
"Convert",
"the",
"passed",
"source",
"value",
"to",
"long"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java#L354-L360 |
dmak/jaxb-xew-plugin | src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java | XmlElementWrapperPlugin.deleteFactoryMethod | private int deleteFactoryMethod(JDefinedClass factoryClass, Candidate candidate) {
int deletedMethods = 0;
for (Iterator<JMethod> iter = factoryClass.methods().iterator(); iter.hasNext();) {
JMethod method = iter.next();
// Remove the methods:
// * public T createT() { return new T(); }
// * public JAXBElement<T> createT(T value) { return new JAXBElement<T>(QNAME, T.class, null, value); }
// * @XmlElementDecl(..., scope = X.class)
// public JAXBElement<T> createT...(T value) { return new JAXBElement<...>(QNAME, T.class, X.class, value); }
if ((method.type() instanceof JDefinedClass
&& ((JDefinedClass) method.type()).isAssignableFrom(candidate.getClazz()))
|| isListedAsParametrisation(candidate.getClazz(), method.type())
|| candidate.getScopedElementInfos().containsKey(method.name())) {
writeSummary("\tRemoving factory method [" + method.type().fullName() + "#" + method.name()
+ "()] from " + factoryClass.fullName());
iter.remove();
deletedMethods++;
}
}
return deletedMethods;
} | java | private int deleteFactoryMethod(JDefinedClass factoryClass, Candidate candidate) {
int deletedMethods = 0;
for (Iterator<JMethod> iter = factoryClass.methods().iterator(); iter.hasNext();) {
JMethod method = iter.next();
// Remove the methods:
// * public T createT() { return new T(); }
// * public JAXBElement<T> createT(T value) { return new JAXBElement<T>(QNAME, T.class, null, value); }
// * @XmlElementDecl(..., scope = X.class)
// public JAXBElement<T> createT...(T value) { return new JAXBElement<...>(QNAME, T.class, X.class, value); }
if ((method.type() instanceof JDefinedClass
&& ((JDefinedClass) method.type()).isAssignableFrom(candidate.getClazz()))
|| isListedAsParametrisation(candidate.getClazz(), method.type())
|| candidate.getScopedElementInfos().containsKey(method.name())) {
writeSummary("\tRemoving factory method [" + method.type().fullName() + "#" + method.name()
+ "()] from " + factoryClass.fullName());
iter.remove();
deletedMethods++;
}
}
return deletedMethods;
} | [
"private",
"int",
"deleteFactoryMethod",
"(",
"JDefinedClass",
"factoryClass",
",",
"Candidate",
"candidate",
")",
"{",
"int",
"deletedMethods",
"=",
"0",
";",
"for",
"(",
"Iterator",
"<",
"JMethod",
">",
"iter",
"=",
"factoryClass",
".",
"methods",
"(",
")",
... | Remove method {@code ObjectFactory} that creates an object of a given {@code clazz}.
@return {@code 1} if such method was successfully located and removed | [
"Remove",
"method",
"{",
"@code",
"ObjectFactory",
"}",
"that",
"creates",
"an",
"object",
"of",
"a",
"given",
"{",
"@code",
"clazz",
"}",
"."
] | train | https://github.com/dmak/jaxb-xew-plugin/blob/d564d6bf8e50c46b056cdb4b46d1d4bee4adfbe3/src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java#L824-L848 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.countByG_C | @Override
public int countByG_C(long groupId, String code) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_C;
Object[] finderArgs = new Object[] { groupId, code };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_COMMERCECURRENCY_WHERE);
query.append(_FINDER_COLUMN_G_C_GROUPID_2);
boolean bindCode = false;
if (code == null) {
query.append(_FINDER_COLUMN_G_C_CODE_1);
}
else if (code.equals("")) {
query.append(_FINDER_COLUMN_G_C_CODE_3);
}
else {
bindCode = true;
query.append(_FINDER_COLUMN_G_C_CODE_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindCode) {
qPos.add(code);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByG_C(long groupId, String code) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_C;
Object[] finderArgs = new Object[] { groupId, code };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_COMMERCECURRENCY_WHERE);
query.append(_FINDER_COLUMN_G_C_GROUPID_2);
boolean bindCode = false;
if (code == null) {
query.append(_FINDER_COLUMN_G_C_CODE_1);
}
else if (code.equals("")) {
query.append(_FINDER_COLUMN_G_C_CODE_3);
}
else {
bindCode = true;
query.append(_FINDER_COLUMN_G_C_CODE_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindCode) {
qPos.add(code);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByG_C",
"(",
"long",
"groupId",
",",
"String",
"code",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_G_C",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[",
"]",
"{",
"groupId",
",",
... | Returns the number of commerce currencies where groupId = ? and code = ?.
@param groupId the group ID
@param code the code
@return the number of matching commerce currencies | [
"Returns",
"the",
"number",
"of",
"commerce",
"currencies",
"where",
"groupId",
"=",
"?",
";",
"and",
"code",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L2172-L2233 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/visunproj/XYPlotVisualization.java | XYPlotVisualization.setupCSS | private void setupCSS(VisualizerContext context, SVGPlot svgp, XYPlot plot) {
StyleLibrary style = context.getStyleLibrary();
for(XYPlot.Curve curve : plot) {
CSSClass csscls = new CSSClass(this, SERIESID + curve.getColor());
// csscls.setStatement(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.2%");
csscls.setStatement(SVGConstants.SVG_FILL_ATTRIBUTE, SVGConstants.SVG_NONE_VALUE);
style.lines().formatCSSClass(csscls, curve.getColor(), style.getLineWidth(StyleLibrary.XYCURVE));
svgp.addCSSClassOrLogError(csscls);
}
// Axis label
CSSClass label = new CSSClass(this, CSS_AXIS_LABEL);
label.setStatement(SVGConstants.CSS_FILL_PROPERTY, style.getTextColor(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, style.getFontFamily(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, style.getTextSize(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_TEXT_ANCHOR_PROPERTY, SVGConstants.CSS_MIDDLE_VALUE);
svgp.addCSSClassOrLogError(label);
svgp.updateStyleElement();
} | java | private void setupCSS(VisualizerContext context, SVGPlot svgp, XYPlot plot) {
StyleLibrary style = context.getStyleLibrary();
for(XYPlot.Curve curve : plot) {
CSSClass csscls = new CSSClass(this, SERIESID + curve.getColor());
// csscls.setStatement(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.2%");
csscls.setStatement(SVGConstants.SVG_FILL_ATTRIBUTE, SVGConstants.SVG_NONE_VALUE);
style.lines().formatCSSClass(csscls, curve.getColor(), style.getLineWidth(StyleLibrary.XYCURVE));
svgp.addCSSClassOrLogError(csscls);
}
// Axis label
CSSClass label = new CSSClass(this, CSS_AXIS_LABEL);
label.setStatement(SVGConstants.CSS_FILL_PROPERTY, style.getTextColor(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, style.getFontFamily(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, style.getTextSize(StyleLibrary.XYCURVE));
label.setStatement(SVGConstants.CSS_TEXT_ANCHOR_PROPERTY, SVGConstants.CSS_MIDDLE_VALUE);
svgp.addCSSClassOrLogError(label);
svgp.updateStyleElement();
} | [
"private",
"void",
"setupCSS",
"(",
"VisualizerContext",
"context",
",",
"SVGPlot",
"svgp",
",",
"XYPlot",
"plot",
")",
"{",
"StyleLibrary",
"style",
"=",
"context",
".",
"getStyleLibrary",
"(",
")",
";",
"for",
"(",
"XYPlot",
".",
"Curve",
"curve",
":",
"... | Setup the CSS classes for the plot.
@param svgp Plot
@param plot Plot to render | [
"Setup",
"the",
"CSS",
"classes",
"for",
"the",
"plot",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/visunproj/XYPlotVisualization.java#L135-L152 |
networknt/light-4j | http-url/src/main/java/com/networknt/url/URLNormalizer.java | URLNormalizer.removeSessionIds | public URLNormalizer removeSessionIds() {
if (StringUtils.containsIgnoreCase(url, ";jsessionid=")) {
url = url.replaceFirst(
"(;jsessionid=([A-F0-9]+)((\\.\\w+)*))", "");
} else {
String u = StringUtils.substringBefore(url, "?");
String q = StringUtils.substringAfter(url, "?");
if (StringUtils.containsIgnoreCase(url, "PHPSESSID=")) {
q = q.replaceFirst("(&|^)(PHPSESSID=[0-9a-zA-Z]*)", "");
} else if (StringUtils.containsIgnoreCase(url, "ASPSESSIONID")) {
q = q.replaceFirst(
"(&|^)(ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]*)", "");
}
if (!StringUtils.isBlank(q)) {
u += "?" + StringUtils.removeStart(q, "&");
}
url = u;
}
return this;
} | java | public URLNormalizer removeSessionIds() {
if (StringUtils.containsIgnoreCase(url, ";jsessionid=")) {
url = url.replaceFirst(
"(;jsessionid=([A-F0-9]+)((\\.\\w+)*))", "");
} else {
String u = StringUtils.substringBefore(url, "?");
String q = StringUtils.substringAfter(url, "?");
if (StringUtils.containsIgnoreCase(url, "PHPSESSID=")) {
q = q.replaceFirst("(&|^)(PHPSESSID=[0-9a-zA-Z]*)", "");
} else if (StringUtils.containsIgnoreCase(url, "ASPSESSIONID")) {
q = q.replaceFirst(
"(&|^)(ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]*)", "");
}
if (!StringUtils.isBlank(q)) {
u += "?" + StringUtils.removeStart(q, "&");
}
url = u;
}
return this;
} | [
"public",
"URLNormalizer",
"removeSessionIds",
"(",
")",
"{",
"if",
"(",
"StringUtils",
".",
"containsIgnoreCase",
"(",
"url",
",",
"\";jsessionid=\"",
")",
")",
"{",
"url",
"=",
"url",
".",
"replaceFirst",
"(",
"\"(;jsessionid=([A-F0-9]+)((\\\\.\\\\w+)*))\"",
",",
... | <p>Removes a URL-based session id. It removes PHP (PHPSESSID),
ASP (ASPSESSIONID), and Java EE (jsessionid) session ids.</p>
<code>http://www.example.com/servlet;jsessionid=1E6FEC0D14D044541DD84D2D013D29ED?a=b
→ http://www.example.com/servlet?a=b</code>
<p><b>Please Note:</b> Removing session IDs from URLs is often
a good way to have the URL return an error once invoked.</p>
@return this instance | [
"<p",
">",
"Removes",
"a",
"URL",
"-",
"based",
"session",
"id",
".",
"It",
"removes",
"PHP",
"(",
"PHPSESSID",
")",
"ASP",
"(",
"ASPSESSIONID",
")",
"and",
"Java",
"EE",
"(",
"jsessionid",
")",
"session",
"ids",
".",
"<",
"/",
"p",
">",
"<code",
"... | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/http-url/src/main/java/com/networknt/url/URLNormalizer.java#L742-L761 |
httl/httl | httl/src/main/java/httl/util/ConcurrentLinkedHashMap.java | ConcurrentLinkedHashMap.runTasks | void runTasks(Task[] tasks, int maxTaskIndex) {
for (int i = 0; i <= maxTaskIndex; i++) {
runTasksInChain(tasks[i]);
tasks[i] = null;
}
} | java | void runTasks(Task[] tasks, int maxTaskIndex) {
for (int i = 0; i <= maxTaskIndex; i++) {
runTasksInChain(tasks[i]);
tasks[i] = null;
}
} | [
"void",
"runTasks",
"(",
"Task",
"[",
"]",
"tasks",
",",
"int",
"maxTaskIndex",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<=",
"maxTaskIndex",
";",
"i",
"++",
")",
"{",
"runTasksInChain",
"(",
"tasks",
"[",
"i",
"]",
")",
";",
"tasks... | Runs the pending page replacement policy operations.
@param tasks the ordered array of the pending operations
@param maxTaskIndex the maximum index of the array | [
"Runs",
"the",
"pending",
"page",
"replacement",
"policy",
"operations",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/util/ConcurrentLinkedHashMap.java#L522-L527 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java | AsteriskQueueImpl.removeEntry | void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived)
{
synchronized (serviceLevelTimerTasks)
{
if (serviceLevelTimerTasks.containsKey(entry))
{
ServiceLevelTimerTask timerTask = serviceLevelTimerTasks.get(entry);
timerTask.cancel();
serviceLevelTimerTasks.remove(entry);
}
}
boolean changed;
synchronized (entries)
{
changed = entries.remove(entry);
if (changed)
{
// Keep the lock !
shift();
}
}
// Fire outside lock
if (changed)
{
entry.getChannel().setQueueEntry(null);
entry.left(dateReceived);
fireEntryLeave(entry);
}
} | java | void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived)
{
synchronized (serviceLevelTimerTasks)
{
if (serviceLevelTimerTasks.containsKey(entry))
{
ServiceLevelTimerTask timerTask = serviceLevelTimerTasks.get(entry);
timerTask.cancel();
serviceLevelTimerTasks.remove(entry);
}
}
boolean changed;
synchronized (entries)
{
changed = entries.remove(entry);
if (changed)
{
// Keep the lock !
shift();
}
}
// Fire outside lock
if (changed)
{
entry.getChannel().setQueueEntry(null);
entry.left(dateReceived);
fireEntryLeave(entry);
}
} | [
"void",
"removeEntry",
"(",
"AsteriskQueueEntryImpl",
"entry",
",",
"Date",
"dateReceived",
")",
"{",
"synchronized",
"(",
"serviceLevelTimerTasks",
")",
"{",
"if",
"(",
"serviceLevelTimerTasks",
".",
"containsKey",
"(",
"entry",
")",
")",
"{",
"ServiceLevelTimerTas... | Removes the given queue entry from the queue.<p>
Fires if needed:
<ul>
<li>PCE on channel</li>
<li>EntryLeave on this queue</li>
<li>PCE on other queue entries if shifted</li>
</ul>
@param entry an existing entry object.
@param dateReceived the remove event was received. | [
"Removes",
"the",
"given",
"queue",
"entry",
"from",
"the",
"queue",
".",
"<p",
">",
"Fires",
"if",
"needed",
":",
"<ul",
">",
"<li",
">",
"PCE",
"on",
"channel<",
"/",
"li",
">",
"<li",
">",
"EntryLeave",
"on",
"this",
"queue<",
"/",
"li",
">",
"<... | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java#L399-L430 |
vincentk/joptimizer | src/main/java/com/joptimizer/algebra/MatrixLogSumRescaler.java | MatrixLogSumRescaler.checkScaling | @Override
public boolean checkScaling(final DoubleMatrix2D A,
final DoubleMatrix1D U, final DoubleMatrix1D V){
final double log10_2 = Math.log10(base);
final double[] originalOFValue = {0};
final double[] scaledOFValue = {0};
final double[] x = new double[A.rows()];
final double[] y = new double[A.columns()];
A.forEachNonZero(new IntIntDoubleFunction() {
@Override
public double apply(int i, int j, double aij) {
double v = Math.log10(Math.abs(aij)) / log10_2 + 0.5;
originalOFValue[0] = originalOFValue[0] + Math.pow(v, 2);
double xi = Math.log10(U.getQuick(i)) / log10_2;
double yj = Math.log10(V.getQuick(j)) / log10_2;
scaledOFValue[0] = scaledOFValue[0] + Math.pow(xi + yj + v, 2);
x[i] = xi;
y[j] = yj;
return aij;
}
});
originalOFValue[0] = 0.5 * originalOFValue[0];
scaledOFValue[0] = 0.5 * scaledOFValue[0];
logger.debug("x: " + ArrayUtils.toString(x));
logger.debug("y: " + ArrayUtils.toString(y));
logger.debug("originalOFValue: " + originalOFValue[0]);
logger.debug("scaledOFValue : " + scaledOFValue[0]);
return !(originalOFValue[0] < scaledOFValue[0]);
} | java | @Override
public boolean checkScaling(final DoubleMatrix2D A,
final DoubleMatrix1D U, final DoubleMatrix1D V){
final double log10_2 = Math.log10(base);
final double[] originalOFValue = {0};
final double[] scaledOFValue = {0};
final double[] x = new double[A.rows()];
final double[] y = new double[A.columns()];
A.forEachNonZero(new IntIntDoubleFunction() {
@Override
public double apply(int i, int j, double aij) {
double v = Math.log10(Math.abs(aij)) / log10_2 + 0.5;
originalOFValue[0] = originalOFValue[0] + Math.pow(v, 2);
double xi = Math.log10(U.getQuick(i)) / log10_2;
double yj = Math.log10(V.getQuick(j)) / log10_2;
scaledOFValue[0] = scaledOFValue[0] + Math.pow(xi + yj + v, 2);
x[i] = xi;
y[j] = yj;
return aij;
}
});
originalOFValue[0] = 0.5 * originalOFValue[0];
scaledOFValue[0] = 0.5 * scaledOFValue[0];
logger.debug("x: " + ArrayUtils.toString(x));
logger.debug("y: " + ArrayUtils.toString(y));
logger.debug("originalOFValue: " + originalOFValue[0]);
logger.debug("scaledOFValue : " + scaledOFValue[0]);
return !(originalOFValue[0] < scaledOFValue[0]);
} | [
"@",
"Override",
"public",
"boolean",
"checkScaling",
"(",
"final",
"DoubleMatrix2D",
"A",
",",
"final",
"DoubleMatrix1D",
"U",
",",
"final",
"DoubleMatrix1D",
"V",
")",
"{",
"final",
"double",
"log10_2",
"=",
"Math",
".",
"log10",
"(",
"base",
")",
";",
"... | Check if the scaling algorithm returned proper results.
Note that the scaling algorithm is for minimizing a given objective function of the original matrix elements, and
the check will be done on the value of this objective function.
@param A the ORIGINAL (before scaling) matrix
@param U the return of the scaling algorithm
@param V the return of the scaling algorithm
@param base
@return | [
"Check",
"if",
"the",
"scaling",
"algorithm",
"returned",
"proper",
"results",
".",
"Note",
"that",
"the",
"scaling",
"algorithm",
"is",
"for",
"minimizing",
"a",
"given",
"objective",
"function",
"of",
"the",
"original",
"matrix",
"elements",
"and",
"the",
"c... | train | https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/algebra/MatrixLogSumRescaler.java#L242-L274 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/CatalogUtil.java | CatalogUtil.compileDeployment | public static String compileDeployment(Catalog catalog,
DeploymentType deployment,
boolean isPlaceHolderCatalog)
{
String errmsg = null;
try {
validateDeployment(catalog, deployment);
// add our hacky Deployment to the catalog
if (catalog.getClusters().get("cluster").getDeployment().get("deployment") == null) {
catalog.getClusters().get("cluster").getDeployment().add("deployment");
}
// set the cluster info
setClusterInfo(catalog, deployment);
//Set the snapshot schedule
setSnapshotInfo(catalog, deployment.getSnapshot());
//Set enable security
setSecurityEnabled(catalog, deployment.getSecurity());
// set the users info
// We'll skip this when building the dummy catalog on startup
// so that we don't spew misleading user/role warnings
if (!isPlaceHolderCatalog) {
setUsersInfo(catalog, deployment.getUsers());
}
// set the HTTPD info
setHTTPDInfo(catalog, deployment.getHttpd(), deployment.getSsl());
setDrInfo(catalog, deployment.getDr(), deployment.getCluster(), isPlaceHolderCatalog);
if (!isPlaceHolderCatalog) {
setExportInfo(catalog, deployment.getExport());
setImportInfo(catalog, deployment.getImport());
setSnmpInfo(deployment.getSnmp());
}
setCommandLogInfo( catalog, deployment.getCommandlog());
//This is here so we can update our local list of paths.
//I would not have needed this if validateResourceMonitorInfo didnt exist here.
VoltDB.instance().loadLegacyPathProperties(deployment);
setupPaths(deployment.getPaths());
validateResourceMonitorInfo(deployment);
}
catch (Exception e) {
// Anything that goes wrong anywhere in trying to handle the deployment file
// should return an error, and let the caller decide what to do (crash or not, for
// example)
errmsg = "Error validating deployment configuration: " + e.getMessage();
hostLog.error(errmsg);
return errmsg;
}
return null;
} | java | public static String compileDeployment(Catalog catalog,
DeploymentType deployment,
boolean isPlaceHolderCatalog)
{
String errmsg = null;
try {
validateDeployment(catalog, deployment);
// add our hacky Deployment to the catalog
if (catalog.getClusters().get("cluster").getDeployment().get("deployment") == null) {
catalog.getClusters().get("cluster").getDeployment().add("deployment");
}
// set the cluster info
setClusterInfo(catalog, deployment);
//Set the snapshot schedule
setSnapshotInfo(catalog, deployment.getSnapshot());
//Set enable security
setSecurityEnabled(catalog, deployment.getSecurity());
// set the users info
// We'll skip this when building the dummy catalog on startup
// so that we don't spew misleading user/role warnings
if (!isPlaceHolderCatalog) {
setUsersInfo(catalog, deployment.getUsers());
}
// set the HTTPD info
setHTTPDInfo(catalog, deployment.getHttpd(), deployment.getSsl());
setDrInfo(catalog, deployment.getDr(), deployment.getCluster(), isPlaceHolderCatalog);
if (!isPlaceHolderCatalog) {
setExportInfo(catalog, deployment.getExport());
setImportInfo(catalog, deployment.getImport());
setSnmpInfo(deployment.getSnmp());
}
setCommandLogInfo( catalog, deployment.getCommandlog());
//This is here so we can update our local list of paths.
//I would not have needed this if validateResourceMonitorInfo didnt exist here.
VoltDB.instance().loadLegacyPathProperties(deployment);
setupPaths(deployment.getPaths());
validateResourceMonitorInfo(deployment);
}
catch (Exception e) {
// Anything that goes wrong anywhere in trying to handle the deployment file
// should return an error, and let the caller decide what to do (crash or not, for
// example)
errmsg = "Error validating deployment configuration: " + e.getMessage();
hostLog.error(errmsg);
return errmsg;
}
return null;
} | [
"public",
"static",
"String",
"compileDeployment",
"(",
"Catalog",
"catalog",
",",
"DeploymentType",
"deployment",
",",
"boolean",
"isPlaceHolderCatalog",
")",
"{",
"String",
"errmsg",
"=",
"null",
";",
"try",
"{",
"validateDeployment",
"(",
"catalog",
",",
"deplo... | Parse the deployment.xml file and add its data into the catalog.
@param catalog Catalog to be updated.
@param deployment Parsed representation of the deployment.xml file.
@param isPlaceHolderCatalog if the catalog is isPlaceHolderCatalog and we are verifying only deployment xml.
@return String containing any errors parsing/validating the deployment. NULL on success. | [
"Parse",
"the",
"deployment",
".",
"xml",
"file",
"and",
"add",
"its",
"data",
"into",
"the",
"catalog",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/CatalogUtil.java#L864-L923 |
cdk/cdk | descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java | XLogPDescriptor.getDoubleBondedSulfurCount | private int getDoubleBondedSulfurCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
IBond bond;
int sdbcounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("S")) {
if (atom.getFormalCharge() == 1 && neighbour.getFormalCharge() == -1) {
sdbcounter += 1;
}
bond = ac.getBond(neighbour, atom);
if (!neighbour.getFlag(CDKConstants.ISAROMATIC)) {
if (bond.getOrder() == IBond.Order.DOUBLE) {
sdbcounter += 1;
}
}
}
}
return sdbcounter;
} | java | private int getDoubleBondedSulfurCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
IBond bond;
int sdbcounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("S")) {
if (atom.getFormalCharge() == 1 && neighbour.getFormalCharge() == -1) {
sdbcounter += 1;
}
bond = ac.getBond(neighbour, atom);
if (!neighbour.getFlag(CDKConstants.ISAROMATIC)) {
if (bond.getOrder() == IBond.Order.DOUBLE) {
sdbcounter += 1;
}
}
}
}
return sdbcounter;
} | [
"private",
"int",
"getDoubleBondedSulfurCount",
"(",
"IAtomContainer",
"ac",
",",
"IAtom",
"atom",
")",
"{",
"List",
"<",
"IAtom",
">",
"neighbours",
"=",
"ac",
".",
"getConnectedAtomsList",
"(",
"atom",
")",
";",
"IBond",
"bond",
";",
"int",
"sdbcounter",
"... | Gets the doubleBondedSulfurCount attribute of the XLogPDescriptor object.
@param ac Description of the Parameter
@param atom Description of the Parameter
@return The doubleBondedSulfurCount value | [
"Gets",
"the",
"doubleBondedSulfurCount",
"attribute",
"of",
"the",
"XLogPDescriptor",
"object",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java#L1185-L1203 |
DiUS/pact-jvm | pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java | PactDslJsonArray.arrayMinMaxLike | public static PactDslJsonArray arrayMinMaxLike(int minSize, int maxSize, int numberExamples, PactDslJsonRootValue value) {
if (numberExamples < minSize) {
throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d",
numberExamples, minSize));
} if (numberExamples > maxSize) {
throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d",
numberExamples, maxSize));
}
PactDslJsonArray parent = new PactDslJsonArray("", "", null, true);
parent.setNumberExamples(numberExamples);
parent.matchers.addRule("", parent.matchMinMax(minSize, maxSize));
parent.putObject(value);
return parent;
} | java | public static PactDslJsonArray arrayMinMaxLike(int minSize, int maxSize, int numberExamples, PactDslJsonRootValue value) {
if (numberExamples < minSize) {
throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d",
numberExamples, minSize));
} if (numberExamples > maxSize) {
throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d",
numberExamples, maxSize));
}
PactDslJsonArray parent = new PactDslJsonArray("", "", null, true);
parent.setNumberExamples(numberExamples);
parent.matchers.addRule("", parent.matchMinMax(minSize, maxSize));
parent.putObject(value);
return parent;
} | [
"public",
"static",
"PactDslJsonArray",
"arrayMinMaxLike",
"(",
"int",
"minSize",
",",
"int",
"maxSize",
",",
"int",
"numberExamples",
",",
"PactDslJsonRootValue",
"value",
")",
"{",
"if",
"(",
"numberExamples",
"<",
"minSize",
")",
"{",
"throw",
"new",
"Illegal... | Root level array with minimum and maximum size where each item must match the provided matcher
@param minSize minimum size
@param maxSize maximum size
@param numberExamples Number of examples to generate | [
"Root",
"level",
"array",
"with",
"minimum",
"and",
"maximum",
"size",
"where",
"each",
"item",
"must",
"match",
"the",
"provided",
"matcher"
] | train | https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L907-L920 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/FileSteps.java | FileSteps.checkFile | @Conditioned
@Alors("Le fichier '(.*)' encodé en '(.*)' vérifie '(.*)'[\\.|\\?]")
@Then("The file '(.*)' encoded in '(.*)' matches '(.*)'[\\.|\\?]")
public void checkFile(String file, String encoding, String regexp, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
try {
final Matcher m = Pattern.compile(regexp)
.matcher(FileUtils.readFileToString(new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + file), encoding));
if (!m.find()) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_MATCHES), file, regexp), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
} catch (final IOException e) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_FOUND), file), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
} | java | @Conditioned
@Alors("Le fichier '(.*)' encodé en '(.*)' vérifie '(.*)'[\\.|\\?]")
@Then("The file '(.*)' encoded in '(.*)' matches '(.*)'[\\.|\\?]")
public void checkFile(String file, String encoding, String regexp, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
try {
final Matcher m = Pattern.compile(regexp)
.matcher(FileUtils.readFileToString(new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + file), encoding));
if (!m.find()) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_MATCHES), file, regexp), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
} catch (final IOException e) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_FOUND), file), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
} | [
"@",
"Conditioned",
"@",
"Alors",
"(",
"\"Le fichier '(.*)' encodé en '(.*)' vérifie '(.*)'[\\\\.|\\\\?]\")",
"",
"@",
"Then",
"(",
"\"The file '(.*)' encoded in '(.*)' matches '(.*)'[\\\\.|\\\\?]\"",
")",
"public",
"void",
"checkFile",
"(",
"String",
"file",
",",
"String",
"... | Checks that a file in the default downloaded files folder matches the given regexp.
@param file
The name of the file
@param encoding
The file encoding
@param regexp
The pattern to match
@param conditions
List of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws TechnicalException
@throws FailureException | [
"Checks",
"that",
"a",
"file",
"in",
"the",
"default",
"downloaded",
"files",
"folder",
"matches",
"the",
"given",
"regexp",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/FileSteps.java#L95-L108 |
Danny02/JOpenCTM | src/main/java/darwin/jopenctm/compression/CommonAlgorithms.java | CommonAlgorithms.makeNormalCoordSys | public static float[] makeNormalCoordSys(float[] normals, int offset) {
float[] m = new float[9];
m[6] = normals[offset];
m[7] = normals[offset + 1];
m[8] = normals[offset + 2];
// Calculate a vector that is guaranteed to be orthogonal to the normal, non-
// zero, and a continuous function of the normal (no discrete jumps):
// X = (0,0,1) x normal + (1,0,0) x normal
m[0] = -normals[offset + 1];
m[1] = normals[offset] - normals[offset + 2];
m[2] = normals[offset + 1];
// Normalize the new X axis (note: |x[2]| = |x[0]|)
float len = (float) sqrt(2.0 * m[0] * m[0] + m[1] * m[1]);
if (len > 1.0e-20f) {
len = 1.0f / len;
m[0] *= len;
m[1] *= len;
m[2] *= len;
}
// Let Y = Z x X (no normalization needed, since |Z| = |X| = 1)
m[3 + 0] = m[6 + 1] * m[2] - m[6 + 2] * m[1];
m[3 + 1] = m[6 + 2] * m[0] - m[6 + 0] * m[2];
m[3 + 2] = m[6 + 0] * m[1] - m[6 + 1] * m[0];
return m;
} | java | public static float[] makeNormalCoordSys(float[] normals, int offset) {
float[] m = new float[9];
m[6] = normals[offset];
m[7] = normals[offset + 1];
m[8] = normals[offset + 2];
// Calculate a vector that is guaranteed to be orthogonal to the normal, non-
// zero, and a continuous function of the normal (no discrete jumps):
// X = (0,0,1) x normal + (1,0,0) x normal
m[0] = -normals[offset + 1];
m[1] = normals[offset] - normals[offset + 2];
m[2] = normals[offset + 1];
// Normalize the new X axis (note: |x[2]| = |x[0]|)
float len = (float) sqrt(2.0 * m[0] * m[0] + m[1] * m[1]);
if (len > 1.0e-20f) {
len = 1.0f / len;
m[0] *= len;
m[1] *= len;
m[2] *= len;
}
// Let Y = Z x X (no normalization needed, since |Z| = |X| = 1)
m[3 + 0] = m[6 + 1] * m[2] - m[6 + 2] * m[1];
m[3 + 1] = m[6 + 2] * m[0] - m[6 + 0] * m[2];
m[3 + 2] = m[6 + 0] * m[1] - m[6 + 1] * m[0];
return m;
} | [
"public",
"static",
"float",
"[",
"]",
"makeNormalCoordSys",
"(",
"float",
"[",
"]",
"normals",
",",
"int",
"offset",
")",
"{",
"float",
"[",
"]",
"m",
"=",
"new",
"float",
"[",
"9",
"]",
";",
"m",
"[",
"6",
"]",
"=",
"normals",
"[",
"offset",
"]... | Create an ortho-normalized coordinate system where the Z-axis is aligned
with the given normal.
<p>
Note 1: This function is central to how the
compressed normal data is interpreted, and it can not be changed
(mathematically) without making the coder/decoder incompatible with other
versions of the library!
<p>
Note 2: Since we do this for every single
normal, this routine needs to be fast. The current implementation uses:
12 MUL, 1 DIV, 1 SQRT, ~6 ADD.
@param normals the normal array, consecutive x,y,z coordinates
@param offset offset into the normal array
@return a 3x3 matrix defining the nroaml coordinate system | [
"Create",
"an",
"ortho",
"-",
"normalized",
"coordinate",
"system",
"where",
"the",
"Z",
"-",
"axis",
"is",
"aligned",
"with",
"the",
"given",
"normal",
".",
"<p",
">",
"Note",
"1",
":",
"This",
"function",
"is",
"central",
"to",
"how",
"the",
"compresse... | train | https://github.com/Danny02/JOpenCTM/blob/c55a2a2d166a55979190f1bb08214fc84c93008f/src/main/java/darwin/jopenctm/compression/CommonAlgorithms.java#L181-L210 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java | ProcessGroovyMethods.withWriter | public static void withWriter(final Process self, final Closure closure) {
new Thread(new Runnable() {
public void run() {
try {
IOGroovyMethods.withWriter(new BufferedOutputStream(getOut(self)), closure);
} catch (IOException e) {
throw new GroovyRuntimeException("exception while reading process stream", e);
}
}
}).start();
} | java | public static void withWriter(final Process self, final Closure closure) {
new Thread(new Runnable() {
public void run() {
try {
IOGroovyMethods.withWriter(new BufferedOutputStream(getOut(self)), closure);
} catch (IOException e) {
throw new GroovyRuntimeException("exception while reading process stream", e);
}
}
}).start();
} | [
"public",
"static",
"void",
"withWriter",
"(",
"final",
"Process",
"self",
",",
"final",
"Closure",
"closure",
")",
"{",
"new",
"Thread",
"(",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"IOGroovyMethods",
".",
... | Creates a new BufferedWriter as stdin for this process,
passes it to the closure, and ensures the stream is flushed
and closed after the closure returns.
A new Thread is started, so this method will return immediately.
@param self a Process
@param closure a closure
@since 1.5.2 | [
"Creates",
"a",
"new",
"BufferedWriter",
"as",
"stdin",
"for",
"this",
"process",
"passes",
"it",
"to",
"the",
"closure",
"and",
"ensures",
"the",
"stream",
"is",
"flushed",
"and",
"closed",
"after",
"the",
"closure",
"returns",
".",
"A",
"new",
"Thread",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L350-L360 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/TaskState.java | TaskState.updateByteMetrics | public synchronized void updateByteMetrics(long bytesWritten, int branchIndex) {
TaskMetrics metrics = TaskMetrics.get(this);
String forkBranchId = TaskMetrics.taskInstanceRemoved(this.taskId);
Counter taskByteCounter = metrics.getCounter(MetricGroup.TASK.name(), forkBranchId, BYTES);
long inc = bytesWritten - taskByteCounter.getCount();
taskByteCounter.inc(inc);
metrics.getMeter(MetricGroup.TASK.name(), forkBranchId, BYTES_PER_SECOND).mark(inc);
metrics.getCounter(MetricGroup.JOB.name(), this.jobId, BYTES).inc(inc);
metrics.getMeter(MetricGroup.JOB.name(), this.jobId, BYTES_PER_SECOND).mark(inc);
} | java | public synchronized void updateByteMetrics(long bytesWritten, int branchIndex) {
TaskMetrics metrics = TaskMetrics.get(this);
String forkBranchId = TaskMetrics.taskInstanceRemoved(this.taskId);
Counter taskByteCounter = metrics.getCounter(MetricGroup.TASK.name(), forkBranchId, BYTES);
long inc = bytesWritten - taskByteCounter.getCount();
taskByteCounter.inc(inc);
metrics.getMeter(MetricGroup.TASK.name(), forkBranchId, BYTES_PER_SECOND).mark(inc);
metrics.getCounter(MetricGroup.JOB.name(), this.jobId, BYTES).inc(inc);
metrics.getMeter(MetricGroup.JOB.name(), this.jobId, BYTES_PER_SECOND).mark(inc);
} | [
"public",
"synchronized",
"void",
"updateByteMetrics",
"(",
"long",
"bytesWritten",
",",
"int",
"branchIndex",
")",
"{",
"TaskMetrics",
"metrics",
"=",
"TaskMetrics",
".",
"get",
"(",
"this",
")",
";",
"String",
"forkBranchId",
"=",
"TaskMetrics",
".",
"taskInst... | Collect byte-level metrics.
@param bytesWritten number of bytes written by the writer
@param branchIndex fork branch index
@deprecated see {@link org.apache.gobblin.instrumented.writer.InstrumentedDataWriterBase}. | [
"Collect",
"byte",
"-",
"level",
"metrics",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/TaskState.java#L278-L288 |
ixa-ehu/kaflib | src/main/java/ixa/kaflib/KAFDocument.java | KAFDocument.newCoref | public Coref newCoref(List<Span<Term>> mentions) {
String newId = idManager.getNextId(AnnotationType.COREF);
Coref newCoref = new Coref(newId, mentions);
annotationContainer.add(newCoref, Layer.COREFERENCES, AnnotationType.COREF);
return newCoref;
} | java | public Coref newCoref(List<Span<Term>> mentions) {
String newId = idManager.getNextId(AnnotationType.COREF);
Coref newCoref = new Coref(newId, mentions);
annotationContainer.add(newCoref, Layer.COREFERENCES, AnnotationType.COREF);
return newCoref;
} | [
"public",
"Coref",
"newCoref",
"(",
"List",
"<",
"Span",
"<",
"Term",
">",
">",
"mentions",
")",
"{",
"String",
"newId",
"=",
"idManager",
".",
"getNextId",
"(",
"AnnotationType",
".",
"COREF",
")",
";",
"Coref",
"newCoref",
"=",
"new",
"Coref",
"(",
"... | Creates a new coreference. It assigns an appropriate ID to it. The Coref is added to the document.
@param references different mentions (list of targets) to the same entity.
@return a new coreference. | [
"Creates",
"a",
"new",
"coreference",
".",
"It",
"assigns",
"an",
"appropriate",
"ID",
"to",
"it",
".",
"The",
"Coref",
"is",
"added",
"to",
"the",
"document",
"."
] | train | https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L767-L772 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java | FeatureScopes.createStaticFeatureOnTypeLiteralScope | protected IScope createStaticFeatureOnTypeLiteralScope(
EObject featureCall,
XExpression receiver,
LightweightTypeReference receiverType,
TypeBucket receiverBucket,
IScope parent,
IFeatureScopeSession session) {
return new StaticFeatureOnTypeLiteralScope(parent, session, asAbstractFeatureCall(featureCall), receiver, receiverType, receiverBucket, operatorMapping);
} | java | protected IScope createStaticFeatureOnTypeLiteralScope(
EObject featureCall,
XExpression receiver,
LightweightTypeReference receiverType,
TypeBucket receiverBucket,
IScope parent,
IFeatureScopeSession session) {
return new StaticFeatureOnTypeLiteralScope(parent, session, asAbstractFeatureCall(featureCall), receiver, receiverType, receiverBucket, operatorMapping);
} | [
"protected",
"IScope",
"createStaticFeatureOnTypeLiteralScope",
"(",
"EObject",
"featureCall",
",",
"XExpression",
"receiver",
",",
"LightweightTypeReference",
"receiverType",
",",
"TypeBucket",
"receiverBucket",
",",
"IScope",
"parent",
",",
"IFeatureScopeSession",
"session"... | Creates a scope for the static features that are exposed by a type that was used, e.g.
{@code java.lang.String.valueOf(1)} where {@code valueOf(1)} is to be linked.
@param featureCall the feature call that is currently processed by the scoping infrastructure
@param receiver an optionally available receiver expression
@param receiverType the type of the receiver. It may be available even if the receiver itself is null, which indicates an implicit receiver.
@param receiverBucket the types that contribute the static features.
@param parent the parent scope. Is never null.
@param session the currently known scope session. Is never null. | [
"Creates",
"a",
"scope",
"for",
"the",
"static",
"features",
"that",
"are",
"exposed",
"by",
"a",
"type",
"that",
"was",
"used",
"e",
".",
"g",
".",
"{",
"@code",
"java",
".",
"lang",
".",
"String",
".",
"valueOf",
"(",
"1",
")",
"}",
"where",
"{",... | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java#L528-L536 |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.removeChars | @Deprecated
public static String removeChars(String S, char ch) {
int pos;
while((pos=S.indexOf(ch))!=-1) S=S.substring(0,pos)+S.substring(pos+1);
return S;
} | java | @Deprecated
public static String removeChars(String S, char ch) {
int pos;
while((pos=S.indexOf(ch))!=-1) S=S.substring(0,pos)+S.substring(pos+1);
return S;
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"removeChars",
"(",
"String",
"S",
",",
"char",
"ch",
")",
"{",
"int",
"pos",
";",
"while",
"(",
"(",
"pos",
"=",
"S",
".",
"indexOf",
"(",
"ch",
")",
")",
"!=",
"-",
"1",
")",
"S",
"=",
"S",
"."... | Removes all occurrences of a <code>char</code> from a <code>String</code>
@deprecated this method is slow and no longer supported | [
"Removes",
"all",
"occurrences",
"of",
"a",
"<code",
">",
"char<",
"/",
"code",
">",
"from",
"a",
"<code",
">",
"String<",
"/",
"code",
">"
] | train | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L685-L690 |
facebookarchive/hive-dwrf | hive-dwrf/src/main/java/com/facebook/hive/orc/RecordReaderImpl.java | RecordReaderImpl.shouldReadEagerly | protected boolean shouldReadEagerly(StripeInformation stripe, int currentSection) {
if (readEagerlyFromHdfsBytes <= 0) {
return readEagerlyFromHdfs;
}
long inputBytes = 0;
if (included == null) {
// This means there is no projection and all the columns would be read
inputBytes = stripe.getDataLength();
} else {
// Get a sum of lengths of all the streams desired to be read
List<OrcProto.Stream> streamList = stripeFooter.getStreamsList();
for (int i = currentSection; i < streamList.size(); i++) {
if (included[streamList.get(i).getColumn()]) {
inputBytes += streamList.get(i).getLength();
}
}
}
return inputBytes <= readEagerlyFromHdfsBytes;
} | java | protected boolean shouldReadEagerly(StripeInformation stripe, int currentSection) {
if (readEagerlyFromHdfsBytes <= 0) {
return readEagerlyFromHdfs;
}
long inputBytes = 0;
if (included == null) {
// This means there is no projection and all the columns would be read
inputBytes = stripe.getDataLength();
} else {
// Get a sum of lengths of all the streams desired to be read
List<OrcProto.Stream> streamList = stripeFooter.getStreamsList();
for (int i = currentSection; i < streamList.size(); i++) {
if (included[streamList.get(i).getColumn()]) {
inputBytes += streamList.get(i).getLength();
}
}
}
return inputBytes <= readEagerlyFromHdfsBytes;
} | [
"protected",
"boolean",
"shouldReadEagerly",
"(",
"StripeInformation",
"stripe",
",",
"int",
"currentSection",
")",
"{",
"if",
"(",
"readEagerlyFromHdfsBytes",
"<=",
"0",
")",
"{",
"return",
"readEagerlyFromHdfs",
";",
"}",
"long",
"inputBytes",
"=",
"0",
";",
"... | Calculates the total number of bytes to be read for the data streams.
If this sum is <= {@code readEagerlyFromHdfsBytes}, return true else return false | [
"Calculates",
"the",
"total",
"number",
"of",
"bytes",
"to",
"be",
"read",
"for",
"the",
"data",
"streams",
".",
"If",
"this",
"sum",
"is",
"<",
"=",
"{"
] | train | https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/RecordReaderImpl.java#L379-L399 |
gfk-ba/senbot | SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/SynchronisationService.java | SynchronisationService.waitForExpectedCondition | public boolean waitForExpectedCondition(ExpectedCondition<?> condition, int timeout) {
WebDriver driver = getWebDriver();
boolean conditionMet = true;
try {
new WebDriverWait(driver, timeout).until(condition);
} catch (TimeoutException e) {
conditionMet = false;
}
return conditionMet;
} | java | public boolean waitForExpectedCondition(ExpectedCondition<?> condition, int timeout) {
WebDriver driver = getWebDriver();
boolean conditionMet = true;
try {
new WebDriverWait(driver, timeout).until(condition);
} catch (TimeoutException e) {
conditionMet = false;
}
return conditionMet;
} | [
"public",
"boolean",
"waitForExpectedCondition",
"(",
"ExpectedCondition",
"<",
"?",
">",
"condition",
",",
"int",
"timeout",
")",
"{",
"WebDriver",
"driver",
"=",
"getWebDriver",
"(",
")",
";",
"boolean",
"conditionMet",
"=",
"true",
";",
"try",
"{",
"new",
... | Waits until the expectations are full filled or timeout runs out
@param condition The conditions the element should meet
@param timeout The timeout to wait
@return True if element meets the condition | [
"Waits",
"until",
"the",
"expectations",
"are",
"full",
"filled",
"or",
"timeout",
"runs",
"out"
] | train | https://github.com/gfk-ba/senbot/blob/e9a152aa67be48b1bb13a4691655caf6d873b553/SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/SynchronisationService.java#L37-L46 |
primefaces/primefaces | src/main/java/org/primefaces/model/CheckboxTreeNodeChildren.java | CheckboxTreeNodeChildren.setSibling | @Override
public TreeNode setSibling(int index, TreeNode node) {
if (node == null) {
throw new NullPointerException();
}
else if ((index < 0) || (index >= size())) {
throw new IndexOutOfBoundsException();
}
else {
if (!parent.equals(node.getParent())) {
eraseParent(node);
}
TreeNode previous = get(index);
super.set(index, node);
node.setParent(parent);
updateRowKeys(parent);
updateSelectionState(parent);
return previous;
}
} | java | @Override
public TreeNode setSibling(int index, TreeNode node) {
if (node == null) {
throw new NullPointerException();
}
else if ((index < 0) || (index >= size())) {
throw new IndexOutOfBoundsException();
}
else {
if (!parent.equals(node.getParent())) {
eraseParent(node);
}
TreeNode previous = get(index);
super.set(index, node);
node.setParent(parent);
updateRowKeys(parent);
updateSelectionState(parent);
return previous;
}
} | [
"@",
"Override",
"public",
"TreeNode",
"setSibling",
"(",
"int",
"index",
",",
"TreeNode",
"node",
")",
"{",
"if",
"(",
"node",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
")",
";",
"}",
"else",
"if",
"(",
"(",
"index",
"<",
... | Optimized set implementation to be used in sorting
@param index index of the element to replace
@param node node to be stored at the specified position
@return the node previously at the specified position | [
"Optimized",
"set",
"implementation",
"to",
"be",
"used",
"in",
"sorting"
] | train | https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/model/CheckboxTreeNodeChildren.java#L160-L180 |
lightblueseas/vintage-time | src/main/java/de/alpharogroup/date/ParseDateExtensions.java | ParseDateExtensions.parseToString | public static String parseToString(final Date date, final String format)
{
return parseToString(date, format, Locale.getDefault(Locale.Category.FORMAT));
} | java | public static String parseToString(final Date date, final String format)
{
return parseToString(date, format, Locale.getDefault(Locale.Category.FORMAT));
} | [
"public",
"static",
"String",
"parseToString",
"(",
"final",
"Date",
"date",
",",
"final",
"String",
"format",
")",
"{",
"return",
"parseToString",
"(",
"date",
",",
"format",
",",
"Locale",
".",
"getDefault",
"(",
"Locale",
".",
"Category",
".",
"FORMAT",
... | The Method parseToString(Date, String) formats the given Date to the given Format. For
Example: Date date =new Date(System.currentTimeMillis()); String format = "dd.MM.yyyy
HH:mm:ss"; String now = UtilDate.parseToString(date, format); System.out.println(now); The
output would be something like this:'15.07.2005 14:12:00'
@param date
The Date to format to a String
@param format
The Format for the date
@return The formated String | [
"The",
"Method",
"parseToString",
"(",
"Date",
"String",
")",
"formats",
"the",
"given",
"Date",
"to",
"the",
"given",
"Format",
".",
"For",
"Example",
":",
"Date",
"date",
"=",
"new",
"Date",
"(",
"System",
".",
"currentTimeMillis",
"()",
")",
";",
"Str... | train | https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/ParseDateExtensions.java#L164-L167 |
reactiverse/reactive-pg-client | src/main/java/io/reactiverse/pgclient/impl/codec/DataTypeCodec.java | DataTypeCodec.decodeDecStringToLong | private static long decodeDecStringToLong(int index, int len, ByteBuf buff) {
long value = 0;
if (len > 0) {
int to = index + len;
boolean neg = false;
if (buff.getByte(index) == '-') {
neg = true;
index++;
}
while (index < to) {
byte ch = buff.getByte(index++);
byte nibble = (byte)(ch - '0');
value = value * 10 + nibble;
}
if (neg) {
value = -value;
}
}
return value;
} | java | private static long decodeDecStringToLong(int index, int len, ByteBuf buff) {
long value = 0;
if (len > 0) {
int to = index + len;
boolean neg = false;
if (buff.getByte(index) == '-') {
neg = true;
index++;
}
while (index < to) {
byte ch = buff.getByte(index++);
byte nibble = (byte)(ch - '0');
value = value * 10 + nibble;
}
if (neg) {
value = -value;
}
}
return value;
} | [
"private",
"static",
"long",
"decodeDecStringToLong",
"(",
"int",
"index",
",",
"int",
"len",
",",
"ByteBuf",
"buff",
")",
"{",
"long",
"value",
"=",
"0",
";",
"if",
"(",
"len",
">",
"0",
")",
"{",
"int",
"to",
"=",
"index",
"+",
"len",
";",
"boole... | Decode the specified {@code buff} formatted as a decimal string starting at the readable index
with the specified {@code length} to a long.
@param index the hex string index
@param len the hex string length
@param buff the byte buff to read from
@return the decoded value as a long | [
"Decode",
"the",
"specified",
"{",
"@code",
"buff",
"}",
"formatted",
"as",
"a",
"decimal",
"string",
"starting",
"at",
"the",
"readable",
"index",
"with",
"the",
"specified",
"{",
"@code",
"length",
"}",
"to",
"a",
"long",
"."
] | train | https://github.com/reactiverse/reactive-pg-client/blob/be75cc5462f0945f81d325f58db5f297403067bf/src/main/java/io/reactiverse/pgclient/impl/codec/DataTypeCodec.java#L1246-L1265 |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/interestrate/HullWhiteModel.java | HullWhiteModel.getMRTime | private double getMRTime(double time, double maturity) {
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-1; // Get timeIndex corresponding to next point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
double integral = 0.0;
double timePrev = time;
double timeNext;
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
double meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
integral += meanReversion*(timeNext-timePrev);
timePrev = timeNext;
}
timeNext = maturity;
double meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
integral += meanReversion*(timeNext-timePrev);
return integral;
} | java | private double getMRTime(double time, double maturity) {
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-1; // Get timeIndex corresponding to next point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
double integral = 0.0;
double timePrev = time;
double timeNext;
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
double meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
integral += meanReversion*(timeNext-timePrev);
timePrev = timeNext;
}
timeNext = maturity;
double meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
integral += meanReversion*(timeNext-timePrev);
return integral;
} | [
"private",
"double",
"getMRTime",
"(",
"double",
"time",
",",
"double",
"maturity",
")",
"{",
"int",
"timeIndexStart",
"=",
"volatilityModel",
".",
"getTimeDiscretization",
"(",
")",
".",
"getTimeIndex",
"(",
"time",
")",
";",
"if",
"(",
"timeIndexStart",
"<",... | Calculates \( \int_{t}^{T} a(s) \mathrm{d}s \), where \( a \) is the mean reversion parameter.
@param time The parameter t.
@param maturity The parameter T.
@return The value of \( \int_{t}^{T} a(s) \mathrm{d}s \). | [
"Calculates",
"\\",
"(",
"\\",
"int_",
"{",
"t",
"}",
"^",
"{",
"T",
"}",
"a",
"(",
"s",
")",
"\\",
"mathrm",
"{",
"d",
"}",
"s",
"\\",
")",
"where",
"\\",
"(",
"a",
"\\",
")",
"is",
"the",
"mean",
"reversion",
"parameter",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/HullWhiteModel.java#L406-L431 |
nostra13/Android-Universal-Image-Loader | library/src/main/java/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java | BaseImageDownloader.getStreamFromFile | protected InputStream getStreamFromFile(String imageUri, Object extra) throws IOException {
String filePath = Scheme.FILE.crop(imageUri);
if (isVideoFileUri(imageUri)) {
return getVideoThumbnailStream(filePath);
} else {
BufferedInputStream imageStream = new BufferedInputStream(new FileInputStream(filePath), BUFFER_SIZE);
return new ContentLengthInputStream(imageStream, (int) new File(filePath).length());
}
} | java | protected InputStream getStreamFromFile(String imageUri, Object extra) throws IOException {
String filePath = Scheme.FILE.crop(imageUri);
if (isVideoFileUri(imageUri)) {
return getVideoThumbnailStream(filePath);
} else {
BufferedInputStream imageStream = new BufferedInputStream(new FileInputStream(filePath), BUFFER_SIZE);
return new ContentLengthInputStream(imageStream, (int) new File(filePath).length());
}
} | [
"protected",
"InputStream",
"getStreamFromFile",
"(",
"String",
"imageUri",
",",
"Object",
"extra",
")",
"throws",
"IOException",
"{",
"String",
"filePath",
"=",
"Scheme",
".",
"FILE",
".",
"crop",
"(",
"imageUri",
")",
";",
"if",
"(",
"isVideoFileUri",
"(",
... | Retrieves {@link InputStream} of image by URI (image is located on the local file system or SD card).
@param imageUri Image URI
@param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
DisplayImageOptions.extraForDownloader(Object)}; can be null
@return {@link InputStream} of image
@throws IOException if some I/O error occurs reading from file system | [
"Retrieves",
"{",
"@link",
"InputStream",
"}",
"of",
"image",
"by",
"URI",
"(",
"image",
"is",
"located",
"on",
"the",
"local",
"file",
"system",
"or",
"SD",
"card",
")",
"."
] | train | https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java#L175-L183 |
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/SyncMembersInner.java | SyncMembersInner.listMemberSchemasWithServiceResponseAsync | public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> listMemberSchemasWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName, final String syncGroupName, final String syncMemberName) {
return listMemberSchemasSinglePageAsync(resourceGroupName, serverName, databaseName, syncGroupName, syncMemberName)
.concatMap(new Func1<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>, Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> call(ServiceResponse<Page<SyncFullSchemaPropertiesInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMemberSchemasNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> listMemberSchemasWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName, final String syncGroupName, final String syncMemberName) {
return listMemberSchemasSinglePageAsync(resourceGroupName, serverName, databaseName, syncGroupName, syncMemberName)
.concatMap(new Func1<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>, Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> call(ServiceResponse<Page<SyncFullSchemaPropertiesInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMemberSchemasNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SyncFullSchemaPropertiesInner",
">",
">",
">",
"listMemberSchemasWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
",",
"final",
"String",
"dat... | Gets a sync member database schema.
@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 on which the sync group is hosted.
@param syncGroupName The name of the sync group on which the sync member is hosted.
@param syncMemberName The name of the sync member.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SyncFullSchemaPropertiesInner> object | [
"Gets",
"a",
"sync",
"member",
"database",
"schema",
"."
] | 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/SyncMembersInner.java#L1071-L1083 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java | Collator.getFunctionalEquivalent | public static final ULocale getFunctionalEquivalent(String keyword,
ULocale locID,
boolean isAvailable[]) {
return ICUResourceBundle.getFunctionalEquivalent(BASE, ICUResourceBundle.ICU_DATA_CLASS_LOADER, RESOURCE,
keyword, locID, isAvailable, true);
} | java | public static final ULocale getFunctionalEquivalent(String keyword,
ULocale locID,
boolean isAvailable[]) {
return ICUResourceBundle.getFunctionalEquivalent(BASE, ICUResourceBundle.ICU_DATA_CLASS_LOADER, RESOURCE,
keyword, locID, isAvailable, true);
} | [
"public",
"static",
"final",
"ULocale",
"getFunctionalEquivalent",
"(",
"String",
"keyword",
",",
"ULocale",
"locID",
",",
"boolean",
"isAvailable",
"[",
"]",
")",
"{",
"return",
"ICUResourceBundle",
".",
"getFunctionalEquivalent",
"(",
"BASE",
",",
"ICUResourceBund... | <strong>[icu]</strong> Returns the functionally equivalent locale for the given
requested locale, with respect to given keyword, for the
collation service. If two locales return the same result, then
collators instantiated for these locales will behave
equivalently. The converse is not always true; two collators
may in fact be equivalent, but return different results, due to
internal details. The return result has no other meaning than
that stated above, and implies nothing as to the relationship
between the two locales. This is intended for use by
applications who wish to cache collators, or otherwise reuse
collators when possible. The functional equivalent may change
over time. For more information, please see the <a
href="http://userguide.icu-project.org/locale#TOC-Locales-and-Services">
Locales and Services</a> section of the ICU User Guide.
@param keyword a particular keyword as enumerated by
getKeywords.
@param locID The requested locale
@param isAvailable If non-null, isAvailable[0] will receive and
output boolean that indicates whether the requested locale was
'available' to the collation service. If non-null, isAvailable
must have length >= 1.
@return the locale | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"the",
"functionally",
"equivalent",
"locale",
"for",
"the",
"given",
"requested",
"locale",
"with",
"respect",
"to",
"given",
"keyword",
"for",
"the",
"collation",
"service",
".",
"If",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java#L1031-L1036 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java | CmsDefaultXmlContentHandler.initPreview | protected void initPreview(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
String preview = root.attributeValue(APPINFO_ATTR_URI);
if (preview == null) {
throw new CmsXmlException(
Messages.get().container(
Messages.ERR_XMLCONTENT_MISSING_PREVIEW_URI_2,
root.getName(),
contentDefinition.getSchemaLocation()));
}
m_previewLocation = preview;
} | java | protected void initPreview(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
String preview = root.attributeValue(APPINFO_ATTR_URI);
if (preview == null) {
throw new CmsXmlException(
Messages.get().container(
Messages.ERR_XMLCONTENT_MISSING_PREVIEW_URI_2,
root.getName(),
contentDefinition.getSchemaLocation()));
}
m_previewLocation = preview;
} | [
"protected",
"void",
"initPreview",
"(",
"Element",
"root",
",",
"CmsXmlContentDefinition",
"contentDefinition",
")",
"throws",
"CmsXmlException",
"{",
"String",
"preview",
"=",
"root",
".",
"attributeValue",
"(",
"APPINFO_ATTR_URI",
")",
";",
"if",
"(",
"preview",
... | Initializes the preview location for this content handler.<p>
@param root the "preview" element from the appinfo node of the XML content definition
@param contentDefinition the content definition the validation rules belong to
@throws CmsXmlException if something goes wrong | [
"Initializes",
"the",
"preview",
"location",
"for",
"this",
"content",
"handler",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2817-L2828 |
GoogleCloudPlatform/google-cloud-datastore | java/datastore/src/main/java/com/google/datastore/v1/client/QuerySplitterImpl.java | QuerySplitterImpl.createSplit | private Query createSplit(Key lastKey, Key nextKey, Query query) {
if (lastKey == null && nextKey == null) {
return query;
}
List<Filter> keyFilters = new ArrayList<Filter>();
if (query.hasFilter()) {
keyFilters.add(query.getFilter());
}
if (lastKey != null) {
Filter lowerBound = DatastoreHelper.makeFilter(DatastoreHelper.KEY_PROPERTY_NAME,
PropertyFilter.Operator.GREATER_THAN_OR_EQUAL,
DatastoreHelper.makeValue(lastKey)).build();
keyFilters.add(lowerBound);
}
if (nextKey != null) {
Filter upperBound = DatastoreHelper.makeFilter(DatastoreHelper.KEY_PROPERTY_NAME,
PropertyFilter.Operator.LESS_THAN,
DatastoreHelper.makeValue(nextKey)).build();
keyFilters.add(upperBound);
}
return Query.newBuilder(query).setFilter(makeAndFilter(keyFilters)).build();
} | java | private Query createSplit(Key lastKey, Key nextKey, Query query) {
if (lastKey == null && nextKey == null) {
return query;
}
List<Filter> keyFilters = new ArrayList<Filter>();
if (query.hasFilter()) {
keyFilters.add(query.getFilter());
}
if (lastKey != null) {
Filter lowerBound = DatastoreHelper.makeFilter(DatastoreHelper.KEY_PROPERTY_NAME,
PropertyFilter.Operator.GREATER_THAN_OR_EQUAL,
DatastoreHelper.makeValue(lastKey)).build();
keyFilters.add(lowerBound);
}
if (nextKey != null) {
Filter upperBound = DatastoreHelper.makeFilter(DatastoreHelper.KEY_PROPERTY_NAME,
PropertyFilter.Operator.LESS_THAN,
DatastoreHelper.makeValue(nextKey)).build();
keyFilters.add(upperBound);
}
return Query.newBuilder(query).setFilter(makeAndFilter(keyFilters)).build();
} | [
"private",
"Query",
"createSplit",
"(",
"Key",
"lastKey",
",",
"Key",
"nextKey",
",",
"Query",
"query",
")",
"{",
"if",
"(",
"lastKey",
"==",
"null",
"&&",
"nextKey",
"==",
"null",
")",
"{",
"return",
"query",
";",
"}",
"List",
"<",
"Filter",
">",
"k... | Create a new {@link Query} given the query and range.
@param lastKey the previous key. If null then assumed to be the beginning.
@param nextKey the next key. If null then assumed to be the end.
@param query the desired query. | [
"Create",
"a",
"new",
"{",
"@link",
"Query",
"}",
"given",
"the",
"query",
"and",
"range",
"."
] | train | https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/java/datastore/src/main/java/com/google/datastore/v1/client/QuerySplitterImpl.java#L142-L163 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBaseGridScreen.java | XBaseGridScreen.printHeadingFootingControls | public boolean printHeadingFootingControls(PrintWriter out, int iPrintOptions)
{
boolean bIsBreak = false;
int iNumCols = ((BasePanel)this.getScreenField()).getSFieldCount();
for (int iIndex = 0; iIndex < iNumCols; iIndex++)
{
ScreenField sField = ((BasePanel)this.getScreenField()).getSField(iIndex);
boolean bPrintControl = this.getScreenField().isPrintableControl(sField, iPrintOptions);
if (!(sField instanceof ReportBreakScreen))
bPrintControl = false;
if (bPrintControl)
sField.printControl(out, iPrintOptions);
}
return bIsBreak;
} | java | public boolean printHeadingFootingControls(PrintWriter out, int iPrintOptions)
{
boolean bIsBreak = false;
int iNumCols = ((BasePanel)this.getScreenField()).getSFieldCount();
for (int iIndex = 0; iIndex < iNumCols; iIndex++)
{
ScreenField sField = ((BasePanel)this.getScreenField()).getSField(iIndex);
boolean bPrintControl = this.getScreenField().isPrintableControl(sField, iPrintOptions);
if (!(sField instanceof ReportBreakScreen))
bPrintControl = false;
if (bPrintControl)
sField.printControl(out, iPrintOptions);
}
return bIsBreak;
} | [
"public",
"boolean",
"printHeadingFootingControls",
"(",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"boolean",
"bIsBreak",
"=",
"false",
";",
"int",
"iNumCols",
"=",
"(",
"(",
"BasePanel",
")",
"this",
".",
"getScreenField",
"(",
")",
")",
... | Display this screen in html input format.
@return true if default params were found for this form.
@param out The http output stream.
@return True if a heading or footing exists.
@exception DBException File exception. | [
"Display",
"this",
"screen",
"in",
"html",
"input",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBaseGridScreen.java#L237-L251 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java | SheetRenderer.decodeSubmittedValues | private void decodeSubmittedValues(final FacesContext context, final Sheet sheet, final String jsonData) {
if (LangUtils.isValueBlank(jsonData)) {
return;
}
try {
// data comes in as a JSON Object with named properties for the row and columns
// updated this is so that
// multiple updates to the same cell overwrite previous deltas prior to
// submission we don't care about
// the property names, just the values, which we'll process in turn
final JSONObject obj = new JSONObject(jsonData);
final Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
final String key = keys.next();
// data comes in: [row, col, oldValue, newValue, rowKey]
final JSONArray update = obj.getJSONArray(key);
// GitHub #586 pasted more values than rows
if (update.isNull(4)) {
continue;
}
final String rowKey = update.getString(4);
final int col = sheet.getMappedColumn(update.getInt(1));
final String newValue = String.valueOf(update.get(3));
sheet.setSubmittedValue(context, rowKey, col, newValue);
}
}
catch (final JSONException ex) {
throw new FacesException("Failed parsing Ajax JSON message for cell change event:" + ex.getMessage(), ex);
}
} | java | private void decodeSubmittedValues(final FacesContext context, final Sheet sheet, final String jsonData) {
if (LangUtils.isValueBlank(jsonData)) {
return;
}
try {
// data comes in as a JSON Object with named properties for the row and columns
// updated this is so that
// multiple updates to the same cell overwrite previous deltas prior to
// submission we don't care about
// the property names, just the values, which we'll process in turn
final JSONObject obj = new JSONObject(jsonData);
final Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
final String key = keys.next();
// data comes in: [row, col, oldValue, newValue, rowKey]
final JSONArray update = obj.getJSONArray(key);
// GitHub #586 pasted more values than rows
if (update.isNull(4)) {
continue;
}
final String rowKey = update.getString(4);
final int col = sheet.getMappedColumn(update.getInt(1));
final String newValue = String.valueOf(update.get(3));
sheet.setSubmittedValue(context, rowKey, col, newValue);
}
}
catch (final JSONException ex) {
throw new FacesException("Failed parsing Ajax JSON message for cell change event:" + ex.getMessage(), ex);
}
} | [
"private",
"void",
"decodeSubmittedValues",
"(",
"final",
"FacesContext",
"context",
",",
"final",
"Sheet",
"sheet",
",",
"final",
"String",
"jsonData",
")",
"{",
"if",
"(",
"LangUtils",
".",
"isValueBlank",
"(",
"jsonData",
")",
")",
"{",
"return",
";",
"}"... | Converts the JSON data received from the in the request params into our sumitted values map. The map is cleared first.
@param jsonData the submitted JSON data
@param sheet
@param jsonData | [
"Converts",
"the",
"JSON",
"data",
"received",
"from",
"the",
"in",
"the",
"request",
"params",
"into",
"our",
"sumitted",
"values",
"map",
".",
"The",
"map",
"is",
"cleared",
"first",
"."
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L961-L991 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/scanner/VariantAbstractQuery.java | VariantAbstractQuery.paramAppend | private boolean paramAppend(StringBuilder sb, String name, String value, ParameterParser parser) {
boolean isEdited = false;
if (name != null) {
sb.append(name);
isEdited = true;
}
if (value != null) {
sb.append(parser.getDefaultKeyValueSeparator());
sb.append(value);
isEdited = true;
}
return isEdited;
} | java | private boolean paramAppend(StringBuilder sb, String name, String value, ParameterParser parser) {
boolean isEdited = false;
if (name != null) {
sb.append(name);
isEdited = true;
}
if (value != null) {
sb.append(parser.getDefaultKeyValueSeparator());
sb.append(value);
isEdited = true;
}
return isEdited;
} | [
"private",
"boolean",
"paramAppend",
"(",
"StringBuilder",
"sb",
",",
"String",
"name",
",",
"String",
"value",
",",
"ParameterParser",
"parser",
")",
"{",
"boolean",
"isEdited",
"=",
"false",
";",
"if",
"(",
"name",
"!=",
"null",
")",
"{",
"sb",
".",
"a... | Set the name value pair into the StringBuilder. If both name and value is
null, not to append whole parameter.
@param sb
@param name Null = not to append parameter.
@param value null = not to append parameter value.
@return true = parameter changed. | [
"Set",
"the",
"name",
"value",
"pair",
"into",
"the",
"StringBuilder",
".",
"If",
"both",
"name",
"and",
"value",
"is",
"null",
"not",
"to",
"append",
"whole",
"parameter",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/VariantAbstractQuery.java#L246-L261 |
UrielCh/ovh-java-sdk | ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java | ApiOvhMsServices.serviceName_sync_license_GET | public ArrayList<OvhSyncDailyLicense> serviceName_sync_license_GET(String serviceName, OvhSyncLicenseEnum license, OvhLicensePeriodEnum period) throws IOException {
String qPath = "/msServices/{serviceName}/sync/license";
StringBuilder sb = path(qPath, serviceName);
query(sb, "license", license);
query(sb, "period", period);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | java | public ArrayList<OvhSyncDailyLicense> serviceName_sync_license_GET(String serviceName, OvhSyncLicenseEnum license, OvhLicensePeriodEnum period) throws IOException {
String qPath = "/msServices/{serviceName}/sync/license";
StringBuilder sb = path(qPath, serviceName);
query(sb, "license", license);
query(sb, "period", period);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | [
"public",
"ArrayList",
"<",
"OvhSyncDailyLicense",
">",
"serviceName_sync_license_GET",
"(",
"String",
"serviceName",
",",
"OvhSyncLicenseEnum",
"license",
",",
"OvhLicensePeriodEnum",
"period",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/msServices/{se... | Get active licenses for specific period of time
REST: GET /msServices/{serviceName}/sync/license
@param period [required] Period of time used to determine sync account license statistics
@param license [required] License type
@param serviceName [required] The internal name of your Active Directory organization
API beta | [
"Get",
"active",
"licenses",
"for",
"specific",
"period",
"of",
"time"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java#L767-L774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.