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 |
|---|---|---|---|---|---|---|---|---|---|---|
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/core/DoradusServer.java | DoradusServer.initConfig | private void initConfig(String[] args) {
try {
ServerParams.load(args);
if (Utils.isEmpty(ServerParams.instance().getModuleParamString("DoradusServer", "super_user"))) {
m_logger.warn("'DoradusServer.super_user' parameter is not defined. " +
"Privileged commands will be available without authentication.");
}
} catch (ConfigurationException e) {
throw new RuntimeException("Failed to initialize server configuration", e);
}
} | java | private void initConfig(String[] args) {
try {
ServerParams.load(args);
if (Utils.isEmpty(ServerParams.instance().getModuleParamString("DoradusServer", "super_user"))) {
m_logger.warn("'DoradusServer.super_user' parameter is not defined. " +
"Privileged commands will be available without authentication.");
}
} catch (ConfigurationException e) {
throw new RuntimeException("Failed to initialize server configuration", e);
}
} | [
"private",
"void",
"initConfig",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"ServerParams",
".",
"load",
"(",
"args",
")",
";",
"if",
"(",
"Utils",
".",
"isEmpty",
"(",
"ServerParams",
".",
"instance",
"(",
")",
".",
"getModuleParamString",
... | Initialize the ServerParams module, which loads the doradus.yaml file. | [
"Initialize",
"the",
"ServerParams",
"module",
"which",
"loads",
"the",
"doradus",
".",
"yaml",
"file",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/DoradusServer.java#L350-L360 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java | JobsInner.getRunbookContent | public InputStream getRunbookContent(String resourceGroupName, String automationAccountName, String jobId) {
return getRunbookContentWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body();
} | java | public InputStream getRunbookContent(String resourceGroupName, String automationAccountName, String jobId) {
return getRunbookContentWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body();
} | [
"public",
"InputStream",
"getRunbookContent",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"jobId",
")",
"{",
"return",
"getRunbookContentWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"j... | Retrieve the runbook content of the job identified by job id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param jobId The job id.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the InputStream object if successful. | [
"Retrieve",
"the",
"runbook",
"content",
"of",
"the",
"job",
"identified",
"by",
"job",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java#L210-L212 |
agmip/agmip-common-functions | src/main/java/org/agmip/functions/PTSaxton2006.java | PTSaxton2006.calcMoisture1500Kpa | public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) {
if ((slsnd = checkPctVal(slsnd)) == null
|| (slcly = checkPctVal(slcly)) == null
|| (omPct = checkPctVal(omPct)) == null) {
LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v");
return null;
}
String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct),
product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534");
LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret);
return ret;
} | java | public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) {
if ((slsnd = checkPctVal(slsnd)) == null
|| (slcly = checkPctVal(slcly)) == null
|| (omPct = checkPctVal(omPct)) == null) {
LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v");
return null;
}
String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct),
product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534");
LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret);
return ret;
} | [
"public",
"static",
"String",
"calcMoisture1500Kpa",
"(",
"String",
"slsnd",
",",
"String",
"slcly",
",",
"String",
"omPct",
")",
"{",
"if",
"(",
"(",
"slsnd",
"=",
"checkPctVal",
"(",
"slsnd",
")",
")",
"==",
"null",
"||",
"(",
"slcly",
"=",
"checkPctVa... | Equation 1 for calculating 1500 kPa moisture, %v
@param slsnd Sand weight percentage by layer ([0,100]%)
@param slcly Clay weight percentage by layer ([0,100]%)
@param omPct Organic matter weight percentage by layer ([0,100]%), (=
SLOC * 1.72) | [
"Equation",
"1",
"for",
"calculating",
"1500",
"kPa",
"moisture",
"%v"
] | train | https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L121-L134 |
mgormley/optimize | src/main/java/edu/jhu/hlt/optimize/function/AbstractSumBatchFunction.java | AbstractSumBatchFunction.getGradient | public void getGradient(int[] batch, double[] gradient) {
for (int i=0; i<batch.length; i++) {
addGradient(i, gradient);
}
} | java | public void getGradient(int[] batch, double[] gradient) {
for (int i=0; i<batch.length; i++) {
addGradient(i, gradient);
}
} | [
"public",
"void",
"getGradient",
"(",
"int",
"[",
"]",
"batch",
",",
"double",
"[",
"]",
"gradient",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"batch",
".",
"length",
";",
"i",
"++",
")",
"{",
"addGradient",
"(",
"i",
",",
"gra... | Gets the gradient at the current point, computed on the given batch of examples.
@param batch A set of indices indicating the examples over which the gradient should be computed.
@param gradient The output gradient, a vector of partial derivatives. | [
"Gets",
"the",
"gradient",
"at",
"the",
"current",
"point",
"computed",
"on",
"the",
"given",
"batch",
"of",
"examples",
"."
] | train | https://github.com/mgormley/optimize/blob/3d1b93260b99febb8a5ecd9e8543c223e151a8d3/src/main/java/edu/jhu/hlt/optimize/function/AbstractSumBatchFunction.java#L33-L37 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java | MapUtils.getBoundingBox | public static BoundingBox getBoundingBox(GoogleMap map) {
LatLngBounds visibleBounds = map.getProjection()
.getVisibleRegion().latLngBounds;
LatLng southwest = visibleBounds.southwest;
LatLng northeast = visibleBounds.northeast;
double minLatitude = southwest.latitude;
double maxLatitude = northeast.latitude;
double minLongitude = southwest.longitude;
double maxLongitude = northeast.longitude;
if (maxLongitude < minLongitude) {
maxLongitude += (2 * ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH);
}
BoundingBox boundingBox = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude);
return boundingBox;
} | java | public static BoundingBox getBoundingBox(GoogleMap map) {
LatLngBounds visibleBounds = map.getProjection()
.getVisibleRegion().latLngBounds;
LatLng southwest = visibleBounds.southwest;
LatLng northeast = visibleBounds.northeast;
double minLatitude = southwest.latitude;
double maxLatitude = northeast.latitude;
double minLongitude = southwest.longitude;
double maxLongitude = northeast.longitude;
if (maxLongitude < minLongitude) {
maxLongitude += (2 * ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH);
}
BoundingBox boundingBox = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude);
return boundingBox;
} | [
"public",
"static",
"BoundingBox",
"getBoundingBox",
"(",
"GoogleMap",
"map",
")",
"{",
"LatLngBounds",
"visibleBounds",
"=",
"map",
".",
"getProjection",
"(",
")",
".",
"getVisibleRegion",
"(",
")",
".",
"latLngBounds",
";",
"LatLng",
"southwest",
"=",
"visible... | Get the WGS84 bounding box of the current map view screen.
The max longitude will be larger than the min resulting in values larger than 180.0.
@param map google map
@return current bounding box | [
"Get",
"the",
"WGS84",
"bounding",
"box",
"of",
"the",
"current",
"map",
"view",
"screen",
".",
"The",
"max",
"longitude",
"will",
"be",
"larger",
"than",
"the",
"min",
"resulting",
"in",
"values",
"larger",
"than",
"180",
".",
"0",
"."
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L81-L100 |
VoltDB/voltdb | src/frontend/org/voltdb/ClientInterface.java | ClientInterface.callExecuteTaskAsync | public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
final String procedureName = "@ExecuteTask";
Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
Procedure proc = procedureConfig.asCatalogProcedure();
StoredProcedureInvocation spi = new StoredProcedureInvocation();
spi.setProcName(procedureName);
spi.setParams(params);
spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
if (spi.getSerializedParams() == null) {
spi = MiscUtils.roundTripForCL(spi);
}
synchronized (m_executeTaskAdpater) {
m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
new int[] { 0 } /* Can provide anything for multi-part */,
spi.getSerializedSize(), System.nanoTime());
}
} | java | public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
final String procedureName = "@ExecuteTask";
Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
Procedure proc = procedureConfig.asCatalogProcedure();
StoredProcedureInvocation spi = new StoredProcedureInvocation();
spi.setProcName(procedureName);
spi.setParams(params);
spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
if (spi.getSerializedParams() == null) {
spi = MiscUtils.roundTripForCL(spi);
}
synchronized (m_executeTaskAdpater) {
m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
new int[] { 0 } /* Can provide anything for multi-part */,
spi.getSerializedSize(), System.nanoTime());
}
} | [
"public",
"void",
"callExecuteTaskAsync",
"(",
"SimpleClientResponseAdapter",
".",
"Callback",
"cb",
",",
"byte",
"[",
"]",
"params",
")",
"throws",
"IOException",
"{",
"final",
"String",
"procedureName",
"=",
"\"@ExecuteTask\"",
";",
"Config",
"procedureConfig",
"=... | Asynchronous version, call @ExecuteTask to generate a MP transaction.
@param cb maximum timeout in milliseconds
@param params actual parameter(s) for sub task to run
@return
@throws IOException
@throws InterruptedException | [
"Asynchronous",
"version",
"call",
"@ExecuteTask",
"to",
"generate",
"a",
"MP",
"transaction",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ClientInterface.java#L2091-L2108 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnDeriveBNTensorDescriptor | public static int cudnnDeriveBNTensorDescriptor(
cudnnTensorDescriptor derivedBnDesc,
cudnnTensorDescriptor xDesc,
int mode)
{
return checkResult(cudnnDeriveBNTensorDescriptorNative(derivedBnDesc, xDesc, mode));
} | java | public static int cudnnDeriveBNTensorDescriptor(
cudnnTensorDescriptor derivedBnDesc,
cudnnTensorDescriptor xDesc,
int mode)
{
return checkResult(cudnnDeriveBNTensorDescriptorNative(derivedBnDesc, xDesc, mode));
} | [
"public",
"static",
"int",
"cudnnDeriveBNTensorDescriptor",
"(",
"cudnnTensorDescriptor",
"derivedBnDesc",
",",
"cudnnTensorDescriptor",
"xDesc",
",",
"int",
"mode",
")",
"{",
"return",
"checkResult",
"(",
"cudnnDeriveBNTensorDescriptorNative",
"(",
"derivedBnDesc",
",",
... | <pre>
Derives a tensor descriptor from layer data descriptor for BatchNormalization
scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for
bnScaleBiasMeanVarDesc and bnScaleBiasDiffDesc in Batch Normalization forward and backward functions.
</pre> | [
"<pre",
">",
"Derives",
"a",
"tensor",
"descriptor",
"from",
"layer",
"data",
"descriptor",
"for",
"BatchNormalization",
"scale",
"invVariance",
"bnBias",
"bnScale",
"tensors",
".",
"Use",
"this",
"tensor",
"desc",
"for",
"bnScaleBiasMeanVarDesc",
"and",
"bnScaleBia... | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2187-L2193 |
nakamura5akihito/six-util | src/main/java/jp/go/aist/six/util/core/xml/spring327/AbstractMarshaller.java | AbstractMarshaller.marshalSaxResult | protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException {
ContentHandler contentHandler = saxResult.getHandler();
Assert.notNull(contentHandler, "ContentHandler not set on SAXResult");
LexicalHandler lexicalHandler = saxResult.getLexicalHandler();
marshalSaxHandlers(graph, contentHandler, lexicalHandler);
} | java | protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException {
ContentHandler contentHandler = saxResult.getHandler();
Assert.notNull(contentHandler, "ContentHandler not set on SAXResult");
LexicalHandler lexicalHandler = saxResult.getLexicalHandler();
marshalSaxHandlers(graph, contentHandler, lexicalHandler);
} | [
"protected",
"void",
"marshalSaxResult",
"(",
"Object",
"graph",
",",
"SAXResult",
"saxResult",
")",
"throws",
"XmlMappingException",
"{",
"ContentHandler",
"contentHandler",
"=",
"saxResult",
".",
"getHandler",
"(",
")",
";",
"Assert",
".",
"notNull",
"(",
"conte... | Template method for handling {@code SAXResult}s.
<p>This implementation delegates to {@code marshalSaxHandlers}.
@param graph the root of the object graph to marshal
@param saxResult the {@code SAXResult}
@throws XmlMappingException if the given object cannot be marshalled to the result
@see #marshalSaxHandlers(Object, org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler) | [
"Template",
"method",
"for",
"handling",
"{"
] | train | https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/xml/spring327/AbstractMarshaller.java#L247-L252 |
headius/invokebinder | src/main/java/com/headius/invokebinder/Signature.java | Signature.dropArg | public Signature dropArg(String name) {
String[] newArgNames = new String[argNames.length - 1];
MethodType newType = methodType;
for (int i = 0, j = 0; i < argNames.length; i++) {
if (argNames[i].equals(name)) {
newType = newType.dropParameterTypes(j, j + 1);
continue;
}
newArgNames[j++] = argNames[i];
}
if (newType == null) {
// arg name not found; should we error?
return this;
}
return new Signature(newType, newArgNames);
} | java | public Signature dropArg(String name) {
String[] newArgNames = new String[argNames.length - 1];
MethodType newType = methodType;
for (int i = 0, j = 0; i < argNames.length; i++) {
if (argNames[i].equals(name)) {
newType = newType.dropParameterTypes(j, j + 1);
continue;
}
newArgNames[j++] = argNames[i];
}
if (newType == null) {
// arg name not found; should we error?
return this;
}
return new Signature(newType, newArgNames);
} | [
"public",
"Signature",
"dropArg",
"(",
"String",
"name",
")",
"{",
"String",
"[",
"]",
"newArgNames",
"=",
"new",
"String",
"[",
"argNames",
".",
"length",
"-",
"1",
"]",
";",
"MethodType",
"newType",
"=",
"methodType",
";",
"for",
"(",
"int",
"i",
"="... | Drops the first argument with the given name.
@param name the name of the argument to drop
@return a new signature | [
"Drops",
"the",
"first",
"argument",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Signature.java#L308-L326 |
Stratio/stratio-connector-commons | connector-commons/src/main/java/com/stratio/connector/commons/connection/Connection.java | Connection.addObjectToSession | public void addObjectToSession(String name, Object value) {
if (session == null) {
session = new HashMap<>();
}
if (logger.isDebugEnabled()) {
logger.debug("Add object [" + name + "] to session with value [" + value + "]");
}
session.put(name, value);
} | java | public void addObjectToSession(String name, Object value) {
if (session == null) {
session = new HashMap<>();
}
if (logger.isDebugEnabled()) {
logger.debug("Add object [" + name + "] to session with value [" + value + "]");
}
session.put(name, value);
} | [
"public",
"void",
"addObjectToSession",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"session",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"}",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
... | Add a object into the session.
@param name the object name.
@param value the objecet value. | [
"Add",
"a",
"object",
"into",
"the",
"session",
"."
] | train | https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/connection/Connection.java#L80-L88 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/core/msg/MsgChecker.java | MsgChecker.checkPointListChild | public void checkPointListChild(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) {
ValidationData listParent = param.findListParent();
List list = (List) listParent.getValue(bodyObj);
if (list == null || list.isEmpty()) {
return;
}
list.stream().forEach(item -> {
this.checkPoint(param, rule, item, standardValue);
});
} | java | public void checkPointListChild(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) {
ValidationData listParent = param.findListParent();
List list = (List) listParent.getValue(bodyObj);
if (list == null || list.isEmpty()) {
return;
}
list.stream().forEach(item -> {
this.checkPoint(param, rule, item, standardValue);
});
} | [
"public",
"void",
"checkPointListChild",
"(",
"ValidationData",
"param",
",",
"ValidationRule",
"rule",
",",
"Object",
"bodyObj",
",",
"Object",
"standardValue",
")",
"{",
"ValidationData",
"listParent",
"=",
"param",
".",
"findListParent",
"(",
")",
";",
"List",
... | Check point list child.
@param param the param
@param rule the rule
@param bodyObj the body obj
@param standardValue the standard value | [
"Check",
"point",
"list",
"child",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/core/msg/MsgChecker.java#L86-L97 |
apache/fluo-recipes | modules/kryo/src/main/java/org/apache/fluo/recipes/kryo/KryoSimplerSerializer.java | KryoSimplerSerializer.setKryoFactory | public static void setKryoFactory(FluoConfiguration config, String factoryType) {
config.getAppConfiguration().setProperty(KRYO_FACTORY_PROP, factoryType);
} | java | public static void setKryoFactory(FluoConfiguration config, String factoryType) {
config.getAppConfiguration().setProperty(KRYO_FACTORY_PROP, factoryType);
} | [
"public",
"static",
"void",
"setKryoFactory",
"(",
"FluoConfiguration",
"config",
",",
"String",
"factoryType",
")",
"{",
"config",
".",
"getAppConfiguration",
"(",
")",
".",
"setProperty",
"(",
"KRYO_FACTORY_PROP",
",",
"factoryType",
")",
";",
"}"
] | Call this to configure a KryoFactory type before initializing Fluo. | [
"Call",
"this",
"to",
"configure",
"a",
"KryoFactory",
"type",
"before",
"initializing",
"Fluo",
"."
] | train | https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/kryo/src/main/java/org/apache/fluo/recipes/kryo/KryoSimplerSerializer.java#L117-L119 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/ValidateXMLInterceptor.java | ValidateXMLInterceptor.paintOriginalXML | private void paintOriginalXML(final String originalXML, final PrintWriter writer) {
// Replace any CDATA Sections embedded in XML
String xml = originalXML.replaceAll("<!\\[CDATA\\[", "CDATASTART");
xml = xml.replaceAll("\\]\\]>", "CDATAFINISH");
// Paint Output
writer.println("<div>");
writer.println("<!-- VALIDATE XML ERROR - START XML -->");
writer.println("<![CDATA[");
writer.println(xml);
writer.println("]]>");
writer.println("<!-- VALIDATE XML ERROR - END XML -->");
writer.println("</div>");
} | java | private void paintOriginalXML(final String originalXML, final PrintWriter writer) {
// Replace any CDATA Sections embedded in XML
String xml = originalXML.replaceAll("<!\\[CDATA\\[", "CDATASTART");
xml = xml.replaceAll("\\]\\]>", "CDATAFINISH");
// Paint Output
writer.println("<div>");
writer.println("<!-- VALIDATE XML ERROR - START XML -->");
writer.println("<![CDATA[");
writer.println(xml);
writer.println("]]>");
writer.println("<!-- VALIDATE XML ERROR - END XML -->");
writer.println("</div>");
} | [
"private",
"void",
"paintOriginalXML",
"(",
"final",
"String",
"originalXML",
",",
"final",
"PrintWriter",
"writer",
")",
"{",
"// Replace any CDATA Sections embedded in XML",
"String",
"xml",
"=",
"originalXML",
".",
"replaceAll",
"(",
"\"<!\\\\[CDATA\\\\[\"",
",",
"\"... | Paint the original XML wrapped in a CDATA Section.
@param originalXML the original XML
@param writer the output writer | [
"Paint",
"the",
"original",
"XML",
"wrapped",
"in",
"a",
"CDATA",
"Section",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/ValidateXMLInterceptor.java#L104-L117 |
chocoteam/choco-graph | src/main/java/org/chocosolver/graphsolver/util/BitOperations.java | BitOperations.binaryLCA | public static int binaryLCA(int x, int y) {
if (x == y) {
return x;
}
int xor = x ^ y;
int idx = getMaxExp(xor);
if (idx == -1) {
throw new UnsupportedOperationException();
}
return replaceBy1and0sFrom(x, idx);
} | java | public static int binaryLCA(int x, int y) {
if (x == y) {
return x;
}
int xor = x ^ y;
int idx = getMaxExp(xor);
if (idx == -1) {
throw new UnsupportedOperationException();
}
return replaceBy1and0sFrom(x, idx);
} | [
"public",
"static",
"int",
"binaryLCA",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"if",
"(",
"x",
"==",
"y",
")",
"{",
"return",
"x",
";",
"}",
"int",
"xor",
"=",
"x",
"^",
"y",
";",
"int",
"idx",
"=",
"getMaxExp",
"(",
"xor",
")",
";",
"... | Get the lowest common ancestor of x and y in a complete binary tree
@param x a node
@param y a node
@return the lowest common ancestor of x and y in a complete binary tree | [
"Get",
"the",
"lowest",
"common",
"ancestor",
"of",
"x",
"and",
"y",
"in",
"a",
"complete",
"binary",
"tree"
] | train | https://github.com/chocoteam/choco-graph/blob/0a03b0aafc86601977728c7e3fcb5ed376f1fae9/src/main/java/org/chocosolver/graphsolver/util/BitOperations.java#L52-L62 |
micronaut-projects/micronaut-core | core/src/main/java/io/micronaut/core/util/clhm/ConcurrentLinkedHashMap.java | ConcurrentLinkedHashMap.recordRead | long recordRead(int bufferIndex, Node<K, V> node) {
// The location in the buffer is chosen in a racy fashion as the increment
// is not atomic with the insertion. This means that concurrent reads can
// overlap and overwrite one another, resulting in a lossy buffer.
final AtomicLong counter = readBufferWriteCount[bufferIndex];
final long writeCount = counter.get();
counter.lazySet(writeCount + 1);
final int index = (int) (writeCount & READ_BUFFER_INDEX_MASK);
readBuffers[bufferIndex][index].lazySet(node);
return writeCount;
} | java | long recordRead(int bufferIndex, Node<K, V> node) {
// The location in the buffer is chosen in a racy fashion as the increment
// is not atomic with the insertion. This means that concurrent reads can
// overlap and overwrite one another, resulting in a lossy buffer.
final AtomicLong counter = readBufferWriteCount[bufferIndex];
final long writeCount = counter.get();
counter.lazySet(writeCount + 1);
final int index = (int) (writeCount & READ_BUFFER_INDEX_MASK);
readBuffers[bufferIndex][index].lazySet(node);
return writeCount;
} | [
"long",
"recordRead",
"(",
"int",
"bufferIndex",
",",
"Node",
"<",
"K",
",",
"V",
">",
"node",
")",
"{",
"// The location in the buffer is chosen in a racy fashion as the increment",
"// is not atomic with the insertion. This means that concurrent reads can",
"// overlap and overwr... | Records a read in the buffer and return its write count.
@param bufferIndex the index to the chosen read buffer
@param node the entry in the page replacement policy
@return the number of writes on the chosen read buffer | [
"Records",
"a",
"read",
"in",
"the",
"buffer",
"and",
"return",
"its",
"write",
"count",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/util/clhm/ConcurrentLinkedHashMap.java#L360-L372 |
voldemort/voldemort | src/java/voldemort/utils/PartitionBalanceUtils.java | PartitionBalanceUtils.compressedListOfPartitionsInZone | public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {
Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,
zoneId);
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());
for(int initPartitionId: sortedInitPartitionIds) {
if(!first) {
sb.append(", ");
} else {
first = false;
}
int runLength = idToRunLength.get(initPartitionId);
if(runLength == 1) {
sb.append(initPartitionId);
} else {
int endPartitionId = (initPartitionId + runLength - 1)
% cluster.getNumberOfPartitions();
sb.append(initPartitionId).append("-").append(endPartitionId);
}
}
sb.append("]");
return sb.toString();
} | java | public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {
Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,
zoneId);
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());
for(int initPartitionId: sortedInitPartitionIds) {
if(!first) {
sb.append(", ");
} else {
first = false;
}
int runLength = idToRunLength.get(initPartitionId);
if(runLength == 1) {
sb.append(initPartitionId);
} else {
int endPartitionId = (initPartitionId + runLength - 1)
% cluster.getNumberOfPartitions();
sb.append(initPartitionId).append("-").append(endPartitionId);
}
}
sb.append("]");
return sb.toString();
} | [
"public",
"static",
"String",
"compressedListOfPartitionsInZone",
"(",
"final",
"Cluster",
"cluster",
",",
"int",
"zoneId",
")",
"{",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"idToRunLength",
"=",
"PartitionBalanceUtils",
".",
"getMapOfContiguousPartitions",
"(",
... | Compress contiguous partitions into format "e-i" instead of
"e, f, g, h, i". This helps illustrate contiguous partitions within a
zone.
@param cluster
@param zoneId
@return pretty string of partitions per zone | [
"Compress",
"contiguous",
"partitions",
"into",
"format",
"e",
"-",
"i",
"instead",
"of",
"e",
"f",
"g",
"h",
"i",
".",
"This",
"helps",
"illustrate",
"contiguous",
"partitions",
"within",
"a",
"zone",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/PartitionBalanceUtils.java#L54-L81 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.classesNotConfigured | public static void classesNotConfigured(Class<?> destination,Class<?> source){
throw new MappingNotFoundException(MSG.INSTANCE.message(Constants.mappingNotFoundException2,destination.getSimpleName(), source.getSimpleName()));
} | java | public static void classesNotConfigured(Class<?> destination,Class<?> source){
throw new MappingNotFoundException(MSG.INSTANCE.message(Constants.mappingNotFoundException2,destination.getSimpleName(), source.getSimpleName()));
} | [
"public",
"static",
"void",
"classesNotConfigured",
"(",
"Class",
"<",
"?",
">",
"destination",
",",
"Class",
"<",
"?",
">",
"source",
")",
"{",
"throw",
"new",
"MappingNotFoundException",
"(",
"MSG",
".",
"INSTANCE",
".",
"message",
"(",
"Constants",
".",
... | Thrown when the xml configuration doesn't exist.
@param destination destination class name
@param source source class name | [
"Thrown",
"when",
"the",
"xml",
"configuration",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L530-L532 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/style/ColorUtils.java | ColorUtils.toColor | public static String toColor(String red, String green, String blue) {
return toColorWithAlpha(red, green, blue, null);
} | java | public static String toColor(String red, String green, String blue) {
return toColorWithAlpha(red, green, blue, null);
} | [
"public",
"static",
"String",
"toColor",
"(",
"String",
"red",
",",
"String",
"green",
",",
"String",
"blue",
")",
"{",
"return",
"toColorWithAlpha",
"(",
"red",
",",
"green",
",",
"blue",
",",
"null",
")",
";",
"}"
] | Convert the hex color values to a hex color
@param red
red hex color in format RR or R
@param green
green hex color in format GG or G
@param blue
blue hex color in format BB or B
@return hex color in format #RRGGBB | [
"Convert",
"the",
"hex",
"color",
"values",
"to",
"a",
"hex",
"color"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/style/ColorUtils.java#L40-L42 |
killbilling/recurly-java-library | src/main/java/com/ning/billing/recurly/RecurlyClient.java | RecurlyClient.getCoupon | public Coupon getCoupon(final String couponCode) {
if (couponCode == null || couponCode.isEmpty())
throw new RuntimeException("couponCode cannot be empty!");
return doGET(Coupon.COUPON_RESOURCE + "/" + couponCode, Coupon.class);
} | java | public Coupon getCoupon(final String couponCode) {
if (couponCode == null || couponCode.isEmpty())
throw new RuntimeException("couponCode cannot be empty!");
return doGET(Coupon.COUPON_RESOURCE + "/" + couponCode, Coupon.class);
} | [
"public",
"Coupon",
"getCoupon",
"(",
"final",
"String",
"couponCode",
")",
"{",
"if",
"(",
"couponCode",
"==",
"null",
"||",
"couponCode",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"couponCode cannot be empty!\"",
")",
";",
"re... | Get a Coupon
<p>
@param couponCode The code for the {@link Coupon}
@return The {@link Coupon} object as identified by the passed in code | [
"Get",
"a",
"Coupon",
"<p",
">"
] | train | https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1556-L1561 |
ManfredTremmel/gwt-bean-validators | mt-bean-validators/src/main/java/de/knightsoftnet/validators/server/data/CreateBicMapConstantsClass.java | CreateBicMapConstantsClass.create | public static BicMapSharedConstants create() {
if (bicMapConstants == null) { // NOPMD it's thread save!
synchronized (BicMapConstantsImpl.class) {
if (bicMapConstants == null) {
bicMapConstants =
new BicMapConstantsImpl(readMapFromProperties("BicMapConstants", "bics"));
}
}
}
return bicMapConstants;
} | java | public static BicMapSharedConstants create() {
if (bicMapConstants == null) { // NOPMD it's thread save!
synchronized (BicMapConstantsImpl.class) {
if (bicMapConstants == null) {
bicMapConstants =
new BicMapConstantsImpl(readMapFromProperties("BicMapConstants", "bics"));
}
}
}
return bicMapConstants;
} | [
"public",
"static",
"BicMapSharedConstants",
"create",
"(",
")",
"{",
"if",
"(",
"bicMapConstants",
"==",
"null",
")",
"{",
"// NOPMD it's thread save!",
"synchronized",
"(",
"BicMapConstantsImpl",
".",
"class",
")",
"{",
"if",
"(",
"bicMapConstants",
"==",
"null"... | Instantiates a class via deferred binding.
@return the new instance, which must be cast to the requested class | [
"Instantiates",
"a",
"class",
"via",
"deferred",
"binding",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/server/data/CreateBicMapConstantsClass.java#L35-L45 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.timeTemplate | public static <T extends Comparable<?>> TimeTemplate<T> timeTemplate(Class<? extends T> cl,
String template, Object... args) {
return timeTemplate(cl, createTemplate(template), ImmutableList.copyOf(args));
} | java | public static <T extends Comparable<?>> TimeTemplate<T> timeTemplate(Class<? extends T> cl,
String template, Object... args) {
return timeTemplate(cl, createTemplate(template), ImmutableList.copyOf(args));
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"?",
">",
">",
"TimeTemplate",
"<",
"T",
">",
"timeTemplate",
"(",
"Class",
"<",
"?",
"extends",
"T",
">",
"cl",
",",
"String",
"template",
",",
"Object",
"...",
"args",
")",
"{",
"return",
... | Create a new Template expression
@param cl type of expression
@param template template
@param args template parameters
@return template expression | [
"Create",
"a",
"new",
"Template",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L643-L646 |
ykrasik/jaci | jaci-core/src/main/java/com/github/ykrasik/jaci/path/ParsedPath.java | ParsedPath.toEntry | public static ParsedPath toEntry(String rawPath) {
final String path = rawPath.trim();
final boolean startsWithDelimiter = path.startsWith("/");
// Keep the trailing delimiter.
// This allows us to treat paths that end with a delimiter differently from paths that don't.
// i.e. path/to would be a path with 2 elements: 'path' and 'to', but
// but path/to/ would be a path with 3 elements: 'path', 'to' and an empty element ''.
final List<String> pathElements = splitPath(path, true);
return new ParsedPath(startsWithDelimiter, pathElements);
} | java | public static ParsedPath toEntry(String rawPath) {
final String path = rawPath.trim();
final boolean startsWithDelimiter = path.startsWith("/");
// Keep the trailing delimiter.
// This allows us to treat paths that end with a delimiter differently from paths that don't.
// i.e. path/to would be a path with 2 elements: 'path' and 'to', but
// but path/to/ would be a path with 3 elements: 'path', 'to' and an empty element ''.
final List<String> pathElements = splitPath(path, true);
return new ParsedPath(startsWithDelimiter, pathElements);
} | [
"public",
"static",
"ParsedPath",
"toEntry",
"(",
"String",
"rawPath",
")",
"{",
"final",
"String",
"path",
"=",
"rawPath",
".",
"trim",
"(",
")",
";",
"final",
"boolean",
"startsWithDelimiter",
"=",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
";",
"// K... | Create a path that is expected to represent a path to any entry.
This is different from {@link #toDirectory(String)} in that if the path ends with a delimiter '/',
it is <b>not</b> considered the same as if it didn't.
i.e. path/to would be a path with 2 elements: 'path' and 'to', but
but path/to/ would be a path with 3 elements: 'path', 'to' and an empty element ''.
@param rawPath Path to parse.
@return A {@link ParsedPath} out of the given path.
@throws IllegalArgumentException If any element along the path except the last one is empty. | [
"Create",
"a",
"path",
"that",
"is",
"expected",
"to",
"represent",
"a",
"path",
"to",
"any",
"entry",
".",
"This",
"is",
"different",
"from",
"{",
"@link",
"#toDirectory",
"(",
"String",
")",
"}",
"in",
"that",
"if",
"the",
"path",
"ends",
"with",
"a"... | train | https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-core/src/main/java/com/github/ykrasik/jaci/path/ParsedPath.java#L181-L192 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/property/GeoPackageJavaProperties.java | GeoPackageJavaProperties.getIntegerProperty | public static Integer getIntegerProperty(String key, boolean required) {
Integer value = null;
String stringValue = getProperty(key, required);
if (stringValue != null) {
value = Integer.valueOf(stringValue);
}
return value;
} | java | public static Integer getIntegerProperty(String key, boolean required) {
Integer value = null;
String stringValue = getProperty(key, required);
if (stringValue != null) {
value = Integer.valueOf(stringValue);
}
return value;
} | [
"public",
"static",
"Integer",
"getIntegerProperty",
"(",
"String",
"key",
",",
"boolean",
"required",
")",
"{",
"Integer",
"value",
"=",
"null",
";",
"String",
"stringValue",
"=",
"getProperty",
"(",
"key",
",",
"required",
")",
";",
"if",
"(",
"stringValue... | Get an integer property by key
@param key
key
@param required
required flag
@return property value | [
"Get",
"an",
"integer",
"property",
"by",
"key"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/property/GeoPackageJavaProperties.java#L110-L117 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java | SheetRenderer.encodeScript | protected void encodeScript(final FacesContext context, final Sheet sheet, final ResponseWriter responseWriter)
throws IOException {
final WidgetBuilder wb = getWidgetBuilder(context);
final String clientId = sheet.getClientId(context);
wb.init("ExtSheet", sheet.resolveWidgetVar(), clientId);
// errors
encodeInvalidData(context, sheet, wb);
// data
encodeData(context, sheet, wb);
// the delta var that will be used to track changes client side
// stringified and placed in hidden input for submission
wb.nativeAttr("delta", "{}");
// filters
encodeFilterVar(context, sheet, wb);
// sortable
encodeSortVar(context, sheet, wb);
// behaviors
encodeBehaviors(context, sheet, wb);
encodeOptionalNativeAttr(wb, "readOnly", sheet.isReadOnly());
encodeOptionalNativeAttr(wb, "fixedColumnsLeft", sheet.getFixedCols());
encodeOptionalNativeAttr(wb, "fixedRowsTop", sheet.getFixedRows());
encodeOptionalNativeAttr(wb, "fixedRowsBottom", sheet.getFixedRowsBottom());
encodeOptionalNativeAttr(wb, "manualColumnResize", sheet.isResizableCols());
encodeOptionalNativeAttr(wb, "manualRowResize", sheet.isResizableRows());
encodeOptionalNativeAttr(wb, "manualColumnMove", sheet.isMovableCols());
encodeOptionalNativeAttr(wb, "manualRowMove", sheet.isMovableRows());
encodeOptionalNativeAttr(wb, "width", sheet.getWidth());
encodeOptionalNativeAttr(wb, "height", sheet.getHeight());
encodeOptionalNativeAttr(wb, "minRows", sheet.getMinRows());
encodeOptionalNativeAttr(wb, "minCols", sheet.getMinCols());
encodeOptionalNativeAttr(wb, "maxRows", sheet.getMaxRows());
encodeOptionalNativeAttr(wb, "maxCols", sheet.getMaxCols());
encodeOptionalAttr(wb, "stretchH", sheet.getStretchH());
encodeOptionalAttr(wb, "language", sheet.getLocale());
encodeOptionalAttr(wb, "selectionMode", sheet.getSelectionMode());
encodeOptionalAttr(wb, "activeHeaderClassName", sheet.getActiveHeaderStyleClass());
encodeOptionalAttr(wb, "commentedCellClassName", sheet.getCommentedCellStyleClass());
encodeOptionalAttr(wb, "currentRowClassName", sheet.getCurrentRowStyleClass());
encodeOptionalAttr(wb, "currentColClassName", sheet.getCurrentColStyleClass());
encodeOptionalAttr(wb, "currentHeaderClassName", sheet.getCurrentHeaderStyleClass());
encodeOptionalAttr(wb, "invalidCellClassName", sheet.getInvalidCellStyleClass());
encodeOptionalAttr(wb, "noWordWrapClassName", sheet.getNoWordWrapStyleClass());
encodeOptionalAttr(wb, "placeholderCellClassName", sheet.getPlaceholderCellStyleClass());
encodeOptionalAttr(wb, "readOnlyCellClassName", sheet.getReadOnlyCellStyleClass());
encodeOptionalNativeAttr(wb, "extender", sheet.getExtender());
String emptyMessage = sheet.getEmptyMessage();
if (LangUtils.isValueBlank(emptyMessage)) {
emptyMessage = "No Records Found";
}
encodeOptionalAttr(wb, "emptyMessage", emptyMessage);
encodeColHeaders(context, sheet, wb);
encodeColOptions(context, sheet, wb);
wb.finish();
} | java | protected void encodeScript(final FacesContext context, final Sheet sheet, final ResponseWriter responseWriter)
throws IOException {
final WidgetBuilder wb = getWidgetBuilder(context);
final String clientId = sheet.getClientId(context);
wb.init("ExtSheet", sheet.resolveWidgetVar(), clientId);
// errors
encodeInvalidData(context, sheet, wb);
// data
encodeData(context, sheet, wb);
// the delta var that will be used to track changes client side
// stringified and placed in hidden input for submission
wb.nativeAttr("delta", "{}");
// filters
encodeFilterVar(context, sheet, wb);
// sortable
encodeSortVar(context, sheet, wb);
// behaviors
encodeBehaviors(context, sheet, wb);
encodeOptionalNativeAttr(wb, "readOnly", sheet.isReadOnly());
encodeOptionalNativeAttr(wb, "fixedColumnsLeft", sheet.getFixedCols());
encodeOptionalNativeAttr(wb, "fixedRowsTop", sheet.getFixedRows());
encodeOptionalNativeAttr(wb, "fixedRowsBottom", sheet.getFixedRowsBottom());
encodeOptionalNativeAttr(wb, "manualColumnResize", sheet.isResizableCols());
encodeOptionalNativeAttr(wb, "manualRowResize", sheet.isResizableRows());
encodeOptionalNativeAttr(wb, "manualColumnMove", sheet.isMovableCols());
encodeOptionalNativeAttr(wb, "manualRowMove", sheet.isMovableRows());
encodeOptionalNativeAttr(wb, "width", sheet.getWidth());
encodeOptionalNativeAttr(wb, "height", sheet.getHeight());
encodeOptionalNativeAttr(wb, "minRows", sheet.getMinRows());
encodeOptionalNativeAttr(wb, "minCols", sheet.getMinCols());
encodeOptionalNativeAttr(wb, "maxRows", sheet.getMaxRows());
encodeOptionalNativeAttr(wb, "maxCols", sheet.getMaxCols());
encodeOptionalAttr(wb, "stretchH", sheet.getStretchH());
encodeOptionalAttr(wb, "language", sheet.getLocale());
encodeOptionalAttr(wb, "selectionMode", sheet.getSelectionMode());
encodeOptionalAttr(wb, "activeHeaderClassName", sheet.getActiveHeaderStyleClass());
encodeOptionalAttr(wb, "commentedCellClassName", sheet.getCommentedCellStyleClass());
encodeOptionalAttr(wb, "currentRowClassName", sheet.getCurrentRowStyleClass());
encodeOptionalAttr(wb, "currentColClassName", sheet.getCurrentColStyleClass());
encodeOptionalAttr(wb, "currentHeaderClassName", sheet.getCurrentHeaderStyleClass());
encodeOptionalAttr(wb, "invalidCellClassName", sheet.getInvalidCellStyleClass());
encodeOptionalAttr(wb, "noWordWrapClassName", sheet.getNoWordWrapStyleClass());
encodeOptionalAttr(wb, "placeholderCellClassName", sheet.getPlaceholderCellStyleClass());
encodeOptionalAttr(wb, "readOnlyCellClassName", sheet.getReadOnlyCellStyleClass());
encodeOptionalNativeAttr(wb, "extender", sheet.getExtender());
String emptyMessage = sheet.getEmptyMessage();
if (LangUtils.isValueBlank(emptyMessage)) {
emptyMessage = "No Records Found";
}
encodeOptionalAttr(wb, "emptyMessage", emptyMessage);
encodeColHeaders(context, sheet, wb);
encodeColOptions(context, sheet, wb);
wb.finish();
} | [
"protected",
"void",
"encodeScript",
"(",
"final",
"FacesContext",
"context",
",",
"final",
"Sheet",
"sheet",
",",
"final",
"ResponseWriter",
"responseWriter",
")",
"throws",
"IOException",
"{",
"final",
"WidgetBuilder",
"wb",
"=",
"getWidgetBuilder",
"(",
"context"... | Encodes the Javascript for the sheet.
@param context
@param sheet
@throws IOException | [
"Encodes",
"the",
"Javascript",
"for",
"the",
"sheet",
"."
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L182-L241 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java | Transforms.lessThanOrEqual | public static INDArray lessThanOrEqual(INDArray first, INDArray ndArray) {
return lessThanOrEqual(first, ndArray, true);
} | java | public static INDArray lessThanOrEqual(INDArray first, INDArray ndArray) {
return lessThanOrEqual(first, ndArray, true);
} | [
"public",
"static",
"INDArray",
"lessThanOrEqual",
"(",
"INDArray",
"first",
",",
"INDArray",
"ndArray",
")",
"{",
"return",
"lessThanOrEqual",
"(",
"first",
",",
"ndArray",
",",
"true",
")",
";",
"}"
] | 1 if less than or equal to 0 otherwise (at each element)
@param first
@param ndArray
@return | [
"1",
"if",
"less",
"than",
"or",
"equal",
"to",
"0",
"otherwise",
"(",
"at",
"each",
"element",
")"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java#L772-L774 |
google/closure-compiler | src/com/google/javascript/jscomp/NodeUtil.java | NodeUtil.deleteNode | public static void deleteNode(Node n, AbstractCompiler compiler) {
Node parent = n.getParent();
NodeUtil.markFunctionsDeleted(n, compiler);
n.detach();
compiler.reportChangeToEnclosingScope(parent);
} | java | public static void deleteNode(Node n, AbstractCompiler compiler) {
Node parent = n.getParent();
NodeUtil.markFunctionsDeleted(n, compiler);
n.detach();
compiler.reportChangeToEnclosingScope(parent);
} | [
"public",
"static",
"void",
"deleteNode",
"(",
"Node",
"n",
",",
"AbstractCompiler",
"compiler",
")",
"{",
"Node",
"parent",
"=",
"n",
".",
"getParent",
"(",
")",
";",
"NodeUtil",
".",
"markFunctionsDeleted",
"(",
"n",
",",
"compiler",
")",
";",
"n",
"."... | Permanently delete the given node from the AST, as well as report
the related AST changes/deletions to the given compiler. | [
"Permanently",
"delete",
"the",
"given",
"node",
"from",
"the",
"AST",
"as",
"well",
"as",
"report",
"the",
"related",
"AST",
"changes",
"/",
"deletions",
"to",
"the",
"given",
"compiler",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L2746-L2751 |
resilience4j/resilience4j | resilience4j-prometheus/src/main/java/io/github/resilience4j/prometheus/collectors/BulkheadMetricsCollector.java | BulkheadMetricsCollector.ofSupplier | public static BulkheadMetricsCollector ofSupplier(MetricNames names, Supplier<? extends Iterable<? extends Bulkhead>> supplier) {
return new BulkheadMetricsCollector(names, supplier);
} | java | public static BulkheadMetricsCollector ofSupplier(MetricNames names, Supplier<? extends Iterable<? extends Bulkhead>> supplier) {
return new BulkheadMetricsCollector(names, supplier);
} | [
"public",
"static",
"BulkheadMetricsCollector",
"ofSupplier",
"(",
"MetricNames",
"names",
",",
"Supplier",
"<",
"?",
"extends",
"Iterable",
"<",
"?",
"extends",
"Bulkhead",
">",
">",
"supplier",
")",
"{",
"return",
"new",
"BulkheadMetricsCollector",
"(",
"names",... | Creates a new collector with custom metric names and
using given {@code supplier} as source of bulkheads.
@param names the custom metric names
@param supplier the supplier of bulkheads, note that supplier will be called one every {@link #collect()} | [
"Creates",
"a",
"new",
"collector",
"with",
"custom",
"metric",
"names",
"and",
"using",
"given",
"{",
"@code",
"supplier",
"}",
"as",
"source",
"of",
"bulkheads",
"."
] | train | https://github.com/resilience4j/resilience4j/blob/fa843d30f531c00f0c3dc218b65a7f2bb51af336/resilience4j-prometheus/src/main/java/io/github/resilience4j/prometheus/collectors/BulkheadMetricsCollector.java#L42-L44 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java | IDManager.constructId | private long constructId(long count, long partition, VertexIDType type) {
Preconditions.checkArgument(partition<partitionIDBound && partition>=0,"Invalid partition: %s",partition);
Preconditions.checkArgument(count>=0);
Preconditions.checkArgument(VariableLong.unsignedBitLength(count)+partitionBits+
(type==null?0:type.offset())<=TOTAL_BITS);
Preconditions.checkArgument(type==null || type.isProper());
long id = (count<<partitionBits)+partition;
if (type!=null) id = type.addPadding(id);
return id;
} | java | private long constructId(long count, long partition, VertexIDType type) {
Preconditions.checkArgument(partition<partitionIDBound && partition>=0,"Invalid partition: %s",partition);
Preconditions.checkArgument(count>=0);
Preconditions.checkArgument(VariableLong.unsignedBitLength(count)+partitionBits+
(type==null?0:type.offset())<=TOTAL_BITS);
Preconditions.checkArgument(type==null || type.isProper());
long id = (count<<partitionBits)+partition;
if (type!=null) id = type.addPadding(id);
return id;
} | [
"private",
"long",
"constructId",
"(",
"long",
"count",
",",
"long",
"partition",
",",
"VertexIDType",
"type",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"partition",
"<",
"partitionIDBound",
"&&",
"partition",
">=",
"0",
",",
"\"Invalid partition: %s\"... | /* --- TitanElement id bit format ---
[ 0 | count | partition | ID padding (if any) ] | [
"/",
"*",
"---",
"TitanElement",
"id",
"bit",
"format",
"---",
"[",
"0",
"|",
"count",
"|",
"partition",
"|",
"ID",
"padding",
"(",
"if",
"any",
")",
"]"
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java#L432-L441 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/CueList.java | CueList.addEntriesFromTag | private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {
for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.
if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {
entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),
Util.timeToHalfFrame(cueEntry.loopTime())));
} else {
entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));
}
}
} | java | private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {
for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.
if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {
entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),
Util.timeToHalfFrame(cueEntry.loopTime())));
} else {
entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));
}
}
} | [
"private",
"void",
"addEntriesFromTag",
"(",
"List",
"<",
"Entry",
">",
"entries",
",",
"RekordboxAnlz",
".",
"CueTag",
"tag",
")",
"{",
"for",
"(",
"RekordboxAnlz",
".",
"CueEntry",
"cueEntry",
":",
"tag",
".",
"cues",
"(",
")",
")",
"{",
"// TODO: Need t... | Helper method to add cue list entries from a parsed ANLZ cue tag
@param entries the list of entries being accumulated
@param tag the tag whose entries are to be added | [
"Helper",
"method",
"to",
"add",
"cue",
"list",
"entries",
"from",
"a",
"parsed",
"ANLZ",
"cue",
"tag"
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/CueList.java#L226-L235 |
Wikidata/Wikidata-Toolkit | wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java | Timer.getNamedTotalTimer | public static Timer getNamedTotalTimer(String timerName) {
long totalCpuTime = 0;
long totalSystemTime = 0;
int measurements = 0;
int timerCount = 0;
int todoFlags = RECORD_NONE;
Timer previousTimer = null;
for (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) {
if (entry.getValue().name.equals(timerName)) {
previousTimer = entry.getValue();
timerCount += 1;
totalCpuTime += previousTimer.totalCpuTime;
totalSystemTime += previousTimer.totalWallTime;
measurements += previousTimer.measurements;
todoFlags |= previousTimer.todoFlags;
}
}
if (timerCount == 1) {
return previousTimer;
} else {
Timer result = new Timer(timerName, todoFlags, 0);
result.totalCpuTime = totalCpuTime;
result.totalWallTime = totalSystemTime;
result.measurements = measurements;
result.threadCount = timerCount;
return result;
}
} | java | public static Timer getNamedTotalTimer(String timerName) {
long totalCpuTime = 0;
long totalSystemTime = 0;
int measurements = 0;
int timerCount = 0;
int todoFlags = RECORD_NONE;
Timer previousTimer = null;
for (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) {
if (entry.getValue().name.equals(timerName)) {
previousTimer = entry.getValue();
timerCount += 1;
totalCpuTime += previousTimer.totalCpuTime;
totalSystemTime += previousTimer.totalWallTime;
measurements += previousTimer.measurements;
todoFlags |= previousTimer.todoFlags;
}
}
if (timerCount == 1) {
return previousTimer;
} else {
Timer result = new Timer(timerName, todoFlags, 0);
result.totalCpuTime = totalCpuTime;
result.totalWallTime = totalSystemTime;
result.measurements = measurements;
result.threadCount = timerCount;
return result;
}
} | [
"public",
"static",
"Timer",
"getNamedTotalTimer",
"(",
"String",
"timerName",
")",
"{",
"long",
"totalCpuTime",
"=",
"0",
";",
"long",
"totalSystemTime",
"=",
"0",
";",
"int",
"measurements",
"=",
"0",
";",
"int",
"timerCount",
"=",
"0",
";",
"int",
"todo... | Collect the total times measured by all known named timers of the given
name. This is useful to add up times that were collected across separate
threads.
@param timerName
@return timer | [
"Collect",
"the",
"total",
"times",
"measured",
"by",
"all",
"known",
"named",
"timers",
"of",
"the",
"given",
"name",
".",
"This",
"is",
"useful",
"to",
"add",
"up",
"times",
"that",
"were",
"collected",
"across",
"separate",
"threads",
"."
] | train | https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L526-L555 |
Red5/red5-server-common | src/main/java/org/red5/server/stream/ClientBroadcastStream.java | ClientBroadcastStream.getRecordFile | protected File getRecordFile(IScope scope, String name) {
return RecordingListener.getRecordFile(scope, name);
} | java | protected File getRecordFile(IScope scope, String name) {
return RecordingListener.getRecordFile(scope, name);
} | [
"protected",
"File",
"getRecordFile",
"(",
"IScope",
"scope",
",",
"String",
"name",
")",
"{",
"return",
"RecordingListener",
".",
"getRecordFile",
"(",
"scope",
",",
"name",
")",
";",
"}"
] | Get the file we'd be recording to based on scope and given name.
@param scope
scope
@param name
record name
@return file | [
"Get",
"the",
"file",
"we",
"d",
"be",
"recording",
"to",
"based",
"on",
"scope",
"and",
"given",
"name",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/ClientBroadcastStream.java#L956-L958 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.marketplace_createListing | public Long marketplace_createListing(Boolean showOnProfile, MarketplaceListing attrs)
throws FacebookException, IOException {
T result =
this.callMethod(FacebookMethod.MARKETPLACE_CREATE_LISTING,
new Pair<String, CharSequence>("show_on_profile", showOnProfile ? "1" : "0"),
new Pair<String, CharSequence>("listing_id", "0"),
new Pair<String, CharSequence>("listing_attrs", attrs.jsonify().toString()));
return this.extractLong(result);
} | java | public Long marketplace_createListing(Boolean showOnProfile, MarketplaceListing attrs)
throws FacebookException, IOException {
T result =
this.callMethod(FacebookMethod.MARKETPLACE_CREATE_LISTING,
new Pair<String, CharSequence>("show_on_profile", showOnProfile ? "1" : "0"),
new Pair<String, CharSequence>("listing_id", "0"),
new Pair<String, CharSequence>("listing_attrs", attrs.jsonify().toString()));
return this.extractLong(result);
} | [
"public",
"Long",
"marketplace_createListing",
"(",
"Boolean",
"showOnProfile",
",",
"MarketplaceListing",
"attrs",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"T",
"result",
"=",
"this",
".",
"callMethod",
"(",
"FacebookMethod",
".",
"MARKETPLACE_CRE... | Create a marketplace listing
@param showOnProfile whether the listing can be shown on the user's profile
@param attrs the properties of the listing
@return the id of the created listing
@see MarketplaceListing
@see <a href="http://wiki.developers.facebook.com/index.php/Marketplace.createListing">
Developers Wiki: marketplace.createListing</a> | [
"Create",
"a",
"marketplace",
"listing"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1929-L1937 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/json/JSONSerializer.java | JSONSerializer.serializeObject | public static String serializeObject(final Object obj, final int indentWidth,
final boolean onlySerializePublicFields) {
return serializeObject(obj, indentWidth, onlySerializePublicFields,
new ClassFieldCache(/* resolveTypes = */ false, /* onlySerializePublicFields = */ false));
} | java | public static String serializeObject(final Object obj, final int indentWidth,
final boolean onlySerializePublicFields) {
return serializeObject(obj, indentWidth, onlySerializePublicFields,
new ClassFieldCache(/* resolveTypes = */ false, /* onlySerializePublicFields = */ false));
} | [
"public",
"static",
"String",
"serializeObject",
"(",
"final",
"Object",
"obj",
",",
"final",
"int",
"indentWidth",
",",
"final",
"boolean",
"onlySerializePublicFields",
")",
"{",
"return",
"serializeObject",
"(",
"obj",
",",
"indentWidth",
",",
"onlySerializePublic... | Recursively serialize an Object (or array, list, map or set of objects) to JSON, skipping transient and final
fields.
@param obj
The root object of the object graph to serialize.
@param indentWidth
If indentWidth == 0, no prettyprinting indentation is performed, otherwise this specifies the
number of spaces to indent each level of JSON.
@param onlySerializePublicFields
If true, only serialize public fields.
@return The object graph in JSON form.
@throws IllegalArgumentException
If anything goes wrong during serialization. | [
"Recursively",
"serialize",
"an",
"Object",
"(",
"or",
"array",
"list",
"map",
"or",
"set",
"of",
"objects",
")",
"to",
"JSON",
"skipping",
"transient",
"and",
"final",
"fields",
"."
] | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/json/JSONSerializer.java#L508-L512 |
liferay/com-liferay-commerce | commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java | CommerceDiscountPersistenceImpl.removeByUUID_G | @Override
public CommerceDiscount removeByUUID_G(String uuid, long groupId)
throws NoSuchDiscountException {
CommerceDiscount commerceDiscount = findByUUID_G(uuid, groupId);
return remove(commerceDiscount);
} | java | @Override
public CommerceDiscount removeByUUID_G(String uuid, long groupId)
throws NoSuchDiscountException {
CommerceDiscount commerceDiscount = findByUUID_G(uuid, groupId);
return remove(commerceDiscount);
} | [
"@",
"Override",
"public",
"CommerceDiscount",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchDiscountException",
"{",
"CommerceDiscount",
"commerceDiscount",
"=",
"findByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"return... | Removes the commerce discount where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce discount that was removed | [
"Removes",
"the",
"commerce",
"discount",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java#L816-L822 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.eligibility_search_streetNumbers_POST | public OvhAsyncTaskArray<String> eligibility_search_streetNumbers_POST(String streetCode) throws IOException {
String qPath = "/xdsl/eligibility/search/streetNumbers";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "streetCode", streetCode);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t8);
} | java | public OvhAsyncTaskArray<String> eligibility_search_streetNumbers_POST(String streetCode) throws IOException {
String qPath = "/xdsl/eligibility/search/streetNumbers";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "streetCode", streetCode);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t8);
} | [
"public",
"OvhAsyncTaskArray",
"<",
"String",
">",
"eligibility_search_streetNumbers_POST",
"(",
"String",
"streetCode",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/eligibility/search/streetNumbers\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
... | Get the available street numbers for a given street code (unique identifier of a street you can get with the method POST /xdsl/eligibility/search/streets)
REST: POST /xdsl/eligibility/search/streetNumbers
@param streetCode [required] Street code
@deprecated | [
"Get",
"the",
"available",
"street",
"numbers",
"for",
"a",
"given",
"street",
"code",
"(",
"unique",
"identifier",
"of",
"a",
"street",
"you",
"can",
"get",
"with",
"the",
"method",
"POST",
"/",
"xdsl",
"/",
"eligibility",
"/",
"search",
"/",
"streets",
... | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L339-L346 |
Azure/azure-sdk-for-java | iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java | IotHubResourcesInner.getKeysForKeyNameAsync | public ServiceFuture<SharedAccessSignatureAuthorizationRuleInner> getKeysForKeyNameAsync(String resourceGroupName, String resourceName, String keyName, final ServiceCallback<SharedAccessSignatureAuthorizationRuleInner> serviceCallback) {
return ServiceFuture.fromResponse(getKeysForKeyNameWithServiceResponseAsync(resourceGroupName, resourceName, keyName), serviceCallback);
} | java | public ServiceFuture<SharedAccessSignatureAuthorizationRuleInner> getKeysForKeyNameAsync(String resourceGroupName, String resourceName, String keyName, final ServiceCallback<SharedAccessSignatureAuthorizationRuleInner> serviceCallback) {
return ServiceFuture.fromResponse(getKeysForKeyNameWithServiceResponseAsync(resourceGroupName, resourceName, keyName), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"SharedAccessSignatureAuthorizationRuleInner",
">",
"getKeysForKeyNameAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
",",
"String",
"keyName",
",",
"final",
"ServiceCallback",
"<",
"SharedAccessSignatureAuthorizationRu... | Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
Get a shared access policy by name from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@param keyName The name of the shared access policy.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Get",
"a",
"shared",
"access",
"policy",
"by",
"name",
"from",
"an",
"IoT",
"hub",
".",
"For",
"more",
"information",
"see",
":",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"azure",
"/",
"iot",
"-",
"hub",
"/",
"iot",
"-",
"hub... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L2985-L2987 |
groovy/gmaven | groovy-maven-plugin/src/main/java/org/codehaus/gmaven/plugin/util/GroovyVersionHelper.java | GroovyVersionHelper.getVersion | private String getVersion(final ClassLoader classLoader, final String className, final String methodName) {
log.trace("Getting version; class-loader: {}, class-name: {}, method-name: {}",
classLoader, className, methodName);
try {
Class<?> type = classLoader.loadClass(className);
Method method = type.getMethod(methodName);
Object result = method.invoke(null);
if (result != null) {
return result.toString();
}
}
catch (Throwable e) {
log.trace("Unable determine version from: {}", className);
}
return null;
} | java | private String getVersion(final ClassLoader classLoader, final String className, final String methodName) {
log.trace("Getting version; class-loader: {}, class-name: {}, method-name: {}",
classLoader, className, methodName);
try {
Class<?> type = classLoader.loadClass(className);
Method method = type.getMethod(methodName);
Object result = method.invoke(null);
if (result != null) {
return result.toString();
}
}
catch (Throwable e) {
log.trace("Unable determine version from: {}", className);
}
return null;
} | [
"private",
"String",
"getVersion",
"(",
"final",
"ClassLoader",
"classLoader",
",",
"final",
"String",
"className",
",",
"final",
"String",
"methodName",
")",
"{",
"log",
".",
"trace",
"(",
"\"Getting version; class-loader: {}, class-name: {}, method-name: {}\"",
",",
"... | Get version from Groovy version helper utilities via reflection. | [
"Get",
"version",
"from",
"Groovy",
"version",
"helper",
"utilities",
"via",
"reflection",
"."
] | train | https://github.com/groovy/gmaven/blob/6978316bbc29d9cc6793494e0d1a0a057e47de6c/groovy-maven-plugin/src/main/java/org/codehaus/gmaven/plugin/util/GroovyVersionHelper.java#L77-L94 |
hypercube1024/firefly | firefly/src/main/java/com/firefly/codec/http2/model/HttpFields.java | HttpFields.put | public void put(HttpHeader header, String value) {
if (value == null)
remove(header);
else
put(new HttpField(header, value));
} | java | public void put(HttpHeader header, String value) {
if (value == null)
remove(header);
else
put(new HttpField(header, value));
} | [
"public",
"void",
"put",
"(",
"HttpHeader",
"header",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"remove",
"(",
"header",
")",
";",
"else",
"put",
"(",
"new",
"HttpField",
"(",
"header",
",",
"value",
")",
")",
";",
"}... | Set a field.
@param header the header name of the field
@param value the value of the field. If null the field is cleared. | [
"Set",
"a",
"field",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/model/HttpFields.java#L519-L524 |
marklogic/marklogic-sesame | marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java | MarkLogicRepositoryConnection.removeWithoutCommit | @Override
protected void removeWithoutCommit(Resource subject, URI predicate, Value object, Resource... contexts) throws RepositoryException {
remove(subject, predicate, object, contexts);
} | java | @Override
protected void removeWithoutCommit(Resource subject, URI predicate, Value object, Resource... contexts) throws RepositoryException {
remove(subject, predicate, object, contexts);
} | [
"@",
"Override",
"protected",
"void",
"removeWithoutCommit",
"(",
"Resource",
"subject",
",",
"URI",
"predicate",
",",
"Value",
"object",
",",
"Resource",
"...",
"contexts",
")",
"throws",
"RepositoryException",
"{",
"remove",
"(",
"subject",
",",
"predicate",
"... | remove without commit
supplied to honor interface
@param subject
@param predicate
@param object
@param contexts
@throws RepositoryException | [
"remove",
"without",
"commit"
] | train | https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java#L1220-L1223 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java | SDLoss.l2Loss | public SDVariable l2Loss(String name, @NonNull SDVariable var) {
validateNumerical("l2 loss", var);
SDVariable result = f().lossL2(var);
result = updateVariableNameAndReference(result, name);
result.markAsLoss();
return result;
} | java | public SDVariable l2Loss(String name, @NonNull SDVariable var) {
validateNumerical("l2 loss", var);
SDVariable result = f().lossL2(var);
result = updateVariableNameAndReference(result, name);
result.markAsLoss();
return result;
} | [
"public",
"SDVariable",
"l2Loss",
"(",
"String",
"name",
",",
"@",
"NonNull",
"SDVariable",
"var",
")",
"{",
"validateNumerical",
"(",
"\"l2 loss\"",
",",
"var",
")",
";",
"SDVariable",
"result",
"=",
"f",
"(",
")",
".",
"lossL2",
"(",
"var",
")",
";",
... | L2 loss: 1/2 * sum(x^2)
@param name Name of the output variable
@param var Variable to calculate L2 loss of
@return L2 loss | [
"L2",
"loss",
":",
"1",
"/",
"2",
"*",
"sum",
"(",
"x^2",
")"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java#L202-L208 |
jMotif/GI | src/main/java/net/seninp/gi/sequitur/SequiturFactory.java | SequiturFactory.series2SequiturRules | public static GrammarRules series2SequiturRules(double[] timeseries, int saxWindowSize,
int saxPAASize, int saxAlphabetSize, NumerosityReductionStrategy numerosityReductionStrategy,
double normalizationThreshold) throws Exception, IOException {
LOGGER.debug("Discretizing time series...");
SAXRecords saxFrequencyData = sp.ts2saxViaWindow(timeseries, saxWindowSize, saxPAASize,
normalA.getCuts(saxAlphabetSize), numerosityReductionStrategy, normalizationThreshold);
LOGGER.debug("Inferring the grammar...");
// this is a string we are about to feed into Sequitur
//
String saxDisplayString = saxFrequencyData.getSAXString(" ");
// reset the Sequitur data structures
SAXRule.numRules = new AtomicInteger(0);
SAXRule.theRules.clear();
SAXSymbol.theDigrams.clear();
// bootstrap the grammar
SAXRule grammar = new SAXRule();
SAXRule.arrRuleRecords = new ArrayList<GrammarRuleRecord>();
// digest the string via the tokenizer and build the grammar
StringTokenizer st = new StringTokenizer(saxDisplayString, " ");
int currentPosition = 0;
while (st.hasMoreTokens()) {
grammar.last().insertAfter(new SAXTerminal(st.nextToken(), currentPosition));
grammar.last().p.check();
currentPosition++;
}
// bw.close();
LOGGER.debug("Collecting the grammar rules statistics and expanding the rules...");
GrammarRules rules = grammar.toGrammarRulesData();
LOGGER.debug("Mapping expanded rules to time-series intervals...");
SequiturFactory.updateRuleIntervals(rules, saxFrequencyData, true, timeseries, saxWindowSize,
saxPAASize);
return rules;
} | java | public static GrammarRules series2SequiturRules(double[] timeseries, int saxWindowSize,
int saxPAASize, int saxAlphabetSize, NumerosityReductionStrategy numerosityReductionStrategy,
double normalizationThreshold) throws Exception, IOException {
LOGGER.debug("Discretizing time series...");
SAXRecords saxFrequencyData = sp.ts2saxViaWindow(timeseries, saxWindowSize, saxPAASize,
normalA.getCuts(saxAlphabetSize), numerosityReductionStrategy, normalizationThreshold);
LOGGER.debug("Inferring the grammar...");
// this is a string we are about to feed into Sequitur
//
String saxDisplayString = saxFrequencyData.getSAXString(" ");
// reset the Sequitur data structures
SAXRule.numRules = new AtomicInteger(0);
SAXRule.theRules.clear();
SAXSymbol.theDigrams.clear();
// bootstrap the grammar
SAXRule grammar = new SAXRule();
SAXRule.arrRuleRecords = new ArrayList<GrammarRuleRecord>();
// digest the string via the tokenizer and build the grammar
StringTokenizer st = new StringTokenizer(saxDisplayString, " ");
int currentPosition = 0;
while (st.hasMoreTokens()) {
grammar.last().insertAfter(new SAXTerminal(st.nextToken(), currentPosition));
grammar.last().p.check();
currentPosition++;
}
// bw.close();
LOGGER.debug("Collecting the grammar rules statistics and expanding the rules...");
GrammarRules rules = grammar.toGrammarRulesData();
LOGGER.debug("Mapping expanded rules to time-series intervals...");
SequiturFactory.updateRuleIntervals(rules, saxFrequencyData, true, timeseries, saxWindowSize,
saxPAASize);
return rules;
} | [
"public",
"static",
"GrammarRules",
"series2SequiturRules",
"(",
"double",
"[",
"]",
"timeseries",
",",
"int",
"saxWindowSize",
",",
"int",
"saxPAASize",
",",
"int",
"saxAlphabetSize",
",",
"NumerosityReductionStrategy",
"numerosityReductionStrategy",
",",
"double",
"no... | Takes a time series and returns a grammar.
@param timeseries the input time series.
@param saxWindowSize the sliding window size.
@param saxPAASize the PAA num.
@param saxAlphabetSize the SAX alphabet size.
@param numerosityReductionStrategy the SAX Numerosity Reduction strategy.
@param normalizationThreshold the SAX normalization threshod.
@return the set of rules, i.e. the grammar.
@throws Exception if error occurs.
@throws IOException if error occurs. | [
"Takes",
"a",
"time",
"series",
"and",
"returns",
"a",
"grammar",
"."
] | train | https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/sequitur/SequiturFactory.java#L112-L155 |
jglobus/JGlobus | gridftp/src/main/java/org/globus/ftp/FTPClient.java | FTPClient.setClientWaitParams | public void setClientWaitParams(int maxWait, int waitDelay) {
if (maxWait <= 0 || waitDelay <= 0) {
throw new IllegalArgumentException("Parameter is less than 0");
}
this.session.maxWait = maxWait;
this.session.waitDelay = waitDelay;
} | java | public void setClientWaitParams(int maxWait, int waitDelay) {
if (maxWait <= 0 || waitDelay <= 0) {
throw new IllegalArgumentException("Parameter is less than 0");
}
this.session.maxWait = maxWait;
this.session.waitDelay = waitDelay;
} | [
"public",
"void",
"setClientWaitParams",
"(",
"int",
"maxWait",
",",
"int",
"waitDelay",
")",
"{",
"if",
"(",
"maxWait",
"<=",
"0",
"||",
"waitDelay",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter is less than 0\"",
")",
";... | Changes the default client timeout parameters.
In the beginning of the transfer, the critical moment is the wait
for the initial server reply. If it does not arrive after timeout,
client assumes that the transfer could not start for some reason and
aborts the operation. Default timeout in miliseconds
is Session.DEFAULT_MAX_WAIT. During the waiting period,
client polls the control channel once a certain period, which is by
default set to Session.DEFAULT_WAIT_DELAY.
<br>
Use this method to change these parameters.
@param maxWait timeout in miliseconds
@param waitDelay polling period | [
"Changes",
"the",
"default",
"client",
"timeout",
"parameters",
".",
"In",
"the",
"beginning",
"of",
"the",
"transfer",
"the",
"critical",
"moment",
"is",
"the",
"wait",
"for",
"the",
"initial",
"server",
"reply",
".",
"If",
"it",
"does",
"not",
"arrive",
... | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/FTPClient.java#L1135-L1141 |
JOML-CI/JOML | src/org/joml/Intersectionf.java | Intersectionf.distancePointPlane | public static float distancePointPlane(float pointX, float pointY, float pointZ, float a, float b, float c, float d) {
float denom = (float) Math.sqrt(a * a + b * b + c * c);
return (a * pointX + b * pointY + c * pointZ + d) / denom;
} | java | public static float distancePointPlane(float pointX, float pointY, float pointZ, float a, float b, float c, float d) {
float denom = (float) Math.sqrt(a * a + b * b + c * c);
return (a * pointX + b * pointY + c * pointZ + d) / denom;
} | [
"public",
"static",
"float",
"distancePointPlane",
"(",
"float",
"pointX",
",",
"float",
"pointY",
",",
"float",
"pointZ",
",",
"float",
"a",
",",
"float",
"b",
",",
"float",
"c",
",",
"float",
"d",
")",
"{",
"float",
"denom",
"=",
"(",
"float",
")",
... | Determine the signed distance of the given point <code>(pointX, pointY, pointZ)</code> to the plane specified via its general plane equation
<i>a*x + b*y + c*z + d = 0</i>.
@param pointX
the x coordinate of the point
@param pointY
the y coordinate of the point
@param pointZ
the z coordinate of the point
@param a
the x factor in the plane equation
@param b
the y factor in the plane equation
@param c
the z factor in the plane equation
@param d
the constant in the plane equation
@return the distance between the point and the plane | [
"Determine",
"the",
"signed",
"distance",
"of",
"the",
"given",
"point",
"<code",
">",
"(",
"pointX",
"pointY",
"pointZ",
")",
"<",
"/",
"code",
">",
"to",
"the",
"plane",
"specified",
"via",
"its",
"general",
"plane",
"equation",
"<i",
">",
"a",
"*",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L958-L961 |
keenlabs/KeenClient-Java | core/src/main/java/io/keen/client/java/KeenClient.java | KeenClient.setAttemptsMap | private void setAttemptsMap(String projectId, String eventCollection, Map<String, Integer> attempts) throws IOException {
if (eventStore instanceof KeenAttemptCountingEventStore) {
KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore;
StringWriter writer = null;
try {
writer = new StringWriter();
jsonHandler.writeJson(writer, attempts);
String attemptsJSON = writer.toString();
res.setAttempts(projectId, eventCollection, attemptsJSON);
} finally {
KeenUtils.closeQuietly(writer);
}
}
} | java | private void setAttemptsMap(String projectId, String eventCollection, Map<String, Integer> attempts) throws IOException {
if (eventStore instanceof KeenAttemptCountingEventStore) {
KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore;
StringWriter writer = null;
try {
writer = new StringWriter();
jsonHandler.writeJson(writer, attempts);
String attemptsJSON = writer.toString();
res.setAttempts(projectId, eventCollection, attemptsJSON);
} finally {
KeenUtils.closeQuietly(writer);
}
}
} | [
"private",
"void",
"setAttemptsMap",
"(",
"String",
"projectId",
",",
"String",
"eventCollection",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"attempts",
")",
"throws",
"IOException",
"{",
"if",
"(",
"eventStore",
"instanceof",
"KeenAttemptCountingEventStore",
... | Set the attempts Map in the eventStore
@param projectId the project id
@param eventCollection the collection name
@param attempts the current attempts Map
@throws IOException | [
"Set",
"the",
"attempts",
"Map",
"in",
"the",
"eventStore"
] | train | https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1774-L1787 |
wdullaer/MaterialDateTimePicker | library/src/main/java/com/wdullaer/materialdatetimepicker/date/DatePickerDialog.java | DatePickerDialog.setLocale | public void setLocale(Locale locale) {
mLocale = locale;
mWeekStart = Calendar.getInstance(mTimezone, mLocale).getFirstDayOfWeek();
YEAR_FORMAT = new SimpleDateFormat("yyyy", locale);
MONTH_FORMAT = new SimpleDateFormat("MMM", locale);
DAY_FORMAT = new SimpleDateFormat("dd", locale);
} | java | public void setLocale(Locale locale) {
mLocale = locale;
mWeekStart = Calendar.getInstance(mTimezone, mLocale).getFirstDayOfWeek();
YEAR_FORMAT = new SimpleDateFormat("yyyy", locale);
MONTH_FORMAT = new SimpleDateFormat("MMM", locale);
DAY_FORMAT = new SimpleDateFormat("dd", locale);
} | [
"public",
"void",
"setLocale",
"(",
"Locale",
"locale",
")",
"{",
"mLocale",
"=",
"locale",
";",
"mWeekStart",
"=",
"Calendar",
".",
"getInstance",
"(",
"mTimezone",
",",
"mLocale",
")",
".",
"getFirstDayOfWeek",
"(",
")",
";",
"YEAR_FORMAT",
"=",
"new",
"... | Set a custom locale to be used when generating various strings in the picker
@param locale Locale | [
"Set",
"a",
"custom",
"locale",
"to",
"be",
"used",
"when",
"generating",
"various",
"strings",
"in",
"the",
"picker"
] | train | https://github.com/wdullaer/MaterialDateTimePicker/blob/0a8fe28f19db4f5a5a6cfc525a852416232873a8/library/src/main/java/com/wdullaer/materialdatetimepicker/date/DatePickerDialog.java#L998-L1004 |
kaazing/gateway | util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java | Asn1Utils.decodeIA5String | public static String decodeIA5String(ByteBuffer buf) {
DerId id = DerId.decode(buf);
if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_IA5STRING_TAG_NUM)) {
throw new IllegalArgumentException("Expected IA5String identifier, received " + id);
}
int len = DerUtils.decodeLength(buf);
if (buf.remaining() < len) {
throw new IllegalArgumentException("Insufficient content for IA5String");
}
byte[] dst = new byte[len];
buf.get(dst);
return new String(dst);
} | java | public static String decodeIA5String(ByteBuffer buf) {
DerId id = DerId.decode(buf);
if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_IA5STRING_TAG_NUM)) {
throw new IllegalArgumentException("Expected IA5String identifier, received " + id);
}
int len = DerUtils.decodeLength(buf);
if (buf.remaining() < len) {
throw new IllegalArgumentException("Insufficient content for IA5String");
}
byte[] dst = new byte[len];
buf.get(dst);
return new String(dst);
} | [
"public",
"static",
"String",
"decodeIA5String",
"(",
"ByteBuffer",
"buf",
")",
"{",
"DerId",
"id",
"=",
"DerId",
".",
"decode",
"(",
"buf",
")",
";",
"if",
"(",
"!",
"id",
".",
"matches",
"(",
"DerId",
".",
"TagClass",
".",
"UNIVERSAL",
",",
"DerId",
... | Decode an ASN.1 IA5String.
@param buf
the DER-encoded IA5String
@return the string | [
"Decode",
"an",
"ASN",
".",
"1",
"IA5String",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java#L151-L163 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java | CertificateOperations.getCertificate | public Certificate getCertificate(String thumbprintAlgorithm, String thumbprint, DetailLevel detailLevel, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
CertificateGetOptions getCertificateOptions = new CertificateGetOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.appendDetailLevelToPerCallBehaviors(detailLevel);
bhMgr.applyRequestBehaviors(getCertificateOptions);
return this.parentBatchClient.protocolLayer().certificates().get(thumbprintAlgorithm, thumbprint, getCertificateOptions);
} | java | public Certificate getCertificate(String thumbprintAlgorithm, String thumbprint, DetailLevel detailLevel, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
CertificateGetOptions getCertificateOptions = new CertificateGetOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.appendDetailLevelToPerCallBehaviors(detailLevel);
bhMgr.applyRequestBehaviors(getCertificateOptions);
return this.parentBatchClient.protocolLayer().certificates().get(thumbprintAlgorithm, thumbprint, getCertificateOptions);
} | [
"public",
"Certificate",
"getCertificate",
"(",
"String",
"thumbprintAlgorithm",
",",
"String",
"thumbprint",
",",
"DetailLevel",
"detailLevel",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOExceptio... | Gets the specified {@link Certificate}.
@param thumbprintAlgorithm the algorithm used to derive the thumbprint parameter. This must be sha1.
@param thumbprint the thumbprint of the certificate to get.
@param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@return A {@link Certificate} containing information about the specified certificate in the Azure Batch account.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Gets",
"the",
"specified",
"{",
"@link",
"Certificate",
"}",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java#L273-L280 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java | DateTimeFormatterBuilder.appendOptional | public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) {
checkParser(parser);
InternalParser[] parsers = new InternalParser[] {DateTimeParserInternalParser.of(parser), null};
return append0(null, new MatchingParser(parsers));
} | java | public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) {
checkParser(parser);
InternalParser[] parsers = new InternalParser[] {DateTimeParserInternalParser.of(parser), null};
return append0(null, new MatchingParser(parsers));
} | [
"public",
"DateTimeFormatterBuilder",
"appendOptional",
"(",
"DateTimeParser",
"parser",
")",
"{",
"checkParser",
"(",
"parser",
")",
";",
"InternalParser",
"[",
"]",
"parsers",
"=",
"new",
"InternalParser",
"[",
"]",
"{",
"DateTimeParserInternalParser",
".",
"of",
... | Appends just a parser element which is optional. With no matching
printer, a printer cannot be built from this DateTimeFormatterBuilder.
<p>
The parser interface is part of the low-level part of the formatting API.
Normally, instances are extracted from another formatter.
Note however that any formatter specific information, such as the locale,
time-zone, chronology, offset parsing or pivot/default year, will not be
extracted by this method.
@return this DateTimeFormatterBuilder, for chaining
@throws IllegalArgumentException if parser is null or of an invalid type | [
"Appends",
"just",
"a",
"parser",
"element",
"which",
"is",
"optional",
".",
"With",
"no",
"matching",
"printer",
"a",
"printer",
"cannot",
"be",
"built",
"from",
"this",
"DateTimeFormatterBuilder",
".",
"<p",
">",
"The",
"parser",
"interface",
"is",
"part",
... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java#L345-L349 |
skuzzle/semantic-version | src/main/java/de/skuzzle/semantic/Version.java | Version.nextMajor | public Version nextMajor(String[] newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = verifyAndCopyArray(newPrelease, false);
return new Version(this.major + 1, 0, 0, newPreReleaseParts, EMPTY_ARRAY);
} | java | public Version nextMajor(String[] newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = verifyAndCopyArray(newPrelease, false);
return new Version(this.major + 1, 0, 0, newPreReleaseParts, EMPTY_ARRAY);
} | [
"public",
"Version",
"nextMajor",
"(",
"String",
"[",
"]",
"newPrelease",
")",
"{",
"require",
"(",
"newPrelease",
"!=",
"null",
",",
"\"newPreRelease is null\"",
")",
";",
"final",
"String",
"[",
"]",
"newPreReleaseParts",
"=",
"verifyAndCopyArray",
"(",
"newPr... | Given this Version, returns the next major Version. That is, the major part is
incremented by 1 and the remaining parts are set to 0. The pre-release part will be
set to the given identifier and the build-meta-data is dropped.
@param newPrelease The pre-release part for the resulting Version.
@return The incremented version.
@throws VersionFormatException If the any element of the given array is not a valid
pre release identifier part.
@throws IllegalArgumentException If newPreRelease is null.
@see #nextMajor()
@see #nextMajor(String)
@since 1.2.0 | [
"Given",
"this",
"Version",
"returns",
"the",
"next",
"major",
"Version",
".",
"That",
"is",
"the",
"major",
"part",
"is",
"incremented",
"by",
"1",
"and",
"the",
"remaining",
"parts",
"are",
"set",
"to",
"0",
".",
"The",
"pre",
"-",
"release",
"part",
... | train | https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/main/java/de/skuzzle/semantic/Version.java#L737-L741 |
querydsl/querydsl | querydsl-sql/src/main/java/com/querydsl/sql/oracle/AbstractOracleQuery.java | AbstractOracleQuery.connectByPrior | @WithBridgeMethods(value = OracleQuery.class, castRequired = true)
public C connectByPrior(Predicate cond) {
return addFlag(Position.BEFORE_ORDER, CONNECT_BY_PRIOR, cond);
} | java | @WithBridgeMethods(value = OracleQuery.class, castRequired = true)
public C connectByPrior(Predicate cond) {
return addFlag(Position.BEFORE_ORDER, CONNECT_BY_PRIOR, cond);
} | [
"@",
"WithBridgeMethods",
"(",
"value",
"=",
"OracleQuery",
".",
"class",
",",
"castRequired",
"=",
"true",
")",
"public",
"C",
"connectByPrior",
"(",
"Predicate",
"cond",
")",
"{",
"return",
"addFlag",
"(",
"Position",
".",
"BEFORE_ORDER",
",",
"CONNECT_BY_PR... | CONNECT BY specifies the relationship between parent rows and child rows of the hierarchy.
@param cond condition
@return the current object | [
"CONNECT",
"BY",
"specifies",
"the",
"relationship",
"between",
"parent",
"rows",
"and",
"child",
"rows",
"of",
"the",
"hierarchy",
"."
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/oracle/AbstractOracleQuery.java#L61-L64 |
samskivert/pythagoras | src/main/java/pythagoras/f/Crossing.java | Crossing.crossCubic | public static int crossCubic (float x1, float y1, float cx1, float cy1, float cx2,
float cy2, float x2, float y2, float x, float y) {
// LEFT/RIGHT/UP/EMPTY
if ((x < x1 && x < cx1 && x < cx2 && x < x2) || (x > x1 && x > cx1 && x > cx2 && x > x2)
|| (y > y1 && y > cy1 && y > cy2 && y > y2)
|| (x1 == cx1 && cx1 == cx2 && cx2 == x2)) {
return 0;
}
// DOWN
if (y < y1 && y < cy1 && y < cy2 && y < y2 && x != x1 && x != x2) {
if (x1 < x2) {
return x1 < x && x < x2 ? 1 : 0;
}
return x2 < x && x < x1 ? -1 : 0;
}
// INSIDE
CubicCurveH c = new CubicCurveH(x1, y1, cx1, cy1, cx2, cy2, x2, y2);
float px = x - x1, py = y - y1;
float[] res = new float[3];
int rc = c.solvePoint(res, px);
return c.cross(res, rc, py, py);
} | java | public static int crossCubic (float x1, float y1, float cx1, float cy1, float cx2,
float cy2, float x2, float y2, float x, float y) {
// LEFT/RIGHT/UP/EMPTY
if ((x < x1 && x < cx1 && x < cx2 && x < x2) || (x > x1 && x > cx1 && x > cx2 && x > x2)
|| (y > y1 && y > cy1 && y > cy2 && y > y2)
|| (x1 == cx1 && cx1 == cx2 && cx2 == x2)) {
return 0;
}
// DOWN
if (y < y1 && y < cy1 && y < cy2 && y < y2 && x != x1 && x != x2) {
if (x1 < x2) {
return x1 < x && x < x2 ? 1 : 0;
}
return x2 < x && x < x1 ? -1 : 0;
}
// INSIDE
CubicCurveH c = new CubicCurveH(x1, y1, cx1, cy1, cx2, cy2, x2, y2);
float px = x - x1, py = y - y1;
float[] res = new float[3];
int rc = c.solvePoint(res, px);
return c.cross(res, rc, py, py);
} | [
"public",
"static",
"int",
"crossCubic",
"(",
"float",
"x1",
",",
"float",
"y1",
",",
"float",
"cx1",
",",
"float",
"cy1",
",",
"float",
"cx2",
",",
"float",
"cy2",
",",
"float",
"x2",
",",
"float",
"y2",
",",
"float",
"x",
",",
"float",
"y",
")",
... | Returns how many times ray from point (x,y) cross cubic curve | [
"Returns",
"how",
"many",
"times",
"ray",
"from",
"point",
"(",
"x",
"y",
")",
"cross",
"cubic",
"curve"
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Crossing.java#L396-L419 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-webrisk/src/main/java/com/google/cloud/webrisk/v1beta1/WebRiskServiceV1Beta1Client.java | WebRiskServiceV1Beta1Client.searchUris | public final SearchUrisResponse searchUris(String uri, List<ThreatType> threatTypes) {
SearchUrisRequest request =
SearchUrisRequest.newBuilder().setUri(uri).addAllThreatTypes(threatTypes).build();
return searchUris(request);
} | java | public final SearchUrisResponse searchUris(String uri, List<ThreatType> threatTypes) {
SearchUrisRequest request =
SearchUrisRequest.newBuilder().setUri(uri).addAllThreatTypes(threatTypes).build();
return searchUris(request);
} | [
"public",
"final",
"SearchUrisResponse",
"searchUris",
"(",
"String",
"uri",
",",
"List",
"<",
"ThreatType",
">",
"threatTypes",
")",
"{",
"SearchUrisRequest",
"request",
"=",
"SearchUrisRequest",
".",
"newBuilder",
"(",
")",
".",
"setUri",
"(",
"uri",
")",
".... | This method is used to check whether a URI is on a given threatList.
<p>Sample code:
<pre><code>
try (WebRiskServiceV1Beta1Client webRiskServiceV1Beta1Client = WebRiskServiceV1Beta1Client.create()) {
String uri = "";
List<ThreatType> threatTypes = new ArrayList<>();
SearchUrisResponse response = webRiskServiceV1Beta1Client.searchUris(uri, threatTypes);
}
</code></pre>
@param uri The URI to be checked for matches.
@param threatTypes Required. The ThreatLists to search in.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"This",
"method",
"is",
"used",
"to",
"check",
"whether",
"a",
"URI",
"is",
"on",
"a",
"given",
"threatList",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-webrisk/src/main/java/com/google/cloud/webrisk/v1beta1/WebRiskServiceV1Beta1Client.java#L264-L269 |
cdk/cdk | base/dict/src/main/java/org/openscience/cdk/dict/EntryReact.java | EntryReact.setParameters | public void setParameters(String nameParam, String typeParam, String value) {
this.parameters.put(nameParam, typeParam);
this.parametersValue.add(value);
} | java | public void setParameters(String nameParam, String typeParam, String value) {
this.parameters.put(nameParam, typeParam);
this.parametersValue.add(value);
} | [
"public",
"void",
"setParameters",
"(",
"String",
"nameParam",
",",
"String",
"typeParam",
",",
"String",
"value",
")",
"{",
"this",
".",
"parameters",
".",
"put",
"(",
"nameParam",
",",
"typeParam",
")",
";",
"this",
".",
"parametersValue",
".",
"add",
"(... | Set the parameters of the reaction.
@param nameParam The parameter names of the reaction as String
@param typeParam The parameter types of the reaction as String
@param value The value default of the parameter | [
"Set",
"the",
"parameters",
"of",
"the",
"reaction",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/dict/src/main/java/org/openscience/cdk/dict/EntryReact.java#L108-L111 |
FudanNLP/fnlp | fnlp-core/src/main/java/org/fnlp/nlp/corpus/fnlp/FNLPCorpus.java | FNLPCorpus.readPOS | public void readPOS(String path, String suffix, String charset) throws IOException {
List<File> files = MyFiles.getAllFiles(path, suffix);//".txt"
Iterator<File> it = files.iterator();
while(it.hasNext()){
BufferedReader bfr =null;
File file = it.next();
try {
FileInputStream in = new FileInputStream(file);
bfr = new BufferedReader(new UnicodeReader(in,charset));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FNLPDoc doc = new FNLPDoc();
doc.name = file.getName();
String line = null;
while ((line = bfr.readLine()) != null) {
line = line.trim();
if (line.matches("^$"))
continue;
FNLPSent sent = new FNLPSent();
sent.parseTagedLine(line);
doc.add(sent);
}
add(doc);
}
} | java | public void readPOS(String path, String suffix, String charset) throws IOException {
List<File> files = MyFiles.getAllFiles(path, suffix);//".txt"
Iterator<File> it = files.iterator();
while(it.hasNext()){
BufferedReader bfr =null;
File file = it.next();
try {
FileInputStream in = new FileInputStream(file);
bfr = new BufferedReader(new UnicodeReader(in,charset));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FNLPDoc doc = new FNLPDoc();
doc.name = file.getName();
String line = null;
while ((line = bfr.readLine()) != null) {
line = line.trim();
if (line.matches("^$"))
continue;
FNLPSent sent = new FNLPSent();
sent.parseTagedLine(line);
doc.add(sent);
}
add(doc);
}
} | [
"public",
"void",
"readPOS",
"(",
"String",
"path",
",",
"String",
"suffix",
",",
"String",
"charset",
")",
"throws",
"IOException",
"{",
"List",
"<",
"File",
">",
"files",
"=",
"MyFiles",
".",
"getAllFiles",
"(",
"path",
",",
"suffix",
")",
";",
"//\".t... | 读分词/词性的文件
文件格式为:
word1/pos1 word2/pos2 ... wordn/posn
@param path
@param suffix
@param charset
@throws IOException | [
"读分词",
"/",
"词性的文件",
"文件格式为:",
"word1",
"/",
"pos1",
"word2",
"/",
"pos2",
"...",
"wordn",
"/",
"posn"
] | train | https://github.com/FudanNLP/fnlp/blob/ce258f3e4a5add2ba0b5e4cbac7cab2190af6659/fnlp-core/src/main/java/org/fnlp/nlp/corpus/fnlp/FNLPCorpus.java#L255-L282 |
negusoft/holoaccent | HoloAccent/src/com/negusoft/holoaccent/util/BitmapUtils.java | BitmapUtils.processTintTransformationMap | public static Bitmap processTintTransformationMap(Bitmap transformationMap, int tintColor) {
// tint color
int[] t = new int[] {
Color.red(tintColor),
Color.green(tintColor),
Color.blue(tintColor) };
int width = transformationMap.getWidth();
int height = transformationMap.getHeight();
int[] pixels = new int[width * height];
transformationMap.getPixels(pixels, 0, width, 0, 0, width, height);
float[] transformation = new float[2];
for (int i=0; i<pixels.length; i++) {
int color = pixels[i];
int alpha = Color.alpha(color);
transformation[0] = Color.red(color) / 255f;
transformation[1] = Color.green(color) / 255f;
pixels[i] = applyTransformation(t, alpha, transformation);
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
} | java | public static Bitmap processTintTransformationMap(Bitmap transformationMap, int tintColor) {
// tint color
int[] t = new int[] {
Color.red(tintColor),
Color.green(tintColor),
Color.blue(tintColor) };
int width = transformationMap.getWidth();
int height = transformationMap.getHeight();
int[] pixels = new int[width * height];
transformationMap.getPixels(pixels, 0, width, 0, 0, width, height);
float[] transformation = new float[2];
for (int i=0; i<pixels.length; i++) {
int color = pixels[i];
int alpha = Color.alpha(color);
transformation[0] = Color.red(color) / 255f;
transformation[1] = Color.green(color) / 255f;
pixels[i] = applyTransformation(t, alpha, transformation);
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
} | [
"public",
"static",
"Bitmap",
"processTintTransformationMap",
"(",
"Bitmap",
"transformationMap",
",",
"int",
"tintColor",
")",
"{",
"// tint color",
"int",
"[",
"]",
"t",
"=",
"new",
"int",
"[",
"]",
"{",
"Color",
".",
"red",
"(",
"tintColor",
")",
",",
"... | Apply the given tint color to the transformation map.
@param transformationMap A bitmap representing the transformation map.
@param tintColor Tint color to be applied.
@return A bitmap with the with the tint color set. | [
"Apply",
"the",
"given",
"tint",
"color",
"to",
"the",
"transformation",
"map",
"."
] | train | https://github.com/negusoft/holoaccent/blob/7121a02dde94834e770cb81174d0bdc596323324/HoloAccent/src/com/negusoft/holoaccent/util/BitmapUtils.java#L160-L182 |
forge/core | javaee/scaffold-faces/src/main/java/org/jboss/forge/addon/scaffold/faces/metawidget/widgetbuilder/EntityWidgetBuilder.java | EntityWidgetBuilder.addSelectItems | @Override
protected void addSelectItems(HtmlSelectOneMenu select, String valueExpression, Map<String, String> attributes)
{
// Empty option
//
// Note: a 'null' value (rather than an empty String') renders an <f:selectItem/> rather
// than an <f:selectItem itemValue=""/>. This works out better if the HtmlSelectOneMenu has
// a converter, because the empty String may not be a compatible value
if (WidgetBuilderUtils.needsEmptyLookupItem(attributes))
{
addSelectItem(select, null, null);
}
// Add the select items
SelectItems selectItems = new SelectItems();
selectItems.putAttribute("value", valueExpression);
// For each item to be displayed, set the label to the reverse primary key value
if (attributes.containsKey(REVERSE_PRIMARY_KEY))
{
selectItems.putAttribute("var", SELECT_ITEM);
selectItems.putAttribute("itemValue", StaticFacesUtils.wrapExpression(SELECT_ITEM));
String displayExpression = "forgeview:display(_item)";
((BaseStaticXmlWidget) selectItems).putAdditionalNamespaceURI("forgeview", "http://jboss.org/forge/view");
selectItems.putAttribute("itemLabel", StaticFacesUtils.wrapExpression(displayExpression));
}
select.getChildren().add(selectItems);
} | java | @Override
protected void addSelectItems(HtmlSelectOneMenu select, String valueExpression, Map<String, String> attributes)
{
// Empty option
//
// Note: a 'null' value (rather than an empty String') renders an <f:selectItem/> rather
// than an <f:selectItem itemValue=""/>. This works out better if the HtmlSelectOneMenu has
// a converter, because the empty String may not be a compatible value
if (WidgetBuilderUtils.needsEmptyLookupItem(attributes))
{
addSelectItem(select, null, null);
}
// Add the select items
SelectItems selectItems = new SelectItems();
selectItems.putAttribute("value", valueExpression);
// For each item to be displayed, set the label to the reverse primary key value
if (attributes.containsKey(REVERSE_PRIMARY_KEY))
{
selectItems.putAttribute("var", SELECT_ITEM);
selectItems.putAttribute("itemValue", StaticFacesUtils.wrapExpression(SELECT_ITEM));
String displayExpression = "forgeview:display(_item)";
((BaseStaticXmlWidget) selectItems).putAdditionalNamespaceURI("forgeview", "http://jboss.org/forge/view");
selectItems.putAttribute("itemLabel", StaticFacesUtils.wrapExpression(displayExpression));
}
select.getChildren().add(selectItems);
} | [
"@",
"Override",
"protected",
"void",
"addSelectItems",
"(",
"HtmlSelectOneMenu",
"select",
",",
"String",
"valueExpression",
",",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"// Empty option",
"//",
"// Note: a 'null' value (rather than an empty S... | Overrriden to enhance the default f:selectItem widget with more suitable item labels | [
"Overrriden",
"to",
"enhance",
"the",
"default",
"f",
":",
"selectItem",
"widget",
"with",
"more",
"suitable",
"item",
"labels"
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/javaee/scaffold-faces/src/main/java/org/jboss/forge/addon/scaffold/faces/metawidget/widgetbuilder/EntityWidgetBuilder.java#L681-L712 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/schema/columns/DataColumnsDao.java | DataColumnsDao.getDataColumn | public DataColumns getDataColumn(String tableName, String columnName)
throws SQLException {
TableColumnKey id = new TableColumnKey(tableName, columnName);
return queryForId(id);
} | java | public DataColumns getDataColumn(String tableName, String columnName)
throws SQLException {
TableColumnKey id = new TableColumnKey(tableName, columnName);
return queryForId(id);
} | [
"public",
"DataColumns",
"getDataColumn",
"(",
"String",
"tableName",
",",
"String",
"columnName",
")",
"throws",
"SQLException",
"{",
"TableColumnKey",
"id",
"=",
"new",
"TableColumnKey",
"(",
"tableName",
",",
"columnName",
")",
";",
"return",
"queryForId",
"(",... | Get DataColumn by column name and table name
@param tableName
table name to query for
@param columnName
column name to query for
@return DataColumns
@throws SQLException
upon failure | [
"Get",
"DataColumn",
"by",
"column",
"name",
"and",
"table",
"name"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/schema/columns/DataColumnsDao.java#L204-L208 |
tvbarthel/Cheerleader | library/src/main/java/fr/tvbarthel/cheerleader/library/player/NotificationManager.java | NotificationManager.loadArtwork | private void loadArtwork(final Context context, final String artworkUrl) {
if (mLoadArtworkRunnable != null) {
mMainThreadHandler.removeCallbacks(mLoadArtworkRunnable);
}
mLoadArtworkRunnable = new Runnable() {
@Override
public void run() {
final Picasso picasso = Picasso.with(context);
picasso.cancelRequest(mThumbnailArtworkTarget);
picasso.load(artworkUrl)
.centerCrop()
.resize(mArtworkBitmapSize, mArtworkBitmapSize)
.into(mThumbnailArtworkTarget);
}
};
mMainThreadHandler.postDelayed(mLoadArtworkRunnable, LOAD_ARTWORK_DELAY);
} | java | private void loadArtwork(final Context context, final String artworkUrl) {
if (mLoadArtworkRunnable != null) {
mMainThreadHandler.removeCallbacks(mLoadArtworkRunnable);
}
mLoadArtworkRunnable = new Runnable() {
@Override
public void run() {
final Picasso picasso = Picasso.with(context);
picasso.cancelRequest(mThumbnailArtworkTarget);
picasso.load(artworkUrl)
.centerCrop()
.resize(mArtworkBitmapSize, mArtworkBitmapSize)
.into(mThumbnailArtworkTarget);
}
};
mMainThreadHandler.postDelayed(mLoadArtworkRunnable, LOAD_ARTWORK_DELAY);
} | [
"private",
"void",
"loadArtwork",
"(",
"final",
"Context",
"context",
",",
"final",
"String",
"artworkUrl",
")",
"{",
"if",
"(",
"mLoadArtworkRunnable",
"!=",
"null",
")",
"{",
"mMainThreadHandler",
".",
"removeCallbacks",
"(",
"mLoadArtworkRunnable",
")",
";",
... | Load the track artwork.
@param context context used by {@link com.squareup.picasso.Picasso} to load the artwork asynchronously.
@param artworkUrl artwork url of the track. | [
"Load",
"the",
"track",
"artwork",
"."
] | train | https://github.com/tvbarthel/Cheerleader/blob/f61527e4cc44fcd0ed2e1e98aca285f8c236f24e/library/src/main/java/fr/tvbarthel/cheerleader/library/player/NotificationManager.java#L398-L416 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/UpdateBuilder.java | UpdateBuilder.set | @Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
return set(documentReference, pojo, SetOptions.OVERWRITE);
} | java | @Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
return set(documentReference, pojo, SetOptions.OVERWRITE);
} | [
"@",
"Nonnull",
"public",
"T",
"set",
"(",
"@",
"Nonnull",
"DocumentReference",
"documentReference",
",",
"@",
"Nonnull",
"Object",
"pojo",
")",
"{",
"return",
"set",
"(",
"documentReference",
",",
"pojo",
",",
"SetOptions",
".",
"OVERWRITE",
")",
";",
"}"
] | Overwrites the document referred to by this DocumentReference. If the document doesn't exist
yet, it will be created. If a document already exists, it will be overwritten.
@param documentReference The DocumentReference to overwrite.
@param pojo The POJO that will be used to populate the document contents.
@return The instance for chaining. | [
"Overwrites",
"the",
"document",
"referred",
"to",
"by",
"this",
"DocumentReference",
".",
"If",
"the",
"document",
"doesn",
"t",
"exist",
"yet",
"it",
"will",
"be",
"created",
".",
"If",
"a",
"document",
"already",
"exists",
"it",
"will",
"be",
"overwritten... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/UpdateBuilder.java#L204-L207 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/builder/SqlInfoBuilder.java | SqlInfoBuilder.buildBetweenSql | public SqlInfo buildBetweenSql(String fieldText, Object startValue, Object endValue) {
/* 根据开始文本和结束文本判断执行是大于、小于还是区间的查询sql和参数的生成 */
if (startValue != null && endValue == null) {
join.append(prefix).append(fieldText).append(ZealotConst.GTE_SUFFIX);
params.add(startValue);
} else if (startValue == null && endValue != null) {
join.append(prefix).append(fieldText).append(ZealotConst.LTE_SUFFIX);
params.add(endValue);
} else {
join.append(prefix).append(fieldText).append(ZealotConst.BT_AND_SUFFIX);
params.add(startValue);
params.add(endValue);
}
return sqlInfo.setJoin(join).setParams(params);
} | java | public SqlInfo buildBetweenSql(String fieldText, Object startValue, Object endValue) {
/* 根据开始文本和结束文本判断执行是大于、小于还是区间的查询sql和参数的生成 */
if (startValue != null && endValue == null) {
join.append(prefix).append(fieldText).append(ZealotConst.GTE_SUFFIX);
params.add(startValue);
} else if (startValue == null && endValue != null) {
join.append(prefix).append(fieldText).append(ZealotConst.LTE_SUFFIX);
params.add(endValue);
} else {
join.append(prefix).append(fieldText).append(ZealotConst.BT_AND_SUFFIX);
params.add(startValue);
params.add(endValue);
}
return sqlInfo.setJoin(join).setParams(params);
} | [
"public",
"SqlInfo",
"buildBetweenSql",
"(",
"String",
"fieldText",
",",
"Object",
"startValue",
",",
"Object",
"endValue",
")",
"{",
"/* 根据开始文本和结束文本判断执行是大于、小于还是区间的查询sql和参数的生成 */",
"if",
"(",
"startValue",
"!=",
"null",
"&&",
"endValue",
"==",
"null",
")",
"{",
"j... | 构建区间查询的SqlInfo信息.
@param fieldText 数据库字段文本
@param startValue 参数开始值
@param endValue 参数结束值
@return 返回SqlInfo信息 | [
"构建区间查询的SqlInfo信息",
"."
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/builder/SqlInfoBuilder.java#L111-L126 |
Crab2died/Excel4J | src/main/java/com/github/crab2died/ExcelUtils.java | ExcelUtils.simpleSheet2Excel | public void simpleSheet2Excel(List<SimpleSheetWrapper> sheets, boolean isXSSF, OutputStream os)
throws IOException {
try (Workbook workbook = exportExcelBySimpleHandler(sheets, isXSSF)) {
workbook.write(os);
}
} | java | public void simpleSheet2Excel(List<SimpleSheetWrapper> sheets, boolean isXSSF, OutputStream os)
throws IOException {
try (Workbook workbook = exportExcelBySimpleHandler(sheets, isXSSF)) {
workbook.write(os);
}
} | [
"public",
"void",
"simpleSheet2Excel",
"(",
"List",
"<",
"SimpleSheetWrapper",
">",
"sheets",
",",
"boolean",
"isXSSF",
",",
"OutputStream",
"os",
")",
"throws",
"IOException",
"{",
"try",
"(",
"Workbook",
"workbook",
"=",
"exportExcelBySimpleHandler",
"(",
"sheet... | 无模板、无注解、多sheet数据
@param sheets 待导出sheet数据
@param isXSSF 导出的Excel是否为Excel2007及以上版本(默认是)
@param os 生成的Excel待输出数据流
@throws IOException 异常 | [
"无模板、无注解、多sheet数据"
] | train | https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/ExcelUtils.java#L1435-L1441 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java | JDBC4DatabaseMetaData.getSuperTypes | @Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException
{
checkClosed();
throw SQLError.noSupport();
} | java | @Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException
{
checkClosed();
throw SQLError.noSupport();
} | [
"@",
"Override",
"public",
"ResultSet",
"getSuperTypes",
"(",
"String",
"catalog",
",",
"String",
"schemaPattern",
",",
"String",
"typeNamePattern",
")",
"throws",
"SQLException",
"{",
"checkClosed",
"(",
")",
";",
"throw",
"SQLError",
".",
"noSupport",
"(",
")"... | Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema in this database. | [
"Retrieves",
"a",
"description",
"of",
"the",
"user",
"-",
"defined",
"type",
"(",
"UDT",
")",
"hierarchies",
"defined",
"in",
"a",
"particular",
"schema",
"in",
"this",
"database",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java#L772-L777 |
JetBrains/xodus | entity-store/src/main/java/jetbrains/exodus/entitystore/tables/PropertiesTable.java | PropertiesTable.put | public void put(@NotNull final PersistentStoreTransaction txn,
final long localId,
@NotNull final ByteIterable value,
@Nullable final ByteIterable oldValue,
final int propertyId,
@NotNull final ComparableValueType type) {
final Store valueIdx = getOrCreateValueIndex(txn, propertyId);
final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));
final Transaction envTxn = txn.getEnvironmentTransaction();
primaryStore.put(envTxn, key, value);
final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);
boolean success;
if (oldValue == null) {
success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);
} else {
success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));
}
if (success) {
for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {
valueIdx.put(envTxn, secondaryKey, secondaryValue);
}
}
checkStatus(success, "Failed to put");
} | java | public void put(@NotNull final PersistentStoreTransaction txn,
final long localId,
@NotNull final ByteIterable value,
@Nullable final ByteIterable oldValue,
final int propertyId,
@NotNull final ComparableValueType type) {
final Store valueIdx = getOrCreateValueIndex(txn, propertyId);
final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));
final Transaction envTxn = txn.getEnvironmentTransaction();
primaryStore.put(envTxn, key, value);
final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);
boolean success;
if (oldValue == null) {
success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);
} else {
success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));
}
if (success) {
for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {
valueIdx.put(envTxn, secondaryKey, secondaryValue);
}
}
checkStatus(success, "Failed to put");
} | [
"public",
"void",
"put",
"(",
"@",
"NotNull",
"final",
"PersistentStoreTransaction",
"txn",
",",
"final",
"long",
"localId",
",",
"@",
"NotNull",
"final",
"ByteIterable",
"value",
",",
"@",
"Nullable",
"final",
"ByteIterable",
"oldValue",
",",
"final",
"int",
... | Setter for property value. Doesn't affect entity version and doesn't
invalidate any of the cached entity iterables.
@param localId entity local id.
@param value property value.
@param oldValue property old value
@param propertyId property id | [
"Setter",
"for",
"property",
"value",
".",
"Doesn",
"t",
"affect",
"entity",
"version",
"and",
"doesn",
"t",
"invalidate",
"any",
"of",
"the",
"cached",
"entity",
"iterables",
"."
] | train | https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/entity-store/src/main/java/jetbrains/exodus/entitystore/tables/PropertiesTable.java#L74-L97 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java | BNFHeadersImpl.getElement | private HeaderElement getElement(HeaderKeys key) {
HeaderElement elem = this.headerElements;
if (null != elem) {
// disconnect it from the rest of the free list
this.headerElements = elem.nextInstance;
elem.nextInstance = null;
elem.init(key);
} else {
elem = new HeaderElement(key, this);
}
return elem;
} | java | private HeaderElement getElement(HeaderKeys key) {
HeaderElement elem = this.headerElements;
if (null != elem) {
// disconnect it from the rest of the free list
this.headerElements = elem.nextInstance;
elem.nextInstance = null;
elem.init(key);
} else {
elem = new HeaderElement(key, this);
}
return elem;
} | [
"private",
"HeaderElement",
"getElement",
"(",
"HeaderKeys",
"key",
")",
"{",
"HeaderElement",
"elem",
"=",
"this",
".",
"headerElements",
";",
"if",
"(",
"null",
"!=",
"elem",
")",
"{",
"// disconnect it from the rest of the free list",
"this",
".",
"headerElements... | Get an empty object for the new header name/value instance.
@param key
@return HeaderElement | [
"Get",
"an",
"empty",
"object",
"for",
"the",
"new",
"header",
"name",
"/",
"value",
"instance",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java#L2137-L2148 |
hap-java/HAP-Java | src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java | HomekitSRP6Routines.createRandomBigIntegerInRange | protected static BigInteger createRandomBigIntegerInRange(
final BigInteger min, final BigInteger max, final SecureRandom random) {
final int cmp = min.compareTo(max);
if (cmp >= 0) {
if (cmp > 0) throw new IllegalArgumentException("'min' may not be greater than 'max'");
return min;
}
if (min.bitLength() > max.bitLength() / 2)
return createRandomBigIntegerInRange(BigInteger.ZERO, max.subtract(min), random).add(min);
final int MAX_ITERATIONS = 1000;
for (int i = 0; i < MAX_ITERATIONS; ++i) {
BigInteger x = new BigInteger(max.bitLength(), random);
if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) return x;
}
// fall back to a faster (restricted) method
return new BigInteger(max.subtract(min).bitLength() - 1, random).add(min);
} | java | protected static BigInteger createRandomBigIntegerInRange(
final BigInteger min, final BigInteger max, final SecureRandom random) {
final int cmp = min.compareTo(max);
if (cmp >= 0) {
if (cmp > 0) throw new IllegalArgumentException("'min' may not be greater than 'max'");
return min;
}
if (min.bitLength() > max.bitLength() / 2)
return createRandomBigIntegerInRange(BigInteger.ZERO, max.subtract(min), random).add(min);
final int MAX_ITERATIONS = 1000;
for (int i = 0; i < MAX_ITERATIONS; ++i) {
BigInteger x = new BigInteger(max.bitLength(), random);
if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) return x;
}
// fall back to a faster (restricted) method
return new BigInteger(max.subtract(min).bitLength() - 1, random).add(min);
} | [
"protected",
"static",
"BigInteger",
"createRandomBigIntegerInRange",
"(",
"final",
"BigInteger",
"min",
",",
"final",
"BigInteger",
"max",
",",
"final",
"SecureRandom",
"random",
")",
"{",
"final",
"int",
"cmp",
"=",
"min",
".",
"compareTo",
"(",
"max",
")",
... | Returns a random big integer in the specified range [min, max].
@param min The least value that may be generated. Must not be {@code null}.
@param max The greatest value that may be generated. Must not be {@code null}.
@param random Source of randomness. Must not be {@code null}.
@return A random big integer in the range [min, max]. | [
"Returns",
"a",
"random",
"big",
"integer",
"in",
"the",
"specified",
"range",
"[",
"min",
"max",
"]",
"."
] | train | https://github.com/hap-java/HAP-Java/blob/d2b2f4f1579580a2b5958af3a192128345843db9/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java#L31-L57 |
geomajas/geomajas-project-client-gwt | plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java | MultiLayerFeaturesList.addFeature | private boolean addFeature(Feature feature, Layer<?> layer) {
// Basic checks:
if (feature == null || layer == null ) {
return false;
}
// Feature checks out, add it to the grid:
ListGridRecord record = new ListGridRecord();
if (layer instanceof VectorLayer) {
record.setAttribute(LABEL, getLabel(feature));
} else if (layer instanceof RasterLayer) {
record.setAttribute(LABEL, feature.getId());
}
record.setAttribute(FEATURE_ID, getFullFeatureId(feature, layer));
record.setAttribute(LAYER_ID, layer.getId());
record.setAttribute(LAYER_LABEL, layer.getLabel());
addData(record);
return true;
} | java | private boolean addFeature(Feature feature, Layer<?> layer) {
// Basic checks:
if (feature == null || layer == null ) {
return false;
}
// Feature checks out, add it to the grid:
ListGridRecord record = new ListGridRecord();
if (layer instanceof VectorLayer) {
record.setAttribute(LABEL, getLabel(feature));
} else if (layer instanceof RasterLayer) {
record.setAttribute(LABEL, feature.getId());
}
record.setAttribute(FEATURE_ID, getFullFeatureId(feature, layer));
record.setAttribute(LAYER_ID, layer.getId());
record.setAttribute(LAYER_LABEL, layer.getLabel());
addData(record);
return true;
} | [
"private",
"boolean",
"addFeature",
"(",
"Feature",
"feature",
",",
"Layer",
"<",
"?",
">",
"layer",
")",
"{",
"// Basic checks:",
"if",
"(",
"feature",
"==",
"null",
"||",
"layer",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"// Feature checks ou... | Adds a new feature to the grid list. A {@link VectorLayer} must have been
set first, and the feature must belong to that VectorLayer.
@param feature
The feature to be added to the grid list.
@return Returns true in case of success, and false if the feature is null
or if the feature does not belong to the correct layer or if the
layer has not yet been set. | [
"Adds",
"a",
"new",
"feature",
"to",
"the",
"grid",
"list",
".",
"A",
"{",
"@link",
"VectorLayer",
"}",
"must",
"have",
"been",
"set",
"first",
"and",
"the",
"feature",
"must",
"belong",
"to",
"that",
"VectorLayer",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java#L163-L180 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/ServerRequest.java | ServerRequest.fromJSON | public static ServerRequest fromJSON(JSONObject json, Context context) {
JSONObject post = null;
String requestPath = "";
try {
if (json.has(POST_KEY)) {
post = json.getJSONObject(POST_KEY);
}
} catch (JSONException e) {
// it's OK for post to be null
}
try {
if (json.has(POST_PATH_KEY)) {
requestPath = json.getString(POST_PATH_KEY);
}
} catch (JSONException e) {
// it's OK for post to be null
}
if (requestPath != null && requestPath.length() > 0) {
return getExtendedServerRequest(requestPath, post, context);
}
return null;
} | java | public static ServerRequest fromJSON(JSONObject json, Context context) {
JSONObject post = null;
String requestPath = "";
try {
if (json.has(POST_KEY)) {
post = json.getJSONObject(POST_KEY);
}
} catch (JSONException e) {
// it's OK for post to be null
}
try {
if (json.has(POST_PATH_KEY)) {
requestPath = json.getString(POST_PATH_KEY);
}
} catch (JSONException e) {
// it's OK for post to be null
}
if (requestPath != null && requestPath.length() > 0) {
return getExtendedServerRequest(requestPath, post, context);
}
return null;
} | [
"public",
"static",
"ServerRequest",
"fromJSON",
"(",
"JSONObject",
"json",
",",
"Context",
"context",
")",
"{",
"JSONObject",
"post",
"=",
"null",
";",
"String",
"requestPath",
"=",
"\"\"",
";",
"try",
"{",
"if",
"(",
"json",
".",
"has",
"(",
"POST_KEY",
... | <p>Converts a {@link JSONObject} object containing keys stored as key-value pairs into
a {@link ServerRequest}.</p>
@param json A {@link JSONObject} object containing post data stored as key-value pairs
@param context Application context.
@return A {@link ServerRequest} object with the {@link #POST_KEY}
values set if not null; this can be one or the other. If both values in the
supplied {@link JSONObject} are null, null is returned instead of an object. | [
"<p",
">",
"Converts",
"a",
"{",
"@link",
"JSONObject",
"}",
"object",
"containing",
"keys",
"stored",
"as",
"key",
"-",
"value",
"pairs",
"into",
"a",
"{",
"@link",
"ServerRequest",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ServerRequest.java#L302-L325 |
cogroo/cogroo4 | cogroo-gc/src/main/java/org/cogroo/tools/checker/checkers/SpaceChecker.java | SpaceChecker.getsSupposedError | private String getsSupposedError(String text, int position) {
int ini;
boolean end = false;
String word = text;
// Indicates where the position of the supposed word begin
for (ini = position; ini >= 0; ini--)
if (Character.isWhitespace(text.charAt(ini))
|| isOpenBracket(text.charAt(ini)))
break;
// Indicates where the supposed word should end
for (int i = position + 1; i < text.length() && end == false; i++) {
switch (text.charAt(i)) {
// Indicates the end of the supposed error
case ' ':
case '!':
case '?':
case ',':
case ';':
case ')':
case ']':
case '}':
case '”':
case '\n':
// The supposed e-mail is attributed in its proper variable
word = word.substring(ini + 1, i);
end = true;
break;
// Possible end of sentence or just part of the supposed error
case '.':
if (Character.isWhitespace(text.charAt(i + 1))) {
word = word.substring(ini + 1, i);
end = true;
break;
}
// Character or digit that is part of the supposed error
default:
break;
}
}
return word;
} | java | private String getsSupposedError(String text, int position) {
int ini;
boolean end = false;
String word = text;
// Indicates where the position of the supposed word begin
for (ini = position; ini >= 0; ini--)
if (Character.isWhitespace(text.charAt(ini))
|| isOpenBracket(text.charAt(ini)))
break;
// Indicates where the supposed word should end
for (int i = position + 1; i < text.length() && end == false; i++) {
switch (text.charAt(i)) {
// Indicates the end of the supposed error
case ' ':
case '!':
case '?':
case ',':
case ';':
case ')':
case ']':
case '}':
case '”':
case '\n':
// The supposed e-mail is attributed in its proper variable
word = word.substring(ini + 1, i);
end = true;
break;
// Possible end of sentence or just part of the supposed error
case '.':
if (Character.isWhitespace(text.charAt(i + 1))) {
word = word.substring(ini + 1, i);
end = true;
break;
}
// Character or digit that is part of the supposed error
default:
break;
}
}
return word;
} | [
"private",
"String",
"getsSupposedError",
"(",
"String",
"text",
",",
"int",
"position",
")",
"{",
"int",
"ini",
";",
"boolean",
"end",
"=",
"false",
";",
"String",
"word",
"=",
"text",
";",
"// Indicates where the position of the supposed word begin\r",
"for",
"(... | Analyze a sentence and gets the word which contains the position of the
error in the parameter
@param text
the entire sentence to be analyzed
@param position
where in the sentence the supposed error was found
@return the word which contains the supposed error | [
"Analyze",
"a",
"sentence",
"and",
"gets",
"the",
"word",
"which",
"contains",
"the",
"position",
"of",
"the",
"error",
"in",
"the",
"parameter"
] | train | https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-gc/src/main/java/org/cogroo/tools/checker/checkers/SpaceChecker.java#L227-L273 |
atomix/atomix | protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java | CrdtSetDelegate.updateElements | private void updateElements(Map<String, SetElement> elements) {
for (SetElement element : elements.values()) {
if (element.isTombstone()) {
if (remove(element)) {
eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value()))));
}
} else {
if (add(element)) {
eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value()))));
}
}
}
} | java | private void updateElements(Map<String, SetElement> elements) {
for (SetElement element : elements.values()) {
if (element.isTombstone()) {
if (remove(element)) {
eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value()))));
}
} else {
if (add(element)) {
eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value()))));
}
}
}
} | [
"private",
"void",
"updateElements",
"(",
"Map",
"<",
"String",
",",
"SetElement",
">",
"elements",
")",
"{",
"for",
"(",
"SetElement",
"element",
":",
"elements",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"element",
".",
"isTombstone",
"(",
")",
"... | Updates the set elements.
@param elements the elements to update | [
"Updates",
"the",
"set",
"elements",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L226-L238 |
alkacon/opencms-core | src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java | CmsEditablePositionCalculator.handleCollision | protected void handleCollision(CmsPositionBean p1, CmsPositionBean p2) {
CmsPositionBean positionToChange = p1;
if (p1.getTop() <= p2.getTop()) {
positionToChange = p2;
}
positionToChange.setTop(positionToChange.getTop() + 25);
} | java | protected void handleCollision(CmsPositionBean p1, CmsPositionBean p2) {
CmsPositionBean positionToChange = p1;
if (p1.getTop() <= p2.getTop()) {
positionToChange = p2;
}
positionToChange.setTop(positionToChange.getTop() + 25);
} | [
"protected",
"void",
"handleCollision",
"(",
"CmsPositionBean",
"p1",
",",
"CmsPositionBean",
"p2",
")",
"{",
"CmsPositionBean",
"positionToChange",
"=",
"p1",
";",
"if",
"(",
"p1",
".",
"getTop",
"(",
")",
"<=",
"p2",
".",
"getTop",
"(",
")",
")",
"{",
... | Handles a collision by moving the lower position down.<p>
@param p1 the first position
@param p2 the second position | [
"Handles",
"a",
"collision",
"by",
"moving",
"the",
"lower",
"position",
"down",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java#L140-L147 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestApiClient.java | RestApiClient.addOutcast | public Response addOutcast(String roomName, String jid) {
return restClient.post("chatrooms/" + roomName + "/outcasts/" + jid, null, new HashMap<String, String>());
} | java | public Response addOutcast(String roomName, String jid) {
return restClient.post("chatrooms/" + roomName + "/outcasts/" + jid, null, new HashMap<String, String>());
} | [
"public",
"Response",
"addOutcast",
"(",
"String",
"roomName",
",",
"String",
"jid",
")",
"{",
"return",
"restClient",
".",
"post",
"(",
"\"chatrooms/\"",
"+",
"roomName",
"+",
"\"/outcasts/\"",
"+",
"jid",
",",
"null",
",",
"new",
"HashMap",
"<",
"String",
... | Adds the outcast.
@param roomName
the room name
@param jid
the jid
@return the response | [
"Adds",
"the",
"outcast",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L329-L331 |
btrplace/scheduler | choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java | VectorPackingPropagator.propagate | @Override
public void propagate(int idx, int mask) throws ContradictionException {
if (idx < bins.length) {
deltaMonitor[idx].freeze();
deltaMonitor[idx].forEachRemVal(remProc.set(idx));
deltaMonitor[idx].unfreeze();
if (vars[idx].isInstantiated()) {
assignItem(idx, vars[idx].getValue());
}
} else {
loadsHaveChanged.set(true);
}
forcePropagate(PropagatorEventType.CUSTOM_PROPAGATION);
} | java | @Override
public void propagate(int idx, int mask) throws ContradictionException {
if (idx < bins.length) {
deltaMonitor[idx].freeze();
deltaMonitor[idx].forEachRemVal(remProc.set(idx));
deltaMonitor[idx].unfreeze();
if (vars[idx].isInstantiated()) {
assignItem(idx, vars[idx].getValue());
}
} else {
loadsHaveChanged.set(true);
}
forcePropagate(PropagatorEventType.CUSTOM_PROPAGATION);
} | [
"@",
"Override",
"public",
"void",
"propagate",
"(",
"int",
"idx",
",",
"int",
"mask",
")",
"throws",
"ContradictionException",
"{",
"if",
"(",
"idx",
"<",
"bins",
".",
"length",
")",
"{",
"deltaMonitor",
"[",
"idx",
"]",
".",
"freeze",
"(",
")",
";",
... | fine grain propagation
- if the event concerns a bin variable, then update data and apply rule 2:
on the assigned bin: binAssignedLoad <= binLoad <= binPotentialLoad
- otherwise remember to recompute the load sums and do nothing
@param idx the variable index
@param mask the event mask
@throws ContradictionException if a contradiction (rule 2) is raised | [
"fine",
"grain",
"propagation",
"-",
"if",
"the",
"event",
"concerns",
"a",
"bin",
"variable",
"then",
"update",
"data",
"and",
"apply",
"rule",
"2",
":",
"on",
"the",
"assigned",
"bin",
":",
"binAssignedLoad",
"<",
"=",
"binLoad",
"<",
"=",
"binPotentialL... | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java#L345-L358 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/validation/SARLValidator.java | SARLValidator.isLocallyAssigned | protected boolean isLocallyAssigned(EObject target, EObject containerToFindUsage) {
if (this.readAndWriteTracking.isAssigned(target)) {
return true;
}
final Collection<Setting> usages = XbaseUsageCrossReferencer.find(target, containerToFindUsage);
// field are assigned when they are not used as the left operand of an assignment operator.
for (final Setting usage : usages) {
final EObject object = usage.getEObject();
if (object instanceof XAssignment) {
final XAssignment assignment = (XAssignment) object;
if (assignment.getFeature() == target) {
// Mark the field as assigned in order to be faster during the next assignment test.
this.readAndWriteTracking.markAssignmentAccess(target);
return true;
}
}
}
return false;
} | java | protected boolean isLocallyAssigned(EObject target, EObject containerToFindUsage) {
if (this.readAndWriteTracking.isAssigned(target)) {
return true;
}
final Collection<Setting> usages = XbaseUsageCrossReferencer.find(target, containerToFindUsage);
// field are assigned when they are not used as the left operand of an assignment operator.
for (final Setting usage : usages) {
final EObject object = usage.getEObject();
if (object instanceof XAssignment) {
final XAssignment assignment = (XAssignment) object;
if (assignment.getFeature() == target) {
// Mark the field as assigned in order to be faster during the next assignment test.
this.readAndWriteTracking.markAssignmentAccess(target);
return true;
}
}
}
return false;
} | [
"protected",
"boolean",
"isLocallyAssigned",
"(",
"EObject",
"target",
",",
"EObject",
"containerToFindUsage",
")",
"{",
"if",
"(",
"this",
".",
"readAndWriteTracking",
".",
"isAssigned",
"(",
"target",
")",
")",
"{",
"return",
"true",
";",
"}",
"final",
"Coll... | Replies if the given object is locally assigned.
<p>An object is locally assigned when it is the left operand of an assignment operation.
@param target the object to test.
@param containerToFindUsage the container in which the usages should be find.
@return {@code true} if the given object is assigned.
@since 0.7 | [
"Replies",
"if",
"the",
"given",
"object",
"is",
"locally",
"assigned",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/validation/SARLValidator.java#L2718-L2736 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/MenuUtil.java | MenuUtil.sortMenu | public static void sortMenu(BaseComponent parent, int startIndex, int endIndex) {
List<BaseComponent> items = parent.getChildren();
int bottom = startIndex + 1;
for (int i = startIndex; i < endIndex;) {
BaseComponent item1 = items.get(i++);
BaseComponent item2 = items.get(i);
if (item1 instanceof BaseMenuComponent && item2 instanceof BaseMenuComponent && ((BaseMenuComponent) item1)
.getLabel().compareToIgnoreCase(((BaseMenuComponent) item2).getLabel()) > 0) {
parent.swapChildren(i - 1, i);
if (i > bottom) {
i -= 2;
}
}
}
} | java | public static void sortMenu(BaseComponent parent, int startIndex, int endIndex) {
List<BaseComponent> items = parent.getChildren();
int bottom = startIndex + 1;
for (int i = startIndex; i < endIndex;) {
BaseComponent item1 = items.get(i++);
BaseComponent item2 = items.get(i);
if (item1 instanceof BaseMenuComponent && item2 instanceof BaseMenuComponent && ((BaseMenuComponent) item1)
.getLabel().compareToIgnoreCase(((BaseMenuComponent) item2).getLabel()) > 0) {
parent.swapChildren(i - 1, i);
if (i > bottom) {
i -= 2;
}
}
}
} | [
"public",
"static",
"void",
"sortMenu",
"(",
"BaseComponent",
"parent",
",",
"int",
"startIndex",
",",
"int",
"endIndex",
")",
"{",
"List",
"<",
"BaseComponent",
">",
"items",
"=",
"parent",
".",
"getChildren",
"(",
")",
";",
"int",
"bottom",
"=",
"startIn... | Alphabetically sorts a range of menu items.
@param parent Parent whose children are to be sorted alphabetically.
@param startIndex Index of first child to be sorted.
@param endIndex Index of last child to be sorted. | [
"Alphabetically",
"sorts",
"a",
"range",
"of",
"menu",
"items",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/MenuUtil.java#L127-L144 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPP14Reader.java | MPP14Reader.getCustomFieldOutlineCodeValue | private String getCustomFieldOutlineCodeValue(Var2Data varData, Var2Data outlineCodeVarData, Integer id, Integer type)
{
String result = null;
int mask = varData.getShort(id, type);
if ((mask & 0xFF00) != VALUE_LIST_MASK)
{
result = outlineCodeVarData.getUnicodeString(Integer.valueOf(varData.getInt(id, 2, type)), OUTLINECODE_DATA);
}
else
{
int uniqueId = varData.getInt(id, 2, type);
CustomFieldValueItem item = m_file.getCustomFields().getCustomFieldValueItemByUniqueID(uniqueId);
if (item != null)
{
Object value = item.getValue();
if (value instanceof String)
{
result = (String) value;
}
String result2 = getCustomFieldOutlineCodeValue(varData, outlineCodeVarData, item.getParent());
if (result != null && result2 != null && !result2.isEmpty())
{
result = result2 + "." + result;
}
}
}
return result;
} | java | private String getCustomFieldOutlineCodeValue(Var2Data varData, Var2Data outlineCodeVarData, Integer id, Integer type)
{
String result = null;
int mask = varData.getShort(id, type);
if ((mask & 0xFF00) != VALUE_LIST_MASK)
{
result = outlineCodeVarData.getUnicodeString(Integer.valueOf(varData.getInt(id, 2, type)), OUTLINECODE_DATA);
}
else
{
int uniqueId = varData.getInt(id, 2, type);
CustomFieldValueItem item = m_file.getCustomFields().getCustomFieldValueItemByUniqueID(uniqueId);
if (item != null)
{
Object value = item.getValue();
if (value instanceof String)
{
result = (String) value;
}
String result2 = getCustomFieldOutlineCodeValue(varData, outlineCodeVarData, item.getParent());
if (result != null && result2 != null && !result2.isEmpty())
{
result = result2 + "." + result;
}
}
}
return result;
} | [
"private",
"String",
"getCustomFieldOutlineCodeValue",
"(",
"Var2Data",
"varData",
",",
"Var2Data",
"outlineCodeVarData",
",",
"Integer",
"id",
",",
"Integer",
"type",
")",
"{",
"String",
"result",
"=",
"null",
";",
"int",
"mask",
"=",
"varData",
".",
"getShort"... | Retrieve custom field value.
@param varData var data block
@param outlineCodeVarData var data block
@param id item ID
@param type item type
@return item value | [
"Retrieve",
"custom",
"field",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP14Reader.java#L1960-L1989 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/core/KerasFlatten.java | KerasFlatten.getInputPreprocessor | @Override
public InputPreProcessor getInputPreprocessor(InputType... inputType) throws InvalidKerasConfigurationException {
if (inputType.length > 1)
throw new InvalidKerasConfigurationException(
"Keras Flatten layer accepts only one input (received " + inputType.length + ")");
InputPreProcessor preprocessor = null;
if (inputType[0] instanceof InputTypeConvolutional) {
InputTypeConvolutional it = (InputTypeConvolutional) inputType[0];
switch (this.getDimOrder()) {
case NONE:
case THEANO:
preprocessor = new CnnToFeedForwardPreProcessor(it.getHeight(), it.getWidth(), it.getChannels());
break;
case TENSORFLOW:
preprocessor = new TensorFlowCnnToFeedForwardPreProcessor(it.getHeight(), it.getWidth(),
it.getChannels());
break;
default:
throw new InvalidKerasConfigurationException("Unknown Keras backend " + this.getDimOrder());
}
} else if (inputType[0] instanceof InputType.InputTypeRecurrent) {
InputType.InputTypeRecurrent it = (InputType.InputTypeRecurrent) inputType[0];
preprocessor = new KerasFlattenRnnPreprocessor(it.getSize(), it.getTimeSeriesLength());
} else if (inputType[0] instanceof InputType.InputTypeFeedForward) {
// NOTE: The output of an embedding layer in DL4J is of feed-forward type. Only if an FF to RNN input
// preprocessor is set or we explicitly provide 3D input data to start with, will the its output be set
// to RNN type. Otherwise we add this trivial preprocessor (since there's nothing to flatten).
InputType.InputTypeFeedForward it = (InputType.InputTypeFeedForward) inputType[0];
val inputShape = new long[]{it.getSize()};
preprocessor = new ReshapePreprocessor(inputShape, inputShape);
}
return preprocessor;
} | java | @Override
public InputPreProcessor getInputPreprocessor(InputType... inputType) throws InvalidKerasConfigurationException {
if (inputType.length > 1)
throw new InvalidKerasConfigurationException(
"Keras Flatten layer accepts only one input (received " + inputType.length + ")");
InputPreProcessor preprocessor = null;
if (inputType[0] instanceof InputTypeConvolutional) {
InputTypeConvolutional it = (InputTypeConvolutional) inputType[0];
switch (this.getDimOrder()) {
case NONE:
case THEANO:
preprocessor = new CnnToFeedForwardPreProcessor(it.getHeight(), it.getWidth(), it.getChannels());
break;
case TENSORFLOW:
preprocessor = new TensorFlowCnnToFeedForwardPreProcessor(it.getHeight(), it.getWidth(),
it.getChannels());
break;
default:
throw new InvalidKerasConfigurationException("Unknown Keras backend " + this.getDimOrder());
}
} else if (inputType[0] instanceof InputType.InputTypeRecurrent) {
InputType.InputTypeRecurrent it = (InputType.InputTypeRecurrent) inputType[0];
preprocessor = new KerasFlattenRnnPreprocessor(it.getSize(), it.getTimeSeriesLength());
} else if (inputType[0] instanceof InputType.InputTypeFeedForward) {
// NOTE: The output of an embedding layer in DL4J is of feed-forward type. Only if an FF to RNN input
// preprocessor is set or we explicitly provide 3D input data to start with, will the its output be set
// to RNN type. Otherwise we add this trivial preprocessor (since there's nothing to flatten).
InputType.InputTypeFeedForward it = (InputType.InputTypeFeedForward) inputType[0];
val inputShape = new long[]{it.getSize()};
preprocessor = new ReshapePreprocessor(inputShape, inputShape);
}
return preprocessor;
} | [
"@",
"Override",
"public",
"InputPreProcessor",
"getInputPreprocessor",
"(",
"InputType",
"...",
"inputType",
")",
"throws",
"InvalidKerasConfigurationException",
"{",
"if",
"(",
"inputType",
".",
"length",
">",
"1",
")",
"throw",
"new",
"InvalidKerasConfigurationExcept... | Gets appropriate DL4J InputPreProcessor for given InputTypes.
@param inputType Array of InputTypes
@return DL4J InputPreProcessor
@throws InvalidKerasConfigurationException Invalid Keras config
@see org.deeplearning4j.nn.conf.InputPreProcessor | [
"Gets",
"appropriate",
"DL4J",
"InputPreProcessor",
"for",
"given",
"InputTypes",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/core/KerasFlatten.java#L86-L118 |
opencb/biodata | biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java | ChunkFrequencyManager.getFileId | private int getFileId(Path filePath, Connection conn) throws SQLException {
int fileId = readFileId(filePath, conn);
if (fileId == -1) {
Statement stmt = conn.createStatement();
String insertFileSql = "insert into file (path, name) values ('" + filePath.getParent()
+ "', '" + filePath.getFileName() + "');";
stmt.executeUpdate(insertFileSql);
stmt.close();
fileId = readFileId(filePath, conn);
if (fileId == -1) {
throw new InternalError("Impossible to read the ID for the file " + filePath + " in database "
+ databasePath);
}
stmt.close();
}
return fileId;
} | java | private int getFileId(Path filePath, Connection conn) throws SQLException {
int fileId = readFileId(filePath, conn);
if (fileId == -1) {
Statement stmt = conn.createStatement();
String insertFileSql = "insert into file (path, name) values ('" + filePath.getParent()
+ "', '" + filePath.getFileName() + "');";
stmt.executeUpdate(insertFileSql);
stmt.close();
fileId = readFileId(filePath, conn);
if (fileId == -1) {
throw new InternalError("Impossible to read the ID for the file " + filePath + " in database "
+ databasePath);
}
stmt.close();
}
return fileId;
} | [
"private",
"int",
"getFileId",
"(",
"Path",
"filePath",
",",
"Connection",
"conn",
")",
"throws",
"SQLException",
"{",
"int",
"fileId",
"=",
"readFileId",
"(",
"filePath",
",",
"conn",
")",
";",
"if",
"(",
"fileId",
"==",
"-",
"1",
")",
"{",
"Statement",... | Read file ID from the database. If it does not exits, then insert it to the database and return the file ID.
@param filePath File to insert
@param conn Database connection
@return File ID in the database | [
"Read",
"file",
"ID",
"from",
"the",
"database",
".",
"If",
"it",
"does",
"not",
"exits",
"then",
"insert",
"it",
"to",
"the",
"database",
"and",
"return",
"the",
"file",
"ID",
"."
] | train | https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java#L558-L577 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/UrlMapClient.java | UrlMapClient.insertUrlMap | @BetaApi
public final Operation insertUrlMap(ProjectName project, UrlMap urlMapResource) {
InsertUrlMapHttpRequest request =
InsertUrlMapHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setUrlMapResource(urlMapResource)
.build();
return insertUrlMap(request);
} | java | @BetaApi
public final Operation insertUrlMap(ProjectName project, UrlMap urlMapResource) {
InsertUrlMapHttpRequest request =
InsertUrlMapHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setUrlMapResource(urlMapResource)
.build();
return insertUrlMap(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertUrlMap",
"(",
"ProjectName",
"project",
",",
"UrlMap",
"urlMapResource",
")",
"{",
"InsertUrlMapHttpRequest",
"request",
"=",
"InsertUrlMapHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setProject",
"(",
"proj... | Creates a UrlMap resource in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (UrlMapClient urlMapClient = UrlMapClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
UrlMap urlMapResource = UrlMap.newBuilder().build();
Operation response = urlMapClient.insertUrlMap(project, urlMapResource);
}
</code></pre>
@param project Project ID for this request.
@param urlMapResource A UrlMap resource. This resource defines the mapping from URL to the
BackendService resource, based on the "longest-match" of the URL's host and path.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"UrlMap",
"resource",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/UrlMapClient.java#L370-L379 |
spring-projects/spring-retry | src/main/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.java | ExceptionClassifierRetryPolicy.registerThrowable | public void registerThrowable(RetryContext context, Throwable throwable) {
RetryPolicy policy = (RetryPolicy) context;
policy.registerThrowable(context, throwable);
((RetryContextSupport) context).registerThrowable(throwable);
} | java | public void registerThrowable(RetryContext context, Throwable throwable) {
RetryPolicy policy = (RetryPolicy) context;
policy.registerThrowable(context, throwable);
((RetryContextSupport) context).registerThrowable(throwable);
} | [
"public",
"void",
"registerThrowable",
"(",
"RetryContext",
"context",
",",
"Throwable",
"throwable",
")",
"{",
"RetryPolicy",
"policy",
"=",
"(",
"RetryPolicy",
")",
"context",
";",
"policy",
".",
"registerThrowable",
"(",
"context",
",",
"throwable",
")",
";",... | Delegate to the policy currently activated in the context.
@see org.springframework.retry.RetryPolicy#registerThrowable(org.springframework.retry.RetryContext,
Throwable) | [
"Delegate",
"to",
"the",
"policy",
"currently",
"activated",
"in",
"the",
"context",
"."
] | train | https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.java#L102-L106 |
alkacon/opencms-core | src/org/opencms/site/CmsSiteManagerImpl.java | CmsSiteManagerImpl.getAvailableSites | public List<CmsSite> getAvailableSites(CmsObject cms, boolean workplaceMode) {
return getAvailableSites(cms, workplaceMode, cms.getRequestContext().getOuFqn());
} | java | public List<CmsSite> getAvailableSites(CmsObject cms, boolean workplaceMode) {
return getAvailableSites(cms, workplaceMode, cms.getRequestContext().getOuFqn());
} | [
"public",
"List",
"<",
"CmsSite",
">",
"getAvailableSites",
"(",
"CmsObject",
"cms",
",",
"boolean",
"workplaceMode",
")",
"{",
"return",
"getAvailableSites",
"(",
"cms",
",",
"workplaceMode",
",",
"cms",
".",
"getRequestContext",
"(",
")",
".",
"getOuFqn",
"(... | Returns a list of all sites available (visible) for the current user.<p>
@param cms the current OpenCms user context
@param workplaceMode if true, the root and current site is included for the admin user
and the view permission is required to see the site root
@return a list of all sites available for the current user | [
"Returns",
"a",
"list",
"of",
"all",
"sites",
"available",
"(",
"visible",
")",
"for",
"the",
"current",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/site/CmsSiteManagerImpl.java#L558-L561 |
facebookarchive/hadoop-20 | src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/InterleavedInputStream.java | InterleavedInputStream.rawSkip | protected boolean rawSkip(long bytes, boolean toNewSource) throws IOException {
boolean result = seekOrSkip(bytes, toNewSource);
setRawOffset(getRawOffset() + bytes);
// Check validity
if (rawBlockOffset > 0 && rawBlockOffset < metaDataBlockSize) {
throw new IOException("Cannot jump into the middle of a MetaDataBlock. MetaDataBlockSize = "
+ metaDataBlockSize + " and we are at " + rawBlockOffset);
}
return result;
} | java | protected boolean rawSkip(long bytes, boolean toNewSource) throws IOException {
boolean result = seekOrSkip(bytes, toNewSource);
setRawOffset(getRawOffset() + bytes);
// Check validity
if (rawBlockOffset > 0 && rawBlockOffset < metaDataBlockSize) {
throw new IOException("Cannot jump into the middle of a MetaDataBlock. MetaDataBlockSize = "
+ metaDataBlockSize + " and we are at " + rawBlockOffset);
}
return result;
} | [
"protected",
"boolean",
"rawSkip",
"(",
"long",
"bytes",
",",
"boolean",
"toNewSource",
")",
"throws",
"IOException",
"{",
"boolean",
"result",
"=",
"seekOrSkip",
"(",
"bytes",
",",
"toNewSource",
")",
";",
"setRawOffset",
"(",
"getRawOffset",
"(",
")",
"+",
... | Skip some bytes from the raw InputStream.
@param toNewSource - only useful when seekableIn is not null.
@return when toNewSource is true, return whether we seeked to a new source.
otherwise return true. | [
"Skip",
"some",
"bytes",
"from",
"the",
"raw",
"InputStream",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/InterleavedInputStream.java#L286-L297 |
geomajas/geomajas-project-server | impl/src/main/java/org/geomajas/internal/security/DefaultSecurityContext.java | DefaultSecurityContext.setAuthentications | @Api
public void setAuthentications(String token, List<Authentication> authentications) {
this.token = token;
this.authentications.clear();
if (null != authentications) {
for (Authentication auth : authentications) {
for (BaseAuthorization ba : auth.getAuthorizations()) {
if (ba instanceof AuthorizationNeedsWiring) {
((AuthorizationNeedsWiring) ba).wire(applicationContext);
}
}
this.authentications.add(auth);
}
}
userInfoInit();
} | java | @Api
public void setAuthentications(String token, List<Authentication> authentications) {
this.token = token;
this.authentications.clear();
if (null != authentications) {
for (Authentication auth : authentications) {
for (BaseAuthorization ba : auth.getAuthorizations()) {
if (ba instanceof AuthorizationNeedsWiring) {
((AuthorizationNeedsWiring) ba).wire(applicationContext);
}
}
this.authentications.add(auth);
}
}
userInfoInit();
} | [
"@",
"Api",
"public",
"void",
"setAuthentications",
"(",
"String",
"token",
",",
"List",
"<",
"Authentication",
">",
"authentications",
")",
"{",
"this",
".",
"token",
"=",
"token",
";",
"this",
".",
"authentications",
".",
"clear",
"(",
")",
";",
"if",
... | Set the token and authentications for this security context.
<p/>
This method can be overwritten to handle custom policies.
@param token current token
@param authentications authentications for token | [
"Set",
"the",
"token",
"and",
"authentications",
"for",
"this",
"security",
"context",
".",
"<p",
"/",
">",
"This",
"method",
"can",
"be",
"overwritten",
"to",
"handle",
"custom",
"policies",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/security/DefaultSecurityContext.java#L120-L135 |
OpenLiberty/open-liberty | dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/VariableEvaluator.java | VariableEvaluator.tryEvaluateExpression | @FFDCIgnore({ NumberFormatException.class, ArithmeticException.class, ConfigEvaluatorException.class })
private String tryEvaluateExpression(String expr, final EvaluationContext context, final boolean ignoreWarnings) {
try {
return new ConfigExpressionEvaluator() {
@Override
String getProperty(String argName) throws ConfigEvaluatorException {
return VariableEvaluator.this.getProperty(argName, context, ignoreWarnings, false);
}
@Override
Object getPropertyObject(String argName) throws ConfigEvaluatorException {
return VariableEvaluator.this.getPropertyObject(argName, context, ignoreWarnings, false);
}
}.evaluateExpression(expr);
} catch (NumberFormatException e) {
// ${0+string}, or a number that exceeds MAX_LONG.
} catch (ArithmeticException e) {
// ${x/0}
} catch (ConfigEvaluatorException e) {
// If getPropertyObject fails
}
return null;
} | java | @FFDCIgnore({ NumberFormatException.class, ArithmeticException.class, ConfigEvaluatorException.class })
private String tryEvaluateExpression(String expr, final EvaluationContext context, final boolean ignoreWarnings) {
try {
return new ConfigExpressionEvaluator() {
@Override
String getProperty(String argName) throws ConfigEvaluatorException {
return VariableEvaluator.this.getProperty(argName, context, ignoreWarnings, false);
}
@Override
Object getPropertyObject(String argName) throws ConfigEvaluatorException {
return VariableEvaluator.this.getPropertyObject(argName, context, ignoreWarnings, false);
}
}.evaluateExpression(expr);
} catch (NumberFormatException e) {
// ${0+string}, or a number that exceeds MAX_LONG.
} catch (ArithmeticException e) {
// ${x/0}
} catch (ConfigEvaluatorException e) {
// If getPropertyObject fails
}
return null;
} | [
"@",
"FFDCIgnore",
"(",
"{",
"NumberFormatException",
".",
"class",
",",
"ArithmeticException",
".",
"class",
",",
"ConfigEvaluatorException",
".",
"class",
"}",
")",
"private",
"String",
"tryEvaluateExpression",
"(",
"String",
"expr",
",",
"final",
"EvaluationConte... | Attempt to evaluate a variable expression.
@param expr the expression string (for example, "x+0")
@param context the context for evaluation
@return the result, or null if evaluation fails | [
"Attempt",
"to",
"evaluate",
"a",
"variable",
"expression",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/VariableEvaluator.java#L208-L232 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceFinder.java | SourceFinder.openSource | public InputStream openSource(String packageName, String fileName) throws IOException {
SourceFile sourceFile = findSourceFile(packageName, fileName);
return sourceFile.getInputStream();
} | java | public InputStream openSource(String packageName, String fileName) throws IOException {
SourceFile sourceFile = findSourceFile(packageName, fileName);
return sourceFile.getInputStream();
} | [
"public",
"InputStream",
"openSource",
"(",
"String",
"packageName",
",",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"SourceFile",
"sourceFile",
"=",
"findSourceFile",
"(",
"packageName",
",",
"fileName",
")",
";",
"return",
"sourceFile",
".",
"getIn... | Open an input stream on a source file in given package.
@param packageName
the name of the package containing the class whose source file
is given
@param fileName
the unqualified name of the source file
@return an InputStream on the source file
@throws IOException
if a matching source file cannot be found | [
"Open",
"an",
"input",
"stream",
"on",
"a",
"source",
"file",
"in",
"given",
"package",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceFinder.java#L442-L445 |
sjamesr/jfreesane | src/main/java/au/com/southsky/jfreesane/SaneWord.java | SaneWord.forSaneVersion | public static SaneWord forSaneVersion(int major, int minor, int build) {
int result = (major & 0xff) << 24;
result |= (minor & 0xff) << 16;
result |= (build & 0xffff) << 0;
return forInt(result);
} | java | public static SaneWord forSaneVersion(int major, int minor, int build) {
int result = (major & 0xff) << 24;
result |= (minor & 0xff) << 16;
result |= (build & 0xffff) << 0;
return forInt(result);
} | [
"public",
"static",
"SaneWord",
"forSaneVersion",
"(",
"int",
"major",
",",
"int",
"minor",
",",
"int",
"build",
")",
"{",
"int",
"result",
"=",
"(",
"major",
"&",
"0xff",
")",
"<<",
"24",
";",
"result",
"|=",
"(",
"minor",
"&",
"0xff",
")",
"<<",
... | Returns a new {@code SaneWord} representing the given SANE version.
@param major the SANE major version
@param minor the SANE minor version
@param build the SANE build identifier | [
"Returns",
"a",
"new",
"{",
"@code",
"SaneWord",
"}",
"representing",
"the",
"given",
"SANE",
"version",
"."
] | train | https://github.com/sjamesr/jfreesane/blob/15ad0f73df0a8d0efec5167a2141cbd53afd862d/src/main/java/au/com/southsky/jfreesane/SaneWord.java#L102-L107 |
asciidoctor/asciidoctorj | asciidoctorj-arquillian-extension/src/main/java/org/asciidoctor/arquillian/SecurityActions.java | SecurityActions.newInstance | static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments)
{
if (implClass == null)
{
throw new IllegalArgumentException("ImplClass must be specified");
}
if (argumentTypes == null)
{
throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
}
if (arguments == null)
{
throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
}
final T obj;
try
{
Constructor<T> constructor = getConstructor(implClass, argumentTypes);
if(!constructor.isAccessible()) {
constructor.setAccessible(true);
}
obj = constructor.newInstance(arguments);
}
catch (Exception e)
{
throw new RuntimeException("Could not create new instance of " + implClass, e);
}
return obj;
} | java | static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments)
{
if (implClass == null)
{
throw new IllegalArgumentException("ImplClass must be specified");
}
if (argumentTypes == null)
{
throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
}
if (arguments == null)
{
throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
}
final T obj;
try
{
Constructor<T> constructor = getConstructor(implClass, argumentTypes);
if(!constructor.isAccessible()) {
constructor.setAccessible(true);
}
obj = constructor.newInstance(arguments);
}
catch (Exception e)
{
throw new RuntimeException("Could not create new instance of " + implClass, e);
}
return obj;
} | [
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"final",
"Class",
"<",
"T",
">",
"implClass",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentTypes",
",",
"final",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"implClass",
"==",
... | Create a new instance by finding a constructor that matches the argumentTypes signature
using the arguments for instantiation.
@param implClass Full classname of class to create
@param argumentTypes The constructor argument types
@param arguments The constructor arguments
@return a new instance
@throws IllegalArgumentException if className, argumentTypes, or arguments are null
@throws RuntimeException if any exceptions during creation
@author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
@author <a href="mailto:andrew.rubinger@jboss.org">ALR</a> | [
"Create",
"a",
"new",
"instance",
"by",
"finding",
"a",
"constructor",
"that",
"matches",
"the",
"argumentTypes",
"signature",
"using",
"the",
"arguments",
"for",
"instantiation",
"."
] | train | https://github.com/asciidoctor/asciidoctorj/blob/e348c9a12b54c33fea7b05d70224c007e2ee75a9/asciidoctorj-arquillian-extension/src/main/java/org/asciidoctor/arquillian/SecurityActions.java#L116-L145 |
jtrfp/javamod | src/main/java/de/quippy/jflac/FixedPredictor.java | FixedPredictor.computeResidual | public static void computeResidual(int[] data, int dataLen, int order, int[] residual) {
int idataLen = (int) dataLen;
switch (order) {
case 0 :
for (int i = 0; i < idataLen; i++) {
residual[i] = data[i];
}
break;
case 1 :
for (int i = 0; i < idataLen; i++) {
residual[i] = data[i] - data[i - 1];
}
break;
case 2 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 2*data[i-1] + data[i-2] */
residual[i] = data[i] - (data[i - 1] << 1) + data[i - 2];
}
break;
case 3 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3] */
residual[i] = data[i] - (((data[i - 1] - data[i - 2]) << 1) + (data[i - 1] - data[i - 2])) - data[i - 3];
}
break;
case 4 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4] */
residual[i] = data[i] - ((data[i - 1] + data[i - 3]) << 2) + ((data[i - 2] << 2) + (data[i - 2] << 1)) + data[i - 4];
}
break;
default :
}
} | java | public static void computeResidual(int[] data, int dataLen, int order, int[] residual) {
int idataLen = (int) dataLen;
switch (order) {
case 0 :
for (int i = 0; i < idataLen; i++) {
residual[i] = data[i];
}
break;
case 1 :
for (int i = 0; i < idataLen; i++) {
residual[i] = data[i] - data[i - 1];
}
break;
case 2 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 2*data[i-1] + data[i-2] */
residual[i] = data[i] - (data[i - 1] << 1) + data[i - 2];
}
break;
case 3 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3] */
residual[i] = data[i] - (((data[i - 1] - data[i - 2]) << 1) + (data[i - 1] - data[i - 2])) - data[i - 3];
}
break;
case 4 :
for (int i = 0; i < idataLen; i++) {
/* == data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4] */
residual[i] = data[i] - ((data[i - 1] + data[i - 3]) << 2) + ((data[i - 2] << 2) + (data[i - 2] << 1)) + data[i - 4];
}
break;
default :
}
} | [
"public",
"static",
"void",
"computeResidual",
"(",
"int",
"[",
"]",
"data",
",",
"int",
"dataLen",
",",
"int",
"order",
",",
"int",
"[",
"]",
"residual",
")",
"{",
"int",
"idataLen",
"=",
"(",
"int",
")",
"dataLen",
";",
"switch",
"(",
"order",
")",... | Compute the residual from the compressed signal.
@param data
@param dataLen
@param order
@param residual | [
"Compute",
"the",
"residual",
"from",
"the",
"compressed",
"signal",
"."
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/jflac/FixedPredictor.java#L163-L197 |
js-lib-com/commons | src/main/java/js/util/Files.java | Files.replaceExtension | public static File replaceExtension(File file, String newExtension) throws IllegalArgumentException
{
Params.notNull(file, "File");
return new File(replaceExtension(file.getPath(), newExtension));
} | java | public static File replaceExtension(File file, String newExtension) throws IllegalArgumentException
{
Params.notNull(file, "File");
return new File(replaceExtension(file.getPath(), newExtension));
} | [
"public",
"static",
"File",
"replaceExtension",
"(",
"File",
"file",
",",
"String",
"newExtension",
")",
"throws",
"IllegalArgumentException",
"{",
"Params",
".",
"notNull",
"(",
"file",
",",
"\"File\"",
")",
";",
"return",
"new",
"File",
"(",
"replaceExtension"... | Replace extension on given file and return resulting file.
@param file file to replace extension,
@param newExtension newly extension.
@return newly created file.
@throws IllegalArgumentException if file parameter is null. | [
"Replace",
"extension",
"on",
"given",
"file",
"and",
"return",
"resulting",
"file",
"."
] | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Files.java#L676-L680 |
hawkular/hawkular-apm | client/instrumenter/src/main/java/org/hawkular/apm/instrumenter/RuleHelper.java | RuleHelper.appendInBuffer | public void appendInBuffer(Object obj, byte[] data, int offset, int len, boolean close) {
if (len > 0) {
collector().appendInBuffer(getRuleName(), obj, data, offset, len);
}
if (close) {
collector().recordInBuffer(getRuleName(), obj);
}
} | java | public void appendInBuffer(Object obj, byte[] data, int offset, int len, boolean close) {
if (len > 0) {
collector().appendInBuffer(getRuleName(), obj, data, offset, len);
}
if (close) {
collector().recordInBuffer(getRuleName(), obj);
}
} | [
"public",
"void",
"appendInBuffer",
"(",
"Object",
"obj",
",",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"len",
",",
"boolean",
"close",
")",
"{",
"if",
"(",
"len",
">",
"0",
")",
"{",
"collector",
"(",
")",
".",
"appendInBuffer",
... | This method appends data to the buffer associated with the supplied object.
@param obj The object associated with the buffer
@param data The data to be appended
@param offset The offset of the data
@param len The length of data
@param close Whether to close the buffer after appending the data | [
"This",
"method",
"appends",
"data",
"to",
"the",
"buffer",
"associated",
"with",
"the",
"supplied",
"object",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/instrumenter/src/main/java/org/hawkular/apm/instrumenter/RuleHelper.java#L482-L489 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/admin/user/Person.java | Person.setPassword | public Status setPassword(final String _newPasswd)
throws EFapsException
{
final Type type = CIAdminUser.Person.getType();
if (_newPasswd.length() == 0) {
throw new EFapsException(getClass(), "PassWordLength", 1, _newPasswd.length());
}
final Update update = new Update(type, "" + getId());
final Status status = update.add(CIAdminUser.Person.Password, _newPasswd);
if (status.isOk()) {
update.execute();
update.close();
} else {
Person.LOG.error("Password could not be set by the Update, due to restrictions " + "e.g. length???");
throw new EFapsException(getClass(), "TODO");
}
return status;
} | java | public Status setPassword(final String _newPasswd)
throws EFapsException
{
final Type type = CIAdminUser.Person.getType();
if (_newPasswd.length() == 0) {
throw new EFapsException(getClass(), "PassWordLength", 1, _newPasswd.length());
}
final Update update = new Update(type, "" + getId());
final Status status = update.add(CIAdminUser.Person.Password, _newPasswd);
if (status.isOk()) {
update.execute();
update.close();
} else {
Person.LOG.error("Password could not be set by the Update, due to restrictions " + "e.g. length???");
throw new EFapsException(getClass(), "TODO");
}
return status;
} | [
"public",
"Status",
"setPassword",
"(",
"final",
"String",
"_newPasswd",
")",
"throws",
"EFapsException",
"{",
"final",
"Type",
"type",
"=",
"CIAdminUser",
".",
"Person",
".",
"getType",
"(",
")",
";",
"if",
"(",
"_newPasswd",
".",
"length",
"(",
")",
"=="... | The instance method sets the new password for the current context user.
Before the new password is set, some checks are made.
@param _newPasswd new Password to set
@throws EFapsException on error
@return true if password set, else false | [
"The",
"instance",
"method",
"sets",
"the",
"new",
"password",
"for",
"the",
"current",
"context",
"user",
".",
"Before",
"the",
"new",
"password",
"is",
"set",
"some",
"checks",
"are",
"made",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/user/Person.java#L814-L831 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsClientVariantDisplay.java | CmsClientVariantDisplay.buildClientVariantUrl | private String buildClientVariantUrl(String context, CmsClientVariantInfo info) {
String currentUrl = Window.Location.getHref();
// remove fragment
currentUrl = currentUrl.replaceFirst("#.*$", "");
String connector = "?";
if (currentUrl.indexOf('?') >= 0) {
connector = "&";
}
String targetUrl = currentUrl + connector + CmsGwtConstants.PARAM_TEMPLATE_CONTEXT + "=" + context;
return targetUrl;
} | java | private String buildClientVariantUrl(String context, CmsClientVariantInfo info) {
String currentUrl = Window.Location.getHref();
// remove fragment
currentUrl = currentUrl.replaceFirst("#.*$", "");
String connector = "?";
if (currentUrl.indexOf('?') >= 0) {
connector = "&";
}
String targetUrl = currentUrl + connector + CmsGwtConstants.PARAM_TEMPLATE_CONTEXT + "=" + context;
return targetUrl;
} | [
"private",
"String",
"buildClientVariantUrl",
"(",
"String",
"context",
",",
"CmsClientVariantInfo",
"info",
")",
"{",
"String",
"currentUrl",
"=",
"Window",
".",
"Location",
".",
"getHref",
"(",
")",
";",
"// remove fragment",
"currentUrl",
"=",
"currentUrl",
"."... | Builds the URL for the client variant.<p>
@param context the template context name
@param info the client variant info
@return the URL for the variant | [
"Builds",
"the",
"URL",
"for",
"the",
"client",
"variant",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsClientVariantDisplay.java#L142-L153 |
line/armeria | core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpServiceFactory.java | AnnotatedHttpServiceFactory.producibleMediaTypes | private static List<MediaType> producibleMediaTypes(Method method, Class<?> clazz) {
List<Produces> produces = findAll(method, Produces.class);
List<ProduceType> produceTypes = findAll(method, ProduceType.class);
if (produces.isEmpty() && produceTypes.isEmpty()) {
produces = findAll(clazz, Produces.class);
produceTypes = findAll(clazz, ProduceType.class);
}
final List<MediaType> types =
Stream.concat(produces.stream().map(Produces::value),
produceTypes.stream().map(ProduceType::value))
.map(MediaType::parse)
.peek(type -> {
if (type.hasWildcard()) {
throw new IllegalArgumentException(
"Producible media types must not have a wildcard: " + type);
}
})
.collect(toImmutableList());
return ensureUniqueTypes(types, Produces.class);
} | java | private static List<MediaType> producibleMediaTypes(Method method, Class<?> clazz) {
List<Produces> produces = findAll(method, Produces.class);
List<ProduceType> produceTypes = findAll(method, ProduceType.class);
if (produces.isEmpty() && produceTypes.isEmpty()) {
produces = findAll(clazz, Produces.class);
produceTypes = findAll(clazz, ProduceType.class);
}
final List<MediaType> types =
Stream.concat(produces.stream().map(Produces::value),
produceTypes.stream().map(ProduceType::value))
.map(MediaType::parse)
.peek(type -> {
if (type.hasWildcard()) {
throw new IllegalArgumentException(
"Producible media types must not have a wildcard: " + type);
}
})
.collect(toImmutableList());
return ensureUniqueTypes(types, Produces.class);
} | [
"private",
"static",
"List",
"<",
"MediaType",
">",
"producibleMediaTypes",
"(",
"Method",
"method",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"List",
"<",
"Produces",
">",
"produces",
"=",
"findAll",
"(",
"method",
",",
"Produces",
".",
"class",
"... | Returns the list of {@link MediaType}s specified by {@link Produces} annotation. | [
"Returns",
"the",
"list",
"of",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpServiceFactory.java#L470-L491 |
ben-manes/caffeine | jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java | CacheProxy.putIfAbsentNoAwait | private boolean putIfAbsentNoAwait(K key, V value, boolean publishToWriter) {
boolean[] absent = { false };
cache.asMap().compute(copyOf(key), (k, expirable) -> {
if ((expirable != null) && !expirable.isEternal()
&& expirable.hasExpired(currentTimeMillis())) {
dispatcher.publishExpired(this, key, expirable.get());
statistics.recordEvictions(1L);
expirable = null;
}
if (expirable != null) {
return expirable;
}
absent[0] = true;
long expireTimeMS = getWriteExpireTimeMS(/* created */ true);
if (expireTimeMS == 0) {
return null;
}
if (publishToWriter) {
publishToCacheWriter(writer::write, () -> new EntryProxy<>(key, value));
}
V copy = copyOf(value);
dispatcher.publishCreated(this, key, copy);
return new Expirable<>(copy, expireTimeMS);
});
return absent[0];
} | java | private boolean putIfAbsentNoAwait(K key, V value, boolean publishToWriter) {
boolean[] absent = { false };
cache.asMap().compute(copyOf(key), (k, expirable) -> {
if ((expirable != null) && !expirable.isEternal()
&& expirable.hasExpired(currentTimeMillis())) {
dispatcher.publishExpired(this, key, expirable.get());
statistics.recordEvictions(1L);
expirable = null;
}
if (expirable != null) {
return expirable;
}
absent[0] = true;
long expireTimeMS = getWriteExpireTimeMS(/* created */ true);
if (expireTimeMS == 0) {
return null;
}
if (publishToWriter) {
publishToCacheWriter(writer::write, () -> new EntryProxy<>(key, value));
}
V copy = copyOf(value);
dispatcher.publishCreated(this, key, copy);
return new Expirable<>(copy, expireTimeMS);
});
return absent[0];
} | [
"private",
"boolean",
"putIfAbsentNoAwait",
"(",
"K",
"key",
",",
"V",
"value",
",",
"boolean",
"publishToWriter",
")",
"{",
"boolean",
"[",
"]",
"absent",
"=",
"{",
"false",
"}",
";",
"cache",
".",
"asMap",
"(",
")",
".",
"compute",
"(",
"copyOf",
"("... | Associates the specified value with the specified key in the cache if there is no existing
mapping.
@param key key with which the specified value is to be associated
@param value value to be associated with the specified key
@param publishToWriter if the writer should be notified
@return if the mapping was successful | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"key",
"in",
"the",
"cache",
"if",
"there",
"is",
"no",
"existing",
"mapping",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java#L435-L461 |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java | NorwegianDateUtil.rollGetDate | private static Date rollGetDate(Calendar calendar, int days) {
Calendar easterSunday = (Calendar) calendar.clone();
easterSunday.add(Calendar.DATE, days);
return easterSunday.getTime();
} | java | private static Date rollGetDate(Calendar calendar, int days) {
Calendar easterSunday = (Calendar) calendar.clone();
easterSunday.add(Calendar.DATE, days);
return easterSunday.getTime();
} | [
"private",
"static",
"Date",
"rollGetDate",
"(",
"Calendar",
"calendar",
",",
"int",
"days",
")",
"{",
"Calendar",
"easterSunday",
"=",
"(",
"Calendar",
")",
"calendar",
".",
"clone",
"(",
")",
";",
"easterSunday",
".",
"add",
"(",
"Calendar",
".",
"DATE",... | Add the given number of days to the calendar and convert to Date.
@param calendar
The calendar to add to.
@param days
The number of days to add.
@return The date object given by the modified calendar. | [
"Add",
"the",
"given",
"number",
"of",
"days",
"to",
"the",
"calendar",
"and",
"convert",
"to",
"Date",
"."
] | train | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L257-L261 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/toolbar/CmsToolbarClipboardView.java | CmsToolbarClipboardView.addModified | public void addModified(CmsClientSitemapEntry entry, String previousPath) {
removeDeleted(entry.getId().toString());
removeModified(entry.getId().toString());
getModified().insertItem(createModifiedItem(entry), 0);
m_clipboardButton.enableClearModified(true);
} | java | public void addModified(CmsClientSitemapEntry entry, String previousPath) {
removeDeleted(entry.getId().toString());
removeModified(entry.getId().toString());
getModified().insertItem(createModifiedItem(entry), 0);
m_clipboardButton.enableClearModified(true);
} | [
"public",
"void",
"addModified",
"(",
"CmsClientSitemapEntry",
"entry",
",",
"String",
"previousPath",
")",
"{",
"removeDeleted",
"(",
"entry",
".",
"getId",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"removeModified",
"(",
"entry",
".",
"getId",
"(",
... | Adds a modified entry.<p>
@param entry the entry
@param previousPath the previous path | [
"Adds",
"a",
"modified",
"entry",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/toolbar/CmsToolbarClipboardView.java#L144-L150 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java | DateUtil.truncate | public static Calendar truncate(Calendar calendar, DateField dateField) {
return DateModifier.modify(calendar, dateField.getValue(), ModifyType.TRUNCATE);
} | java | public static Calendar truncate(Calendar calendar, DateField dateField) {
return DateModifier.modify(calendar, dateField.getValue(), ModifyType.TRUNCATE);
} | [
"public",
"static",
"Calendar",
"truncate",
"(",
"Calendar",
"calendar",
",",
"DateField",
"dateField",
")",
"{",
"return",
"DateModifier",
".",
"modify",
"(",
"calendar",
",",
"dateField",
".",
"getValue",
"(",
")",
",",
"ModifyType",
".",
"TRUNCATE",
")",
... | 修改日期为某个时间字段起始时间
@param calendar {@link Calendar}
@param dateField 时间字段
@return 原{@link Calendar}
@since 4.5.7 | [
"修改日期为某个时间字段起始时间"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L767-L769 |
datasift/datasift-java | src/main/java/com/datasift/client/accounts/DataSiftAccount.java | DataSiftAccount.getUsage | public FutureData<UsageResult> getUsage(String period, int start, int end) {
FutureData<UsageResult> future = new FutureData<>();
if (start != 0 && end != 0 && start >= end) {
throw new IllegalArgumentException("getUsage start timestamp must be earlier than the end timestamp");
}
ParamBuilder b = newParams();
if (period != null && period.length() > 0) {
b.put("period", period);
}
if (start != 0) {
b.put("start", start);
}
if (end != 0) {
b.put("end", end);
}
URI uri = b.forURL(config.newAPIEndpointURI(USAGE));
Request request = config.http().
GET(uri, new PageReader(newRequestCallback(future, new UsageResult(), config)));
performRequest(future, request);
return future;
} | java | public FutureData<UsageResult> getUsage(String period, int start, int end) {
FutureData<UsageResult> future = new FutureData<>();
if (start != 0 && end != 0 && start >= end) {
throw new IllegalArgumentException("getUsage start timestamp must be earlier than the end timestamp");
}
ParamBuilder b = newParams();
if (period != null && period.length() > 0) {
b.put("period", period);
}
if (start != 0) {
b.put("start", start);
}
if (end != 0) {
b.put("end", end);
}
URI uri = b.forURL(config.newAPIEndpointURI(USAGE));
Request request = config.http().
GET(uri, new PageReader(newRequestCallback(future, new UsageResult(), config)));
performRequest(future, request);
return future;
} | [
"public",
"FutureData",
"<",
"UsageResult",
">",
"getUsage",
"(",
"String",
"period",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"FutureData",
"<",
"UsageResult",
">",
"future",
"=",
"new",
"FutureData",
"<>",
"(",
")",
";",
"if",
"(",
"start",
... | /*
Get the usage for the current account.
Period can be "hourly", "daily" or "monthly", and is optional.
If start timestamp is set to 0, start time is calculated based on a single unit of the period passed in.
i.e if the period is daily, this will be one day prior to the end timestamp.
If end timestamp is set to 0, end time is defaulted to current time.
For information on this endpoint see documentation page:
http://dev.datasift.com/pylon/docs/api/acct-api-endpoints
@param period the frequency at which to report usage data within the query period
@param start POSIX timestamp representing the time from which to report usage
@param end POSIX timestamp representing the latest time at which to report usage
@return Usage information in the form of a list of Usage objects | [
"/",
"*",
"Get",
"the",
"usage",
"for",
"the",
"current",
"account",
".",
"Period",
"can",
"be",
"hourly",
"daily",
"or",
"monthly",
"and",
"is",
"optional",
".",
"If",
"start",
"timestamp",
"is",
"set",
"to",
"0",
"start",
"time",
"is",
"calculated",
... | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/accounts/DataSiftAccount.java#L450-L473 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java | ThreadLocalRandom.ints | public IntStream ints(long streamSize) {
if (streamSize < 0L)
throw new IllegalArgumentException(BAD_SIZE);
return StreamSupport.intStream
(new RandomIntsSpliterator
(0L, streamSize, Integer.MAX_VALUE, 0),
false);
} | java | public IntStream ints(long streamSize) {
if (streamSize < 0L)
throw new IllegalArgumentException(BAD_SIZE);
return StreamSupport.intStream
(new RandomIntsSpliterator
(0L, streamSize, Integer.MAX_VALUE, 0),
false);
} | [
"public",
"IntStream",
"ints",
"(",
"long",
"streamSize",
")",
"{",
"if",
"(",
"streamSize",
"<",
"0L",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"BAD_SIZE",
")",
";",
"return",
"StreamSupport",
".",
"intStream",
"(",
"new",
"RandomIntsSpliterator",
... | Returns a stream producing the given {@code streamSize} number of
pseudorandom {@code int} values.
@param streamSize the number of values to generate
@return a stream of pseudorandom {@code int} values
@throws IllegalArgumentException if {@code streamSize} is
less than zero
@since 1.8 | [
"Returns",
"a",
"stream",
"producing",
"the",
"given",
"{",
"@code",
"streamSize",
"}",
"number",
"of",
"pseudorandom",
"{",
"@code",
"int",
"}",
"values",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L474-L481 |
Harium/keel | src/main/java/com/harium/keel/catalano/core/IntPoint.java | IntPoint.Multiply | public static IntPoint Multiply(IntPoint point1, IntPoint point2) {
IntPoint result = new IntPoint(point1);
result.Multiply(point2);
return result;
} | java | public static IntPoint Multiply(IntPoint point1, IntPoint point2) {
IntPoint result = new IntPoint(point1);
result.Multiply(point2);
return result;
} | [
"public",
"static",
"IntPoint",
"Multiply",
"(",
"IntPoint",
"point1",
",",
"IntPoint",
"point2",
")",
"{",
"IntPoint",
"result",
"=",
"new",
"IntPoint",
"(",
"point1",
")",
";",
"result",
".",
"Multiply",
"(",
"point2",
")",
";",
"return",
"result",
";",
... | Multiply values of two points.
@param point1 IntPoint.
@param point2 IntPoint.
@return IntPoint that contains X and Y axis coordinate. | [
"Multiply",
"values",
"of",
"two",
"points",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/core/IntPoint.java#L205-L209 |
alkacon/opencms-core | src/org/opencms/workplace/CmsDialog.java | CmsDialog.dialogScriptSubmit | @Override
public String dialogScriptSubmit() {
if (useNewStyle()) {
return super.dialogScriptSubmit();
}
StringBuffer result = new StringBuffer(512);
result.append("function submitAction(actionValue, theForm, formName) {\n");
result.append("\tif (theForm == null) {\n");
result.append("\t\ttheForm = document.forms[formName];\n");
result.append("\t}\n");
result.append("\ttheForm." + PARAM_FRAMENAME + ".value = window.name;\n");
result.append("\tif (actionValue == \"" + DIALOG_OK + "\") {\n");
result.append("\t\treturn true;\n");
result.append("\t}\n");
result.append("\ttheForm." + PARAM_ACTION + ".value = actionValue;\n");
result.append("\ttheForm.submit();\n");
result.append("\treturn false;\n");
result.append("}\n");
return result.toString();
} | java | @Override
public String dialogScriptSubmit() {
if (useNewStyle()) {
return super.dialogScriptSubmit();
}
StringBuffer result = new StringBuffer(512);
result.append("function submitAction(actionValue, theForm, formName) {\n");
result.append("\tif (theForm == null) {\n");
result.append("\t\ttheForm = document.forms[formName];\n");
result.append("\t}\n");
result.append("\ttheForm." + PARAM_FRAMENAME + ".value = window.name;\n");
result.append("\tif (actionValue == \"" + DIALOG_OK + "\") {\n");
result.append("\t\treturn true;\n");
result.append("\t}\n");
result.append("\ttheForm." + PARAM_ACTION + ".value = actionValue;\n");
result.append("\ttheForm.submit();\n");
result.append("\treturn false;\n");
result.append("}\n");
return result.toString();
} | [
"@",
"Override",
"public",
"String",
"dialogScriptSubmit",
"(",
")",
"{",
"if",
"(",
"useNewStyle",
"(",
")",
")",
"{",
"return",
"super",
".",
"dialogScriptSubmit",
"(",
")",
";",
"}",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"512",
")",... | Builds the standard javascript for submitting the dialog.<p>
@return the standard javascript for submitting the dialog | [
"Builds",
"the",
"standard",
"javascript",
"for",
"submitting",
"the",
"dialog",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L907-L928 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.