repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/Array.java | Array.getValue | @Override
public Object getValue(int index) {
synchronized (lock) {
return getMValue(internalArray, index).asNative(internalArray);
}
} | java | @Override
public Object getValue(int index) {
synchronized (lock) {
return getMValue(internalArray, index).asNative(internalArray);
}
} | [
"@",
"Override",
"public",
"Object",
"getValue",
"(",
"int",
"index",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"return",
"getMValue",
"(",
"internalArray",
",",
"index",
")",
".",
"asNative",
"(",
"internalArray",
")",
";",
"}",
"}"
] | Gets value at the given index as an object. The object types are Blob,
Array, Dictionary, Number, or String based on the underlying
data type; or nil if the value is nil.
@param index the index. This value must not exceed the bounds of the array.
@return the Object or null. | [
"Gets",
"value",
"at",
"the",
"given",
"index",
"as",
"an",
"object",
".",
"The",
"object",
"types",
"are",
"Blob",
"Array",
"Dictionary",
"Number",
"or",
"String",
"based",
"on",
"the",
"underlying",
"data",
"type",
";",
"or",
"nil",
"if",
"the",
"value... | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Array.java#L116-L121 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java | PersistenceBrokerImpl.unlinkFK | public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)
{
setFKField(targetObject, cld, rds, null);
} | java | public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)
{
setFKField(targetObject, cld, rds, null);
} | [
"public",
"void",
"unlinkFK",
"(",
"Object",
"targetObject",
",",
"ClassDescriptor",
"cld",
",",
"ObjectReferenceDescriptor",
"rds",
")",
"{",
"setFKField",
"(",
"targetObject",
",",
"cld",
",",
"rds",
",",
"null",
")",
";",
"}"
] | Unkink FK fields of target object.
@param targetObject real (non-proxy) target object
@param cld {@link ClassDescriptor} of the real target object
@param rds An {@link ObjectReferenceDescriptor} or {@link CollectionDescriptor}
associated with the real object. | [
"Unkink",
"FK",
"fields",
"of",
"target",
"object",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1241-L1244 |
camunda/camunda-bpmn-model | src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractEventBuilder.java | AbstractEventBuilder.camundaInputParameter | public B camundaInputParameter(String name, String value) {
CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement(CamundaInputOutput.class);
CamundaInputParameter camundaInputParameter = createChild(camundaInputOutput, CamundaInputParameter.class);
camundaInputParameter.setCamundaName(name);
camundaInputParameter.setTextContent(value);
return myself;
} | java | public B camundaInputParameter(String name, String value) {
CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement(CamundaInputOutput.class);
CamundaInputParameter camundaInputParameter = createChild(camundaInputOutput, CamundaInputParameter.class);
camundaInputParameter.setCamundaName(name);
camundaInputParameter.setTextContent(value);
return myself;
} | [
"public",
"B",
"camundaInputParameter",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"CamundaInputOutput",
"camundaInputOutput",
"=",
"getCreateSingleExtensionElement",
"(",
"CamundaInputOutput",
".",
"class",
")",
";",
"CamundaInputParameter",
"camundaInputPa... | Creates a new camunda input parameter extension element with the
given name and value.
@param name the name of the input parameter
@param value the value of the input parameter
@return the builder object | [
"Creates",
"a",
"new",
"camunda",
"input",
"parameter",
"extension",
"element",
"with",
"the",
"given",
"name",
"and",
"value",
"."
] | train | https://github.com/camunda/camunda-bpmn-model/blob/debcadf041d10fa62b799de0307b832cea84e5d4/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractEventBuilder.java#L42-L50 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/optimization/GoldenSectionLineSearch.java | GoldenSectionLineSearch.goldenMean | private double goldenMean(double a, double b) {
if (geometric) {
return a * Math.pow(b / a, GOLDEN_SECTION);
} else {
return a + (b - a) * GOLDEN_SECTION;
}
} | java | private double goldenMean(double a, double b) {
if (geometric) {
return a * Math.pow(b / a, GOLDEN_SECTION);
} else {
return a + (b - a) * GOLDEN_SECTION;
}
} | [
"private",
"double",
"goldenMean",
"(",
"double",
"a",
",",
"double",
"b",
")",
"{",
"if",
"(",
"geometric",
")",
"{",
"return",
"a",
"*",
"Math",
".",
"pow",
"(",
"b",
"/",
"a",
",",
"GOLDEN_SECTION",
")",
";",
"}",
"else",
"{",
"return",
"a",
"... | The point that is the GOLDEN_SECTION along the way from a to b.
a may be less or greater than b, you find the point 60-odd percent
of the way from a to b.
@param a Interval minimum
@param b Interval maximum
@return The GOLDEN_SECTION along the way from a to b. | [
"The",
"point",
"that",
"is",
"the",
"GOLDEN_SECTION",
"along",
"the",
"way",
"from",
"a",
"to",
"b",
".",
"a",
"may",
"be",
"less",
"or",
"greater",
"than",
"b",
"you",
"find",
"the",
"point",
"60",
"-",
"odd",
"percent",
"of",
"the",
"way",
"from",... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/optimization/GoldenSectionLineSearch.java#L188-L194 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/statistic/Histogram.java | Histogram.setStrategy | public void setStrategy( double median,
double standardDeviation,
int sigma ) {
this.bucketingStrategy = new StandardDeviationBucketingStrategy(median, standardDeviation, sigma);
this.bucketWidth = null;
} | java | public void setStrategy( double median,
double standardDeviation,
int sigma ) {
this.bucketingStrategy = new StandardDeviationBucketingStrategy(median, standardDeviation, sigma);
this.bucketWidth = null;
} | [
"public",
"void",
"setStrategy",
"(",
"double",
"median",
",",
"double",
"standardDeviation",
",",
"int",
"sigma",
")",
"{",
"this",
".",
"bucketingStrategy",
"=",
"new",
"StandardDeviationBucketingStrategy",
"(",
"median",
",",
"standardDeviation",
",",
"sigma",
... | Set the histogram to use the standard deviation to determine the bucket sizes.
@param median
@param standardDeviation
@param sigma | [
"Set",
"the",
"histogram",
"to",
"use",
"the",
"standard",
"deviation",
"to",
"determine",
"the",
"bucket",
"sizes",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/statistic/Histogram.java#L81-L86 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java | LongExtensions.operator_doubleGreaterThan | @Pure
@Inline(value="($1 >> $2)", constantExpression=true)
public static long operator_doubleGreaterThan(long a, int distance) {
return a >> distance;
} | java | @Pure
@Inline(value="($1 >> $2)", constantExpression=true)
public static long operator_doubleGreaterThan(long a, int distance) {
return a >> distance;
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"($1 >> $2)\"",
",",
"constantExpression",
"=",
"true",
")",
"public",
"static",
"long",
"operator_doubleGreaterThan",
"(",
"long",
"a",
",",
"int",
"distance",
")",
"{",
"return",
"a",
">>",
"distance",
";",
... | The binary <code>signed right sift</code> operator. This is the equivalent to the java <code>>></code> operator.
Shifts in the value of the sign bit as the leftmost bit, thus preserving the sign of the initial value.
@param a
a long.
@param distance
the number of times to shift.
@return <code>a>>distance</code> | [
"The",
"binary",
"<code",
">",
"signed",
"right",
"sift<",
"/",
"code",
">",
"operator",
".",
"This",
"is",
"the",
"equivalent",
"to",
"the",
"java",
"<code",
">",
">",
";",
">",
";",
"<",
"/",
"code",
">",
"operator",
".",
"Shifts",
"in",
"the",... | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java#L141-L145 |
geomajas/geomajas-project-server | common-servlet/src/main/java/org/geomajas/servlet/mvc/legend/LegendGraphicController.java | LegendGraphicController.getGraphic | @RequestMapping(value = "/legendgraphic", method = RequestMethod.GET)
public ModelAndView getGraphic(@RequestParam("layerId") String layerId,
@RequestParam(value = "styleName", required = false) String styleName,
@RequestParam(value = "ruleIndex", required = false) Integer ruleIndex,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "width", required = false) Integer width,
@RequestParam(value = "height", required = false) Integer height,
@RequestParam(value = "scale", required = false) Double scale,
@RequestParam(value = "allRules", required = false) Boolean allRules, HttpServletRequest request)
throws GeomajasException {
if (!allRules) {
return getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);
} else {
return getGraphics(layerId, styleName, format, width, height, scale);
}
} | java | @RequestMapping(value = "/legendgraphic", method = RequestMethod.GET)
public ModelAndView getGraphic(@RequestParam("layerId") String layerId,
@RequestParam(value = "styleName", required = false) String styleName,
@RequestParam(value = "ruleIndex", required = false) Integer ruleIndex,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "width", required = false) Integer width,
@RequestParam(value = "height", required = false) Integer height,
@RequestParam(value = "scale", required = false) Double scale,
@RequestParam(value = "allRules", required = false) Boolean allRules, HttpServletRequest request)
throws GeomajasException {
if (!allRules) {
return getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);
} else {
return getGraphics(layerId, styleName, format, width, height, scale);
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/legendgraphic\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ModelAndView",
"getGraphic",
"(",
"@",
"RequestParam",
"(",
"\"layerId\"",
")",
"String",
"layerId",
",",
"@",
"RequestParam",
"(",
... | Gets a legend graphic with the specified metadata parameters. All parameters are passed as request parameters.
@param layerId
the layer id
@param styleName
the style name
@param ruleIndex
the rule index
@param format
the image format ('png','jpg','gif')
@param width
the graphic's width
@param height
the graphic's height
@param scale
the scale denominator (not supported yet)
@param allRules
if true the image will contain all rules stacked vertically
@param request
the servlet request object
@return the model and view
@throws GeomajasException
when a style or rule does not exist or is not renderable | [
"Gets",
"a",
"legend",
"graphic",
"with",
"the",
"specified",
"metadata",
"parameters",
".",
"All",
"parameters",
"are",
"passed",
"as",
"request",
"parameters",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/common-servlet/src/main/java/org/geomajas/servlet/mvc/legend/LegendGraphicController.java#L81-L96 |
apache/spark | common/network-common/src/main/java/org/apache/spark/network/protocol/MessageWithHeader.java | MessageWithHeader.transferTo | @Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
// Bytes written for header in this call.
long writtenHeader = 0;
if (header.readableBytes() > 0) {
writtenHeader = copyByteBuf(header, target);
totalBytesTransferred += writtenHeader;
if (header.readableBytes() > 0) {
return writtenHeader;
}
}
// Bytes written for body in this call.
long writtenBody = 0;
if (body instanceof FileRegion) {
writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
} else if (body instanceof ByteBuf) {
writtenBody = copyByteBuf((ByteBuf) body, target);
}
totalBytesTransferred += writtenBody;
return writtenHeader + writtenBody;
} | java | @Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
// Bytes written for header in this call.
long writtenHeader = 0;
if (header.readableBytes() > 0) {
writtenHeader = copyByteBuf(header, target);
totalBytesTransferred += writtenHeader;
if (header.readableBytes() > 0) {
return writtenHeader;
}
}
// Bytes written for body in this call.
long writtenBody = 0;
if (body instanceof FileRegion) {
writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
} else if (body instanceof ByteBuf) {
writtenBody = copyByteBuf((ByteBuf) body, target);
}
totalBytesTransferred += writtenBody;
return writtenHeader + writtenBody;
} | [
"@",
"Override",
"public",
"long",
"transferTo",
"(",
"final",
"WritableByteChannel",
"target",
",",
"final",
"long",
"position",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"position",
"==",
"totalBytesTransferred",
",",
"\"Invali... | This code is more complicated than you would think because we might require multiple
transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
The contract is that the caller will ensure position is properly set to the total number
of bytes transferred so far (i.e. value returned by transferred()). | [
"This",
"code",
"is",
"more",
"complicated",
"than",
"you",
"would",
"think",
"because",
"we",
"might",
"require",
"multiple",
"transferTo",
"invocations",
"in",
"order",
"to",
"transfer",
"a",
"single",
"MessageWithHeader",
"to",
"avoid",
"busy",
"waiting",
"."... | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/protocol/MessageWithHeader.java#L105-L128 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/input/CmsRegexValidator.java | CmsRegexValidator.matchRuleRegex | private static boolean matchRuleRegex(String regex, String value) {
if (value == null) {
value = "";
}
if (regex == null) {
return true;
}
if ((regex.length() > 0) && (regex.charAt(0) == '!')) {
return !value.matches(regex.substring(1));
} else {
return value.matches(regex);
}
} | java | private static boolean matchRuleRegex(String regex, String value) {
if (value == null) {
value = "";
}
if (regex == null) {
return true;
}
if ((regex.length() > 0) && (regex.charAt(0) == '!')) {
return !value.matches(regex.substring(1));
} else {
return value.matches(regex);
}
} | [
"private",
"static",
"boolean",
"matchRuleRegex",
"(",
"String",
"regex",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"value",
"=",
"\"\"",
";",
"}",
"if",
"(",
"regex",
"==",
"null",
")",
"{",
"return",
"true",
";",... | Matches a string against a regex, and inverts the match if the regex starts with a '!'.<p>
@param regex the regular expression
@param value the string to be matched
@return true if the validation succeeded | [
"Matches",
"a",
"string",
"against",
"a",
"regex",
"and",
"inverts",
"the",
"match",
"if",
"the",
"regex",
"starts",
"with",
"a",
"!",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/CmsRegexValidator.java#L79-L93 |
craftercms/commons | utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java | ZipUtils.addFolderToZip | private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException {
String currentPath = StringUtils.isNotEmpty(path)? path + "/" + folder.getName(): folder.getName();
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
addFolderToZip(currentPath, file, zos);
} else {
addFileToZip(currentPath, file, zos);
}
}
} | java | private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException {
String currentPath = StringUtils.isNotEmpty(path)? path + "/" + folder.getName(): folder.getName();
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
addFolderToZip(currentPath, file, zos);
} else {
addFileToZip(currentPath, file, zos);
}
}
} | [
"private",
"static",
"void",
"addFolderToZip",
"(",
"String",
"path",
",",
"File",
"folder",
",",
"ZipOutputStream",
"zos",
")",
"throws",
"IOException",
"{",
"String",
"currentPath",
"=",
"StringUtils",
".",
"isNotEmpty",
"(",
"path",
")",
"?",
"path",
"+",
... | Adds a directory to the current zip
@param path the path of the parent folder in the zip
@param folder the directory to be added
@param zos the current zip output stream
@throws FileNotFoundException
@throws IOException | [
"Adds",
"a",
"directory",
"to",
"the",
"current",
"zip"
] | train | https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L135-L145 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java | FeaturesImpl.deletePhraseListAsync | public Observable<OperationStatus> deletePhraseListAsync(UUID appId, String versionId, int phraselistId) {
return deletePhraseListWithServiceResponseAsync(appId, versionId, phraselistId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> deletePhraseListAsync(UUID appId, String versionId, int phraselistId) {
return deletePhraseListWithServiceResponseAsync(appId, versionId, phraselistId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"deletePhraseListAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"int",
"phraselistId",
")",
"{",
"return",
"deletePhraseListWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"phraselist... | Deletes a phraselist feature.
@param appId The application ID.
@param versionId The version ID.
@param phraselistId The ID of the feature to be deleted.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object | [
"Deletes",
"a",
"phraselist",
"feature",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java#L853-L860 |
jboss-integration/fuse-bxms-integ | quickstarts/switchyard-demo-helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java | Transformers.getElementValue | private String getElementValue(Element parent, String elementName) {
String value = null;
NodeList nodes = parent.getElementsByTagName(elementName);
if (nodes.getLength() > 0) {
value = nodes.item(0).getChildNodes().item(0).getNodeValue();
}
return value;
} | java | private String getElementValue(Element parent, String elementName) {
String value = null;
NodeList nodes = parent.getElementsByTagName(elementName);
if (nodes.getLength() > 0) {
value = nodes.item(0).getChildNodes().item(0).getNodeValue();
}
return value;
} | [
"private",
"String",
"getElementValue",
"(",
"Element",
"parent",
",",
"String",
"elementName",
")",
"{",
"String",
"value",
"=",
"null",
";",
"NodeList",
"nodes",
"=",
"parent",
".",
"getElementsByTagName",
"(",
"elementName",
")",
";",
"if",
"(",
"nodes",
... | Gets the element value.
@param parent the parent
@param elementName the element name
@return the element value | [
"Gets",
"the",
"element",
"value",
"."
] | train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/quickstarts/switchyard-demo-helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java#L89-L96 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/variational/VariationalAutoencoder.java | VariationalAutoencoder.reconstructionProbability | public INDArray reconstructionProbability(INDArray data, int numSamples) {
INDArray reconstructionLogProb = reconstructionLogProbability(data, numSamples);
return Transforms.exp(reconstructionLogProb.castTo(DataType.DOUBLE), false); //Cast to double to reduce risk of numerical underflow
} | java | public INDArray reconstructionProbability(INDArray data, int numSamples) {
INDArray reconstructionLogProb = reconstructionLogProbability(data, numSamples);
return Transforms.exp(reconstructionLogProb.castTo(DataType.DOUBLE), false); //Cast to double to reduce risk of numerical underflow
} | [
"public",
"INDArray",
"reconstructionProbability",
"(",
"INDArray",
"data",
",",
"int",
"numSamples",
")",
"{",
"INDArray",
"reconstructionLogProb",
"=",
"reconstructionLogProbability",
"(",
"data",
",",
"numSamples",
")",
";",
"return",
"Transforms",
".",
"exp",
"(... | Calculate the reconstruction probability, as described in An & Cho, 2015 - "Variational Autoencoder based
Anomaly Detection using Reconstruction Probability" (Algorithm 4)<br>
The authors describe it as follows: "This is essentially the probability of the data being generated from a given
latent variable drawn from the approximate posterior distribution."<br>
<br>
Specifically, for each example x in the input, calculate p(x). Note however that p(x) is a stochastic (Monte-Carlo)
estimate of the true p(x), based on the specified number of samples. More samples will produce a more accurate
(lower variance) estimate of the true p(x) for the current model parameters.<br>
<br>
Internally uses {@link #reconstructionLogProbability(INDArray, int)} for the actual implementation.
That method may be more numerically stable in some cases.<br>
<br>
The returned array is a column vector of reconstruction probabilities, for each example. Thus, reconstruction probabilities
can (and should, for efficiency) be calculated in a batched manner.
@param data The data to calculate the reconstruction probability for
@param numSamples Number of samples with which to base the reconstruction probability on.
@return Column vector of reconstruction probabilities for each example (shape: [numExamples,1]) | [
"Calculate",
"the",
"reconstruction",
"probability",
"as",
"described",
"in",
"An",
"&",
"Cho",
"2015",
"-",
"Variational",
"Autoencoder",
"based",
"Anomaly",
"Detection",
"using",
"Reconstruction",
"Probability",
"(",
"Algorithm",
"4",
")",
"<br",
">",
"The",
"... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/variational/VariationalAutoencoder.java#L943-L946 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/ScrollBarButtonPainter.java | ScrollBarButtonPainter.getScrollBarButtonBackgroundPaint | public Paint getScrollBarButtonBackgroundPaint(Shape s, boolean isIncrease, boolean buttonsTogether) {
TwoColors colors = getScrollBarButtonBackgroundColors(buttonsTogether, isIncrease);
return createHorizontalGradient(s, colors);
} | java | public Paint getScrollBarButtonBackgroundPaint(Shape s, boolean isIncrease, boolean buttonsTogether) {
TwoColors colors = getScrollBarButtonBackgroundColors(buttonsTogether, isIncrease);
return createHorizontalGradient(s, colors);
} | [
"public",
"Paint",
"getScrollBarButtonBackgroundPaint",
"(",
"Shape",
"s",
",",
"boolean",
"isIncrease",
",",
"boolean",
"buttonsTogether",
")",
"{",
"TwoColors",
"colors",
"=",
"getScrollBarButtonBackgroundColors",
"(",
"buttonsTogether",
",",
"isIncrease",
")",
";",
... | DOCUMENT ME!
@param s DOCUMENT ME!
@param isIncrease DOCUMENT ME!
@param buttonsTogether DOCUMENT ME!
@return DOCUMENT ME! | [
"DOCUMENT",
"ME!"
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ScrollBarButtonPainter.java#L382-L386 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/ZealotKhala.java | ZealotKhala.orMoreThan | public ZealotKhala orMoreThan(String field, Object value) {
return this.doNormal(ZealotConst.OR_PREFIX, field, value, ZealotConst.GT_SUFFIX, true);
} | java | public ZealotKhala orMoreThan(String field, Object value) {
return this.doNormal(ZealotConst.OR_PREFIX, field, value, ZealotConst.GT_SUFFIX, true);
} | [
"public",
"ZealotKhala",
"orMoreThan",
"(",
"String",
"field",
",",
"Object",
"value",
")",
"{",
"return",
"this",
".",
"doNormal",
"(",
"ZealotConst",
".",
"OR_PREFIX",
",",
"field",
",",
"value",
",",
"ZealotConst",
".",
"GT_SUFFIX",
",",
"true",
")",
";... | 生成带" OR "前缀大于查询的SQL片段.
@param field 数据库字段
@param value 值
@return ZealotKhala实例 | [
"生成带",
"OR",
"前缀大于查询的SQL片段",
"."
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L690-L692 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/db/impl/DirectDataSourceProvider.java | DirectDataSourceProvider.createDataSource | @Override
public DataSource createDataSource(String source, Properties configurationProperties, String config) {
DataSource ds = null;
try {
DirectDataSourceConfiguration cfg = new DirectDataSourceConfiguration(configurationProperties);
ds = new DriverManagerDataSource(cfg.getDriverClassName(), cfg.getUrl(), cfg.getConnectionProperties());
} catch (ClassNotFoundException e) {
log.error("Driver class not found for '" + source + "' with configuration: " + configurationProperties, e);
} catch (Exception e) {
log.error("Error creating data source for '" + source + "' with configuration: " + configurationProperties, e);
}
return ds;
} | java | @Override
public DataSource createDataSource(String source, Properties configurationProperties, String config) {
DataSource ds = null;
try {
DirectDataSourceConfiguration cfg = new DirectDataSourceConfiguration(configurationProperties);
ds = new DriverManagerDataSource(cfg.getDriverClassName(), cfg.getUrl(), cfg.getConnectionProperties());
} catch (ClassNotFoundException e) {
log.error("Driver class not found for '" + source + "' with configuration: " + configurationProperties, e);
} catch (Exception e) {
log.error("Error creating data source for '" + source + "' with configuration: " + configurationProperties, e);
}
return ds;
} | [
"@",
"Override",
"public",
"DataSource",
"createDataSource",
"(",
"String",
"source",
",",
"Properties",
"configurationProperties",
",",
"String",
"config",
")",
"{",
"DataSource",
"ds",
"=",
"null",
";",
"try",
"{",
"DirectDataSourceConfiguration",
"cfg",
"=",
"n... | protected static PropertiesLoader propLoader = new PropertiesLoader(); | [
"protected",
"static",
"PropertiesLoader",
"propLoader",
"=",
"new",
"PropertiesLoader",
"()",
";"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/impl/DirectDataSourceProvider.java#L40-L52 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/ClassUtils.java | ClassUtils.isVisible | public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
if (clazz.getClassLoader() == classLoader) {
return true;
}
} catch (SecurityException ex) {
// Fall through to loadable check below
}
// Visible if same Class can be loaded from given ClassLoader
return isLoadable(clazz, classLoader);
} | java | public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
if (clazz.getClassLoader() == classLoader) {
return true;
}
} catch (SecurityException ex) {
// Fall through to loadable check below
}
// Visible if same Class can be loaded from given ClassLoader
return isLoadable(clazz, classLoader);
} | [
"public",
"static",
"boolean",
"isVisible",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"ClassLoader",
"classLoader",
")",
"{",
"if",
"(",
"classLoader",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"try",
"{",
"if",
"(",
"clazz",
".",
"getClassL... | Check whether the given class is visible in the given ClassLoader.
@param clazz the class to check (typically an interface)
@param classLoader the ClassLoader to check against
(may be {@code null} in which case this method will always return {@code true})
@return true if the given class is visible; otherwise false
@since 6.0.0 | [
"Check",
"whether",
"the",
"given",
"class",
"is",
"visible",
"in",
"the",
"given",
"ClassLoader",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ClassUtils.java#L148-L162 |
Ellzord/JALSE | src/main/java/jalse/entities/functions/Functions.java | Functions.validateEntityID | public static void validateEntityID(final EntityID id) {
int changes = 0;
// Changed new UUID(m, l)
if (id.mostSigBits() != EntityID.DEFAULT_MOST_SIG_BITS
|| id.leastSigBits() != EntityID.DEFAULT_LEAST_SIG_BITS) {
changes++;
}
// Changed fromString(n)
if (!EntityID.DEFAULT_NAME.equals(id.name())) {
changes++;
}
// Changed random
if (id.random() != EntityID.DEFAULT_RANDOM) {
changes++;
}
// Check changed more than once
if (changes > 1) {
throw new IllegalArgumentException(
String.format("%s annotation provides multiple ID source info", EntityID.class));
}
} | java | public static void validateEntityID(final EntityID id) {
int changes = 0;
// Changed new UUID(m, l)
if (id.mostSigBits() != EntityID.DEFAULT_MOST_SIG_BITS
|| id.leastSigBits() != EntityID.DEFAULT_LEAST_SIG_BITS) {
changes++;
}
// Changed fromString(n)
if (!EntityID.DEFAULT_NAME.equals(id.name())) {
changes++;
}
// Changed random
if (id.random() != EntityID.DEFAULT_RANDOM) {
changes++;
}
// Check changed more than once
if (changes > 1) {
throw new IllegalArgumentException(
String.format("%s annotation provides multiple ID source info", EntityID.class));
}
} | [
"public",
"static",
"void",
"validateEntityID",
"(",
"final",
"EntityID",
"id",
")",
"{",
"int",
"changes",
"=",
"0",
";",
"// Changed new UUID(m, l)",
"if",
"(",
"id",
".",
"mostSigBits",
"(",
")",
"!=",
"EntityID",
".",
"DEFAULT_MOST_SIG_BITS",
"||",
"id",
... | Validates an {@link EntityID} annotation is correctly formed.
@param id
ID to check. | [
"Validates",
"an",
"{",
"@link",
"EntityID",
"}",
"annotation",
"is",
"correctly",
"formed",
"."
] | train | https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/functions/Functions.java#L321-L344 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/util/rawQuerying/RawQueryExecutor.java | RawQueryExecutor.ftsToRawCustom | public <T> T ftsToRawCustom(final SearchQuery query, final Func1<String, T> deserializer) {
return Blocking.blockForSingle(async.ftsToRawCustom(query, deserializer), env.searchTimeout(), TimeUnit.MILLISECONDS);
} | java | public <T> T ftsToRawCustom(final SearchQuery query, final Func1<String, T> deserializer) {
return Blocking.blockForSingle(async.ftsToRawCustom(query, deserializer), env.searchTimeout(), TimeUnit.MILLISECONDS);
} | [
"public",
"<",
"T",
">",
"T",
"ftsToRawCustom",
"(",
"final",
"SearchQuery",
"query",
",",
"final",
"Func1",
"<",
"String",
",",
"T",
">",
"deserializer",
")",
"{",
"return",
"Blocking",
".",
"blockForSingle",
"(",
"async",
".",
"ftsToRawCustom",
"(",
"que... | Synchronously perform a {@link SearchQuery} and apply a user function to deserialize the raw JSON
FTS response, which is represented as a {@link String}.
Note that the query is executed "as is", without any processing comparable to what is done in
{@link Bucket#query(SearchQuery)} (like enforcing a server side timeout).
@param query the query to execute.
@param deserializer a deserializer function that transforms the String representation of the response into a custom type T.
@param <T> the type of the response, once deserialized by the user-provided function.
@return the FTS response as a T. | [
"Synchronously",
"perform",
"a",
"{",
"@link",
"SearchQuery",
"}",
"and",
"apply",
"a",
"user",
"function",
"to",
"deserialize",
"the",
"raw",
"JSON",
"FTS",
"response",
"which",
"is",
"represented",
"as",
"a",
"{",
"@link",
"String",
"}",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/rawQuerying/RawQueryExecutor.java#L152-L154 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancerOutboundRulesInner.java | LoadBalancerOutboundRulesInner.listAsync | public Observable<Page<OutboundRuleInner>> listAsync(final String resourceGroupName, final String loadBalancerName) {
return listWithServiceResponseAsync(resourceGroupName, loadBalancerName)
.map(new Func1<ServiceResponse<Page<OutboundRuleInner>>, Page<OutboundRuleInner>>() {
@Override
public Page<OutboundRuleInner> call(ServiceResponse<Page<OutboundRuleInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<OutboundRuleInner>> listAsync(final String resourceGroupName, final String loadBalancerName) {
return listWithServiceResponseAsync(resourceGroupName, loadBalancerName)
.map(new Func1<ServiceResponse<Page<OutboundRuleInner>>, Page<OutboundRuleInner>>() {
@Override
public Page<OutboundRuleInner> call(ServiceResponse<Page<OutboundRuleInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"OutboundRuleInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"loadBalancerName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"loadBalan... | Gets all the outbound rules in a load balancer.
@param resourceGroupName The name of the resource group.
@param loadBalancerName The name of the load balancer.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<OutboundRuleInner> object | [
"Gets",
"all",
"the",
"outbound",
"rules",
"in",
"a",
"load",
"balancer",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancerOutboundRulesInner.java#L123-L131 |
openengsb/openengsb | components/weaver/service/src/main/java/org/openengsb/core/weaver/service/internal/model/ManipulationUtils.java | ManipulationUtils.handleFileField | private static String handleFileField(String property, CtClass clazz) throws NotFoundException,
CannotCompileException {
String wrapperName = property + "wrapper";
StringBuilder builder = new StringBuilder();
builder.append(createTrace(String.format("Handle File type property '%s'", property)))
.append(String.format("if(%s == null) {", property))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\"", wrapperName))
.append(", null, FileWrapper.class));}\n else {")
.append(String.format("FileWrapper %s = new FileWrapper(%s);\n", wrapperName, property))
.append(String.format("%s.serialize();\n", wrapperName))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\",%s,%s.getClass()));}\n",
wrapperName, wrapperName, wrapperName));
addFileFunction(clazz, property);
return builder.toString();
} | java | private static String handleFileField(String property, CtClass clazz) throws NotFoundException,
CannotCompileException {
String wrapperName = property + "wrapper";
StringBuilder builder = new StringBuilder();
builder.append(createTrace(String.format("Handle File type property '%s'", property)))
.append(String.format("if(%s == null) {", property))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\"", wrapperName))
.append(", null, FileWrapper.class));}\n else {")
.append(String.format("FileWrapper %s = new FileWrapper(%s);\n", wrapperName, property))
.append(String.format("%s.serialize();\n", wrapperName))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\",%s,%s.getClass()));}\n",
wrapperName, wrapperName, wrapperName));
addFileFunction(clazz, property);
return builder.toString();
} | [
"private",
"static",
"String",
"handleFileField",
"(",
"String",
"property",
",",
"CtClass",
"clazz",
")",
"throws",
"NotFoundException",
",",
"CannotCompileException",
"{",
"String",
"wrapperName",
"=",
"property",
"+",
"\"wrapper\"",
";",
"StringBuilder",
"builder",... | Creates the logic which is needed to handle fields which are File types, since they need special treatment. | [
"Creates",
"the",
"logic",
"which",
"is",
"needed",
"to",
"handle",
"fields",
"which",
"are",
"File",
"types",
"since",
"they",
"need",
"special",
"treatment",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/weaver/service/src/main/java/org/openengsb/core/weaver/service/internal/model/ManipulationUtils.java#L415-L429 |
audit4j/audit4j-core | src/main/java/org/audit4j/core/util/AuditUtil.java | AuditUtil.dateToString | public static String dateToString(final Date date, final String format) {
if (date == null) {
return null;
}
final DateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
return dateFormat.format(date);
} | java | public static String dateToString(final Date date, final String format) {
if (date == null) {
return null;
}
final DateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
return dateFormat.format(date);
} | [
"public",
"static",
"String",
"dateToString",
"(",
"final",
"Date",
"date",
",",
"final",
"String",
"format",
")",
"{",
"if",
"(",
"date",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"DateFormat",
"dateFormat",
"=",
"new",
"SimpleDateForma... | Date to string.
@param date
the date
@param format
the format
@return the string | [
"Date",
"to",
"string",
"."
] | train | https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/util/AuditUtil.java#L81-L87 |
GoogleCloudPlatform/appengine-pipelines | java/src/main/java/com/google/appengine/tools/pipeline/impl/model/Barrier.java | Barrier.addListArgumentSlots | public void addListArgumentSlots(Slot initialSlot, List<Slot> slotList) {
if (!initialSlot.isFilled()) {
throw new IllegalArgumentException("initialSlot must be filled");
}
verifyStateBeforAdd(initialSlot);
int groupSize = slotList.size() + 1;
addSlotDescriptor(new SlotDescriptor(initialSlot, groupSize));
for (Slot slot : slotList) {
addSlotDescriptor(new SlotDescriptor(slot, groupSize));
}
} | java | public void addListArgumentSlots(Slot initialSlot, List<Slot> slotList) {
if (!initialSlot.isFilled()) {
throw new IllegalArgumentException("initialSlot must be filled");
}
verifyStateBeforAdd(initialSlot);
int groupSize = slotList.size() + 1;
addSlotDescriptor(new SlotDescriptor(initialSlot, groupSize));
for (Slot slot : slotList) {
addSlotDescriptor(new SlotDescriptor(slot, groupSize));
}
} | [
"public",
"void",
"addListArgumentSlots",
"(",
"Slot",
"initialSlot",
",",
"List",
"<",
"Slot",
">",
"slotList",
")",
"{",
"if",
"(",
"!",
"initialSlot",
".",
"isFilled",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"initialSlot must ... | Adds multiple slots to this barrier's waiting-on list representing a single
Job argument of type list.
@param slotList A list of slots that will be added to the barrier and used
as the elements of the list Job argument.
@throws IllegalArgumentException if intialSlot is not filled. | [
"Adds",
"multiple",
"slots",
"to",
"this",
"barrier",
"s",
"waiting",
"-",
"on",
"list",
"representing",
"a",
"single",
"Job",
"argument",
"of",
"type",
"list",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/java/src/main/java/com/google/appengine/tools/pipeline/impl/model/Barrier.java#L269-L279 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java | CPDefinitionLinkPersistenceImpl.findByCProductId | @Override
public List<CPDefinitionLink> findByCProductId(long CProductId, int start,
int end) {
return findByCProductId(CProductId, start, end, null);
} | java | @Override
public List<CPDefinitionLink> findByCProductId(long CProductId, int start,
int end) {
return findByCProductId(CProductId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionLink",
">",
"findByCProductId",
"(",
"long",
"CProductId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCProductId",
"(",
"CProductId",
",",
"start",
",",
"end",
",",
"null",
")",
"... | Returns a range of all the cp definition links where CProductId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionLinkModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CProductId the c product ID
@param start the lower bound of the range of cp definition links
@param end the upper bound of the range of cp definition links (not inclusive)
@return the range of matching cp definition links | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"definition",
"links",
"where",
"CProductId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L2051-L2055 |
xebialabs/overcast | src/main/java/com/xebialabs/overcast/support/libvirt/JDomUtil.java | JDomUtil.stringToDocument | public static Document stringToDocument(String xml) {
try {
SAXBuilder sax = new SAXBuilder();
return sax.build(new ByteArrayInputStream(xml.getBytes("UTF-8")));
} catch (JDOMException e) {
throw new IllegalArgumentException("Unable to parse xml", e);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse xml", e);
}
} | java | public static Document stringToDocument(String xml) {
try {
SAXBuilder sax = new SAXBuilder();
return sax.build(new ByteArrayInputStream(xml.getBytes("UTF-8")));
} catch (JDOMException e) {
throw new IllegalArgumentException("Unable to parse xml", e);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to parse xml", e);
}
} | [
"public",
"static",
"Document",
"stringToDocument",
"(",
"String",
"xml",
")",
"{",
"try",
"{",
"SAXBuilder",
"sax",
"=",
"new",
"SAXBuilder",
"(",
")",
";",
"return",
"sax",
".",
"build",
"(",
"new",
"ByteArrayInputStream",
"(",
"xml",
".",
"getBytes",
"(... | Convert xml to JDOM2 {@link Document}. Throws {@link IllegalArgumentException} in case of errors. | [
"Convert",
"xml",
"to",
"JDOM2",
"{"
] | train | https://github.com/xebialabs/overcast/blob/716e57b66870c9afe51edc3b6045863a34fb0061/src/main/java/com/xebialabs/overcast/support/libvirt/JDomUtil.java#L46-L55 |
tvesalainen/util | util/src/main/java/org/vesalainen/lang/Primitives.java | Primitives.parseChar | public static final char parseChar(CharSequence cs, int beginIndex, int endIndex)
{
if (endIndex - beginIndex != 1)
{
throw new IllegalArgumentException("input length must be 1");
}
return cs.charAt(beginIndex);
} | java | public static final char parseChar(CharSequence cs, int beginIndex, int endIndex)
{
if (endIndex - beginIndex != 1)
{
throw new IllegalArgumentException("input length must be 1");
}
return cs.charAt(beginIndex);
} | [
"public",
"static",
"final",
"char",
"parseChar",
"(",
"CharSequence",
"cs",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"{",
"if",
"(",
"endIndex",
"-",
"beginIndex",
"!=",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"input ... | Returns char from input.
@param cs
@param beginIndex the index to the first char of the text range.
@param endIndex the index after the last char of the text range.
@return
@throws IllegalArgumentException if input length is not 1. | [
"Returns",
"char",
"from",
"input",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/lang/Primitives.java#L471-L478 |
iorga-group/iraj | iraj/src/main/java/com/iorga/iraj/servlet/CacheAwareServlet.java | CacheAwareServlet.checkIfUnmodifiedSince | protected boolean checkIfUnmodifiedSince(final HttpServletRequest request, final HttpServletResponse response, final Attributes resourceAttributes)
throws IOException {
try {
final long lastModified = resourceAttributes.getLastModified();
final long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if (lastModified >= (headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch (final IllegalArgumentException illegalArgument) {
return true;
}
return true;
} | java | protected boolean checkIfUnmodifiedSince(final HttpServletRequest request, final HttpServletResponse response, final Attributes resourceAttributes)
throws IOException {
try {
final long lastModified = resourceAttributes.getLastModified();
final long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if (lastModified >= (headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch (final IllegalArgumentException illegalArgument) {
return true;
}
return true;
} | [
"protected",
"boolean",
"checkIfUnmodifiedSince",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
",",
"final",
"Attributes",
"resourceAttributes",
")",
"throws",
"IOException",
"{",
"try",
"{",
"final",
"long",
"lastModif... | Check if the if-unmodified-since condition is satisfied.
@param request
The servlet request we are processing
@param response
The servlet response we are creating
@param resourceAttributes
File object
@return boolean true if the resource meets the specified condition, and
false if the condition is not satisfied, in which case request
processing is stopped | [
"Check",
"if",
"the",
"if",
"-",
"unmodified",
"-",
"since",
"condition",
"is",
"satisfied",
"."
] | train | https://github.com/iorga-group/iraj/blob/5fdee26464248f29833610de402275eb64505542/iraj/src/main/java/com/iorga/iraj/servlet/CacheAwareServlet.java#L792-L809 |
cdapio/tigon | tigon-common/src/main/java/co/cask/tigon/io/BufferedEncoder.java | BufferedEncoder.writeRaw | public Encoder writeRaw(byte[] rawBytes, int off, int len) throws IOException {
output.write(rawBytes, off, len);
return this;
} | java | public Encoder writeRaw(byte[] rawBytes, int off, int len) throws IOException {
output.write(rawBytes, off, len);
return this;
} | [
"public",
"Encoder",
"writeRaw",
"(",
"byte",
"[",
"]",
"rawBytes",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"output",
".",
"write",
"(",
"rawBytes",
",",
"off",
",",
"len",
")",
";",
"return",
"this",
";",
"}"
] | Writes raw bytes to the buffer without encoding.
@param rawBytes The bytes to write.
@param off Offset to start in the byte array.
@param len Number of bytes to write starting from the offset. | [
"Writes",
"raw",
"bytes",
"to",
"the",
"buffer",
"without",
"encoding",
"."
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-common/src/main/java/co/cask/tigon/io/BufferedEncoder.java#L74-L77 |
deeplearning4j/deeplearning4j | datavec/datavec-api/src/main/java/org/datavec/api/conf/Configuration.java | Configuration.setStrings | public void setStrings(String name, String... values) {
set(name, StringUtils.join(values, ","));
} | java | public void setStrings(String name, String... values) {
set(name, StringUtils.join(values, ","));
} | [
"public",
"void",
"setStrings",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"set",
"(",
"name",
",",
"StringUtils",
".",
"join",
"(",
"values",
",",
"\",\"",
")",
")",
";",
"}"
] | Set the array of string values for the <code>name</code> property as
as comma delimited values.
@param name property name.
@param values The values | [
"Set",
"the",
"array",
"of",
"string",
"values",
"for",
"the",
"<code",
">",
"name<",
"/",
"code",
">",
"property",
"as",
"as",
"comma",
"delimited",
"values",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/conf/Configuration.java#L868-L870 |
apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveUtils.java | HiveUtils.getPartitions | public static List<Partition> getPartitions(IMetaStoreClient client, Table table,
Optional<String> filter, Optional<? extends HivePartitionExtendedFilter> hivePartitionExtendedFilterOptional)
throws IOException {
try {
List<Partition> partitions = Lists.newArrayList();
List<org.apache.hadoop.hive.metastore.api.Partition> partitionsList = filter.isPresent()
? client.listPartitionsByFilter(table.getDbName(), table.getTableName(), filter.get(), (short) -1)
: client.listPartitions(table.getDbName(), table.getTableName(), (short) -1);
for (org.apache.hadoop.hive.metastore.api.Partition p : partitionsList) {
if (!hivePartitionExtendedFilterOptional.isPresent() ||
hivePartitionExtendedFilterOptional.get().accept(p)) {
Partition partition = new Partition(table, p);
partitions.add(partition);
}
}
return partitions;
} catch (TException | HiveException te) {
throw new IOException("Hive Error", te);
}
} | java | public static List<Partition> getPartitions(IMetaStoreClient client, Table table,
Optional<String> filter, Optional<? extends HivePartitionExtendedFilter> hivePartitionExtendedFilterOptional)
throws IOException {
try {
List<Partition> partitions = Lists.newArrayList();
List<org.apache.hadoop.hive.metastore.api.Partition> partitionsList = filter.isPresent()
? client.listPartitionsByFilter(table.getDbName(), table.getTableName(), filter.get(), (short) -1)
: client.listPartitions(table.getDbName(), table.getTableName(), (short) -1);
for (org.apache.hadoop.hive.metastore.api.Partition p : partitionsList) {
if (!hivePartitionExtendedFilterOptional.isPresent() ||
hivePartitionExtendedFilterOptional.get().accept(p)) {
Partition partition = new Partition(table, p);
partitions.add(partition);
}
}
return partitions;
} catch (TException | HiveException te) {
throw new IOException("Hive Error", te);
}
} | [
"public",
"static",
"List",
"<",
"Partition",
">",
"getPartitions",
"(",
"IMetaStoreClient",
"client",
",",
"Table",
"table",
",",
"Optional",
"<",
"String",
">",
"filter",
",",
"Optional",
"<",
"?",
"extends",
"HivePartitionExtendedFilter",
">",
"hivePartitionExt... | Get a list of {@link Partition}s for the <code>table</code> that matches an optional <code>filter</code>
@param client an {@link IMetaStoreClient} for the correct metastore.
@param table the {@link Table} for which we should get partitions.
@param filter an optional filter for partitions as would be used in Hive. Can only filter on String columns.
(e.g. "part = \"part1\"" or "date > \"2015\"".
@return a list of {@link Partition}s | [
"Get",
"a",
"list",
"of",
"{",
"@link",
"Partition",
"}",
"s",
"for",
"the",
"<code",
">",
"table<",
"/",
"code",
">",
"that",
"matches",
"an",
"optional",
"<code",
">",
"filter<",
"/",
"code",
">"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/hive/HiveUtils.java#L87-L106 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java | VirtualMachineScaleSetExtensionsInner.beginCreateOrUpdate | public VirtualMachineScaleSetExtensionInner beginCreateOrUpdate(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, VirtualMachineScaleSetExtensionInner extensionParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters).toBlocking().single().body();
} | java | public VirtualMachineScaleSetExtensionInner beginCreateOrUpdate(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, VirtualMachineScaleSetExtensionInner extensionParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters).toBlocking().single().body();
} | [
"public",
"VirtualMachineScaleSetExtensionInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
",",
"String",
"vmssExtensionName",
",",
"VirtualMachineScaleSetExtensionInner",
"extensionParameters",
")",
"{",
"return",
"beginCreateOr... | The operation to create or update an extension.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set where the extension should be create or updated.
@param vmssExtensionName The name of the VM scale set extension.
@param extensionParameters Parameters supplied to the Create VM scale set Extension operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualMachineScaleSetExtensionInner object if successful. | [
"The",
"operation",
"to",
"create",
"or",
"update",
"an",
"extension",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java#L190-L192 |
js-lib-com/commons | src/main/java/js/util/Classes.java | Classes.getFieldValue | @SuppressWarnings("unchecked")
public static <T> T getFieldValue(Object object, Field field)
{
assert field.isAccessible();
try {
return (T)field.get(object);
}
catch(IllegalAccessException e) {
throw new BugError(e);
}
} | java | @SuppressWarnings("unchecked")
public static <T> T getFieldValue(Object object, Field field)
{
assert field.isAccessible();
try {
return (T)field.get(object);
}
catch(IllegalAccessException e) {
throw new BugError(e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"getFieldValue",
"(",
"Object",
"object",
",",
"Field",
"field",
")",
"{",
"assert",
"field",
".",
"isAccessible",
"(",
")",
";",
"try",
"{",
"return",
"(",
"T",
... | Get object instance field value. Reflective field argument should have accessibility set to true and this condition
is fulfilled if field is obtained via {@link #getField(Class, String)}.
@param object instance to retrieve field value from,
@param field object reflective field.
@param <T> field type.
@return field value, possible null. | [
"Get",
"object",
"instance",
"field",
"value",
".",
"Reflective",
"field",
"argument",
"should",
"have",
"accessibility",
"set",
"to",
"true",
"and",
"this",
"condition",
"is",
"fulfilled",
"if",
"field",
"is",
"obtained",
"via",
"{",
"@link",
"#getField",
"("... | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L686-L696 |
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.getJob | public JobResponseInner getJob(String resourceGroupName, String resourceName, String jobId) {
return getJobWithServiceResponseAsync(resourceGroupName, resourceName, jobId).toBlocking().single().body();
} | java | public JobResponseInner getJob(String resourceGroupName, String resourceName, String jobId) {
return getJobWithServiceResponseAsync(resourceGroupName, resourceName, jobId).toBlocking().single().body();
} | [
"public",
"JobResponseInner",
"getJob",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
",",
"String",
"jobId",
")",
"{",
"return",
"getJobWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
",",
"jobId",
")",
".",
"toBlocking"... | Get the details of a job from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
Get the details of a job from an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@param jobId The job identifier.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorDetailsException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobResponseInner object if successful. | [
"Get",
"the",
"details",
"of",
"a",
"job",
"from",
"an",
"IoT",
"hub",
".",
"For",
"more",
"information",
"see",
":",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"azure",
"/",
"iot",
"-",
"hub",
"/",
"iot",
"-",
"hub",
"-",
"de... | 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#L2208-L2210 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/MulticastSocket.java | MulticastSocket.joinGroup | public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress))
throw new IllegalArgumentException("Unsupported address type");
if (oldImpl)
throw new UnsupportedOperationException();
checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "joinGroup");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());
}
if (!((InetSocketAddress)mcastaddr).getAddress().isMulticastAddress()) {
throw new SocketException("Not a multicast address");
}
getImpl().joinGroup(mcastaddr, netIf);
} | java | public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress))
throw new IllegalArgumentException("Unsupported address type");
if (oldImpl)
throw new UnsupportedOperationException();
checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "joinGroup");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());
}
if (!((InetSocketAddress)mcastaddr).getAddress().isMulticastAddress()) {
throw new SocketException("Not a multicast address");
}
getImpl().joinGroup(mcastaddr, netIf);
} | [
"public",
"void",
"joinGroup",
"(",
"SocketAddress",
"mcastaddr",
",",
"NetworkInterface",
"netIf",
")",
"throws",
"IOException",
"{",
"if",
"(",
"isClosed",
"(",
")",
")",
"throw",
"new",
"SocketException",
"(",
"\"Socket is closed\"",
")",
";",
"if",
"(",
"m... | Joins the specified multicast group at the specified interface.
<p>If there is a security manager, this method first
calls its {@code checkMulticast} method
with the {@code mcastaddr} argument
as its argument.
@param mcastaddr is the multicast address to join
@param netIf specifies the local interface to receive multicast
datagram packets, or <i>null</i> to defer to the interface set by
{@link MulticastSocket#setInterface(InetAddress)} or
{@link MulticastSocket#setNetworkInterface(NetworkInterface)}
@exception IOException if there is an error joining
or when the address is not a multicast address.
@exception SecurityException if a security manager exists and its
{@code checkMulticast} method doesn't allow the join.
@throws IllegalArgumentException if mcastaddr is null or is a
SocketAddress subclass not supported by this socket
@see SecurityManager#checkMulticast(InetAddress)
@since 1.4 | [
"Joins",
"the",
"specified",
"multicast",
"group",
"at",
"the",
"specified",
"interface",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/MulticastSocket.java#L385-L407 |
cdk/cdk | misc/extra/src/main/java/org/openscience/cdk/io/INChIPlainTextReader.java | INChIPlainTextReader.readChemFile | private IChemFile readChemFile(IChemFile cf) throws CDKException {
// have to do stuff here
try {
String line = null;
while ((line = input.readLine()) != null) {
if (line.startsWith("INChI=") || line.startsWith("InChI=")) {
// ok, the fun starts
cf = cf.getBuilder().newInstance(IChemFile.class);
// ok, we need to parse things like:
// INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H
final String INChI = line.substring(6);
StringTokenizer tokenizer = new StringTokenizer(INChI, "/");
// ok, we expect 4 tokens
tokenizer.nextToken(); // 1.12Beta not stored since never used
final String formula = tokenizer.nextToken(); // C6H6
String connections = null;
if (tokenizer.hasMoreTokens()) {
connections = tokenizer.nextToken().substring(1); // 1-2-4-6-5-3-1
}
//final String hydrogens = tokenizer.nextToken().substring(1); // 1-6H
IAtomContainer parsedContent = inchiTool.processFormula(
cf.getBuilder().newInstance(IAtomContainer.class), formula);
if (connections != null)
inchiTool.processConnections(connections, parsedContent, -1);
IAtomContainerSet moleculeSet = cf.getBuilder().newInstance(IAtomContainerSet.class);
moleculeSet.addAtomContainer(cf.getBuilder().newInstance(IAtomContainer.class, parsedContent));
IChemModel model = cf.getBuilder().newInstance(IChemModel.class);
model.setMoleculeSet(moleculeSet);
IChemSequence sequence = cf.getBuilder().newInstance(IChemSequence.class);
sequence.addChemModel(model);
cf.addChemSequence(sequence);
}
}
} catch (IOException | IllegalArgumentException exception) {
exception.printStackTrace();
throw new CDKException("Error while reading INChI file: " + exception.getMessage(), exception);
}
return cf;
} | java | private IChemFile readChemFile(IChemFile cf) throws CDKException {
// have to do stuff here
try {
String line = null;
while ((line = input.readLine()) != null) {
if (line.startsWith("INChI=") || line.startsWith("InChI=")) {
// ok, the fun starts
cf = cf.getBuilder().newInstance(IChemFile.class);
// ok, we need to parse things like:
// INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H
final String INChI = line.substring(6);
StringTokenizer tokenizer = new StringTokenizer(INChI, "/");
// ok, we expect 4 tokens
tokenizer.nextToken(); // 1.12Beta not stored since never used
final String formula = tokenizer.nextToken(); // C6H6
String connections = null;
if (tokenizer.hasMoreTokens()) {
connections = tokenizer.nextToken().substring(1); // 1-2-4-6-5-3-1
}
//final String hydrogens = tokenizer.nextToken().substring(1); // 1-6H
IAtomContainer parsedContent = inchiTool.processFormula(
cf.getBuilder().newInstance(IAtomContainer.class), formula);
if (connections != null)
inchiTool.processConnections(connections, parsedContent, -1);
IAtomContainerSet moleculeSet = cf.getBuilder().newInstance(IAtomContainerSet.class);
moleculeSet.addAtomContainer(cf.getBuilder().newInstance(IAtomContainer.class, parsedContent));
IChemModel model = cf.getBuilder().newInstance(IChemModel.class);
model.setMoleculeSet(moleculeSet);
IChemSequence sequence = cf.getBuilder().newInstance(IChemSequence.class);
sequence.addChemModel(model);
cf.addChemSequence(sequence);
}
}
} catch (IOException | IllegalArgumentException exception) {
exception.printStackTrace();
throw new CDKException("Error while reading INChI file: " + exception.getMessage(), exception);
}
return cf;
} | [
"private",
"IChemFile",
"readChemFile",
"(",
"IChemFile",
"cf",
")",
"throws",
"CDKException",
"{",
"// have to do stuff here",
"try",
"{",
"String",
"line",
"=",
"null",
";",
"while",
"(",
"(",
"line",
"=",
"input",
".",
"readLine",
"(",
")",
")",
"!=",
"... | Reads a ChemFile object from input.
@return ChemFile with the content read from the input | [
"Reads",
"a",
"ChemFile",
"object",
"from",
"input",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/io/INChIPlainTextReader.java#L152-L192 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java | EventListenerSupport.initializeTransientFields | private void initializeTransientFields(final Class<L> listenerInterface, final ClassLoader classLoader) {
@SuppressWarnings("unchecked") // Will throw CCE here if not correct
final
L[] array = (L[]) Array.newInstance(listenerInterface, 0);
this.prototypeArray = array;
createProxy(listenerInterface, classLoader);
} | java | private void initializeTransientFields(final Class<L> listenerInterface, final ClassLoader classLoader) {
@SuppressWarnings("unchecked") // Will throw CCE here if not correct
final
L[] array = (L[]) Array.newInstance(listenerInterface, 0);
this.prototypeArray = array;
createProxy(listenerInterface, classLoader);
} | [
"private",
"void",
"initializeTransientFields",
"(",
"final",
"Class",
"<",
"L",
">",
"listenerInterface",
",",
"final",
"ClassLoader",
"classLoader",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// Will throw CCE here if not correct",
"final",
"L",
... | Initialize transient fields.
@param listenerInterface the class of the listener interface
@param classLoader the class loader to be used | [
"Initialize",
"transient",
"fields",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/event/EventListenerSupport.java#L291-L297 |
Azure/azure-sdk-for-java | batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/implementation/ClustersInner.java | ClustersInner.updateAsync | public Observable<ClusterInner> updateAsync(String resourceGroupName, String clusterName, ClusterUpdateParameters parameters) {
return updateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() {
@Override
public ClusterInner call(ServiceResponse<ClusterInner> response) {
return response.body();
}
});
} | java | public Observable<ClusterInner> updateAsync(String resourceGroupName, String clusterName, ClusterUpdateParameters parameters) {
return updateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() {
@Override
public ClusterInner call(ServiceResponse<ClusterInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ClusterInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"ClusterUpdateParameters",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterNa... | Update the properties of a given cluster.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long.
@param parameters Additional parameters for cluster update.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ClusterInner object | [
"Update",
"the",
"properties",
"of",
"a",
"given",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/implementation/ClustersInner.java#L333-L340 |
uber/NullAway | nullaway/src/main/java/com/uber/nullaway/NullAway.java | NullAway.matchReturn | @Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
handler.onMatchReturn(this, tree, state);
ExpressionTree retExpr = tree.getExpression();
// let's do quick checks on returned expression first
if (retExpr == null) {
return Description.NO_MATCH;
}
// now let's check the enclosing method
TreePath enclosingMethodOrLambda =
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
if (enclosingMethodOrLambda == null) {
throw new RuntimeException("no enclosing method, lambda or initializer!");
}
if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
|| enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
throw new RuntimeException(
"return statement outside of a method or lambda! (e.g. in an initializer block)");
}
Tree leaf = enclosingMethodOrLambda.getLeaf();
Symbol.MethodSymbol methodSymbol;
if (leaf instanceof MethodTree) {
MethodTree enclosingMethod = (MethodTree) leaf;
methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
} else {
// we have a lambda
methodSymbol =
NullabilityUtil.getFunctionalInterfaceMethod(
(LambdaExpressionTree) leaf, state.getTypes());
}
return checkReturnExpression(tree, retExpr, methodSymbol, state);
} | java | @Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
handler.onMatchReturn(this, tree, state);
ExpressionTree retExpr = tree.getExpression();
// let's do quick checks on returned expression first
if (retExpr == null) {
return Description.NO_MATCH;
}
// now let's check the enclosing method
TreePath enclosingMethodOrLambda =
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
if (enclosingMethodOrLambda == null) {
throw new RuntimeException("no enclosing method, lambda or initializer!");
}
if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
|| enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
throw new RuntimeException(
"return statement outside of a method or lambda! (e.g. in an initializer block)");
}
Tree leaf = enclosingMethodOrLambda.getLeaf();
Symbol.MethodSymbol methodSymbol;
if (leaf instanceof MethodTree) {
MethodTree enclosingMethod = (MethodTree) leaf;
methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
} else {
// we have a lambda
methodSymbol =
NullabilityUtil.getFunctionalInterfaceMethod(
(LambdaExpressionTree) leaf, state.getTypes());
}
return checkReturnExpression(tree, retExpr, methodSymbol, state);
} | [
"@",
"Override",
"public",
"Description",
"matchReturn",
"(",
"ReturnTree",
"tree",
",",
"VisitorState",
"state",
")",
"{",
"if",
"(",
"!",
"matchWithinClass",
")",
"{",
"return",
"Description",
".",
"NO_MATCH",
";",
"}",
"handler",
".",
"onMatchReturn",
"(",
... | We are trying to see if (1) we are in a method guaranteed to return something non-null, and (2)
this return statement can return something null. | [
"We",
"are",
"trying",
"to",
"see",
"if",
"(",
"1",
")",
"we",
"are",
"in",
"a",
"method",
"guaranteed",
"to",
"return",
"something",
"non",
"-",
"null",
"and",
"(",
"2",
")",
"this",
"return",
"statement",
"can",
"return",
"something",
"null",
"."
] | train | https://github.com/uber/NullAway/blob/c3979b4241f80411dbba6aac3ff653acbb88d00b/nullaway/src/main/java/com/uber/nullaway/NullAway.java#L284-L318 |
johncarl81/transfuse | transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java | Contract.sameLength | public static void sameLength(final Object[] array1, final Object[] array2, final String array1Name, final String array2Name) {
notNull(array1, array1Name);
notNull(array2, array2Name);
if (array1.length != array2.length) {
throw new IllegalArgumentException("expecting " + maskNullArgument(array1Name) + " to have the same length as " + maskNullArgument(array2Name));
}
} | java | public static void sameLength(final Object[] array1, final Object[] array2, final String array1Name, final String array2Name) {
notNull(array1, array1Name);
notNull(array2, array2Name);
if (array1.length != array2.length) {
throw new IllegalArgumentException("expecting " + maskNullArgument(array1Name) + " to have the same length as " + maskNullArgument(array2Name));
}
} | [
"public",
"static",
"void",
"sameLength",
"(",
"final",
"Object",
"[",
"]",
"array1",
",",
"final",
"Object",
"[",
"]",
"array2",
",",
"final",
"String",
"array1Name",
",",
"final",
"String",
"array2Name",
")",
"{",
"notNull",
"(",
"array1",
",",
"array1Na... | Checks that the arrays have the same number of elements, otherwise throws and exception
@param array1 the first array
@param array2 the second array
@param array1Name the name of the first array
@param array2Name the name of the second array
@throws IllegalArgumentException if array1 or array2 are null or if the arrays don't agree on the number of elements | [
"Checks",
"that",
"the",
"arrays",
"have",
"the",
"same",
"number",
"of",
"elements",
"otherwise",
"throws",
"and",
"exception"
] | train | https://github.com/johncarl81/transfuse/blob/a5f837504797a6c4f8628f7e1dde09b8e6368c8b/transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java#L112-L119 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/helper/JMPath.java | JMPath.getSubFilePathList | public static List<Path> getSubFilePathList(Path startDirectoryPath,
int maxDepth) {
return getSubPathList(startDirectoryPath, maxDepth, RegularFileFilter);
} | java | public static List<Path> getSubFilePathList(Path startDirectoryPath,
int maxDepth) {
return getSubPathList(startDirectoryPath, maxDepth, RegularFileFilter);
} | [
"public",
"static",
"List",
"<",
"Path",
">",
"getSubFilePathList",
"(",
"Path",
"startDirectoryPath",
",",
"int",
"maxDepth",
")",
"{",
"return",
"getSubPathList",
"(",
"startDirectoryPath",
",",
"maxDepth",
",",
"RegularFileFilter",
")",
";",
"}"
] | Gets sub file path list.
@param startDirectoryPath the start directory path
@param maxDepth the max depth
@return the sub file path list | [
"Gets",
"sub",
"file",
"path",
"list",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMPath.java#L434-L437 |
bluelinelabs/Conductor | conductor/src/main/java/com/bluelinelabs/conductor/Controller.java | Controller.handleBack | public boolean handleBack() {
List<RouterTransaction> childTransactions = new ArrayList<>();
for (ControllerHostedRouter childRouter : childRouters) {
childTransactions.addAll(childRouter.getBackstack());
}
Collections.sort(childTransactions, new Comparator<RouterTransaction>() {
@Override
public int compare(RouterTransaction o1, RouterTransaction o2) {
return o2.transactionIndex - o1.transactionIndex;
}
});
for (RouterTransaction transaction : childTransactions) {
Controller childController = transaction.controller;
if (childController.isAttached() && childController.getRouter().handleBack()) {
return true;
}
}
return false;
} | java | public boolean handleBack() {
List<RouterTransaction> childTransactions = new ArrayList<>();
for (ControllerHostedRouter childRouter : childRouters) {
childTransactions.addAll(childRouter.getBackstack());
}
Collections.sort(childTransactions, new Comparator<RouterTransaction>() {
@Override
public int compare(RouterTransaction o1, RouterTransaction o2) {
return o2.transactionIndex - o1.transactionIndex;
}
});
for (RouterTransaction transaction : childTransactions) {
Controller childController = transaction.controller;
if (childController.isAttached() && childController.getRouter().handleBack()) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"handleBack",
"(",
")",
"{",
"List",
"<",
"RouterTransaction",
">",
"childTransactions",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"ControllerHostedRouter",
"childRouter",
":",
"childRouters",
")",
"{",
"childTransactions",
"... | Should be overridden if this Controller needs to handle the back button being pressed.
@return True if this Controller has consumed the back button press, otherwise false | [
"Should",
"be",
"overridden",
"if",
"this",
"Controller",
"needs",
"to",
"handle",
"the",
"back",
"button",
"being",
"pressed",
"."
] | train | https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/Controller.java#L596-L619 |
icode/ameba | src/main/java/ameba/feature/AmebaFeature.java | AmebaFeature.subscribeEvent | protected <E extends Event> Listener subscribeEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) {
Listener<E> listener = locator.createAndInitialize(listenerClass);
subscribe(eventClass, listener);
return listener;
} | java | protected <E extends Event> Listener subscribeEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) {
Listener<E> listener = locator.createAndInitialize(listenerClass);
subscribe(eventClass, listener);
return listener;
} | [
"protected",
"<",
"E",
"extends",
"Event",
">",
"Listener",
"subscribeEvent",
"(",
"Class",
"<",
"E",
">",
"eventClass",
",",
"final",
"Class",
"<",
"?",
"extends",
"Listener",
"<",
"E",
">",
">",
"listenerClass",
")",
"{",
"Listener",
"<",
"E",
">",
"... | <p>subscribeEvent.</p>
@param eventClass a {@link java.lang.Class} object.
@param listenerClass a {@link java.lang.Class} object.
@return a {@link ameba.event.Listener} object.
@since 0.1.6e
@param <E> a E object. | [
"<p",
">",
"subscribeEvent",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/feature/AmebaFeature.java#L102-L106 |
ical4j/ical4j | src/main/java/net/fortuna/ical4j/model/AbstractContentFactory.java | AbstractContentFactory.registerExtendedFactory | @Deprecated
protected final void registerExtendedFactory(String key, T factory) {
extendedFactories.put(key, factory);
} | java | @Deprecated
protected final void registerExtendedFactory(String key, T factory) {
extendedFactories.put(key, factory);
} | [
"@",
"Deprecated",
"protected",
"final",
"void",
"registerExtendedFactory",
"(",
"String",
"key",
",",
"T",
"factory",
")",
"{",
"extendedFactories",
".",
"put",
"(",
"key",
",",
"factory",
")",
";",
"}"
] | Register a non-standard content factory.
@deprecated Define extensions in META-INF/services/net.fortuna.ical4j.model.[Type]Factory | [
"Register",
"a",
"non",
"-",
"standard",
"content",
"factory",
"."
] | train | https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/model/AbstractContentFactory.java#L69-L72 |
ironjacamar/ironjacamar | sjc/src/main/java/org/ironjacamar/sjc/maven/AbstractHostPortMojo.java | AbstractHostPortMojo.executeCommand | protected Serializable executeCommand(String command, Serializable[] arguments) throws Throwable
{
Socket socket = null;
try
{
socket = new Socket(host, port);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeUTF(command);
if (arguments != null)
{
oos.writeInt(arguments.length);
for (Serializable argument : arguments)
{
oos.writeObject(argument);
}
}
else
{
oos.writeInt(0);
}
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
return (Serializable)ois.readObject();
}
catch (EOFException ee)
{
// Nothing
}
finally
{
try
{
if (socket != null)
socket.close();
}
catch (IOException ignore)
{
// Ignore
}
}
return null;
} | java | protected Serializable executeCommand(String command, Serializable[] arguments) throws Throwable
{
Socket socket = null;
try
{
socket = new Socket(host, port);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeUTF(command);
if (arguments != null)
{
oos.writeInt(arguments.length);
for (Serializable argument : arguments)
{
oos.writeObject(argument);
}
}
else
{
oos.writeInt(0);
}
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
return (Serializable)ois.readObject();
}
catch (EOFException ee)
{
// Nothing
}
finally
{
try
{
if (socket != null)
socket.close();
}
catch (IOException ignore)
{
// Ignore
}
}
return null;
} | [
"protected",
"Serializable",
"executeCommand",
"(",
"String",
"command",
",",
"Serializable",
"[",
"]",
"arguments",
")",
"throws",
"Throwable",
"{",
"Socket",
"socket",
"=",
"null",
";",
"try",
"{",
"socket",
"=",
"new",
"Socket",
"(",
"host",
",",
"port",
... | Execute command
@param command The command
@param arguments The arguments
@return The result
@exception Throwable If an error occurs | [
"Execute",
"command"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/sjc/src/main/java/org/ironjacamar/sjc/maven/AbstractHostPortMojo.java#L166-L214 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/types/Version.java | Version.getField | public int getField(int index, int defaultValue)
{
if (index >= 0 && index < this.version.length)
{
return version[index];
}
else
{
return defaultValue;
}
} | java | public int getField(int index, int defaultValue)
{
if (index >= 0 && index < this.version.length)
{
return version[index];
}
else
{
return defaultValue;
}
} | [
"public",
"int",
"getField",
"(",
"int",
"index",
",",
"int",
"defaultValue",
")",
"{",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"this",
".",
"version",
".",
"length",
")",
"{",
"return",
"version",
"[",
"index",
"]",
";",
"}",
"else",
"{... | Retrieves the given field from this Version
@param index
int The index to retrieve (based at 0)
@param defaultValue
int The default value to return if the index doesn't exist
@return int The value of the version segment | [
"Retrieves",
"the",
"given",
"field",
"from",
"this",
"Version"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/Version.java#L141-L151 |
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java | ConditionalCheck.isNumeric | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class })
public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value, @Nullable final String name) {
if (condition) {
Check.isNumeric(value, name);
}
} | java | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class })
public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value, @Nullable final String name) {
if (condition) {
Check.isNumeric(value, name);
}
} | [
"@",
"ArgumentsChecked",
"@",
"Throws",
"(",
"{",
"IllegalNullArgumentException",
".",
"class",
",",
"IllegalNumericArgumentException",
".",
"class",
"}",
")",
"public",
"static",
"<",
"T",
"extends",
"CharSequence",
">",
"void",
"isNumeric",
"(",
"final",
"boolea... | Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the
characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank
account number).
@param condition
condition must be {@code true}^ so that the check will be performed
@param value
a readable sequence of {@code char} values which must be a number
@param name
name of object reference (in source code)
@throws IllegalNumberArgumentException
if the given argument {@code value} is no number | [
"Ensures",
"that",
"a",
"readable",
"sequence",
"of",
"{",
"@code",
"char",
"}",
"values",
"is",
"numeric",
".",
"Numeric",
"arguments",
"consist",
"only",
"of",
"the",
"characters",
"0",
"-",
"9",
"and",
"may",
"start",
"with",
"0",
"(",
"compared",
"to... | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L933-L939 |
jcuda/jnvgraph | JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java | JNvgraph.nvgraphAllocateEdgeData | public static int nvgraphAllocateEdgeData(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
long numsets,
Pointer settypes)
{
return checkResult(nvgraphAllocateEdgeDataNative(handle, descrG, numsets, settypes));
} | java | public static int nvgraphAllocateEdgeData(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
long numsets,
Pointer settypes)
{
return checkResult(nvgraphAllocateEdgeDataNative(handle, descrG, numsets, settypes));
} | [
"public",
"static",
"int",
"nvgraphAllocateEdgeData",
"(",
"nvgraphHandle",
"handle",
",",
"nvgraphGraphDescr",
"descrG",
",",
"long",
"numsets",
",",
"Pointer",
"settypes",
")",
"{",
"return",
"checkResult",
"(",
"nvgraphAllocateEdgeDataNative",
"(",
"handle",
",",
... | Allocate numsets vectors of size E reprensenting Edge Data and attached them the graph.
settypes[i] is the type of vector #i, currently all Vertex and Edge data should have the same type | [
"Allocate",
"numsets",
"vectors",
"of",
"size",
"E",
"reprensenting",
"Edge",
"Data",
"and",
"attached",
"them",
"the",
"graph",
".",
"settypes",
"[",
"i",
"]",
"is",
"the",
"type",
"of",
"vector",
"#i",
"currently",
"all",
"Vertex",
"and",
"Edge",
"data",... | train | https://github.com/jcuda/jnvgraph/blob/2c6bd7c58edac181753bacf30af2cceeb1989a78/JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java#L256-L263 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/JacksonUtils.java | JacksonUtils.toJson | public static JsonNode toJson(Object obj, ClassLoader classLoader) {
return SerializationUtils.toJson(obj, classLoader);
} | java | public static JsonNode toJson(Object obj, ClassLoader classLoader) {
return SerializationUtils.toJson(obj, classLoader);
} | [
"public",
"static",
"JsonNode",
"toJson",
"(",
"Object",
"obj",
",",
"ClassLoader",
"classLoader",
")",
"{",
"return",
"SerializationUtils",
".",
"toJson",
"(",
"obj",
",",
"classLoader",
")",
";",
"}"
] | Serialize an object to {@link JsonNode}, with a custom class loader.
@param obj
@param classLoader
@return | [
"Serialize",
"an",
"object",
"to",
"{",
"@link",
"JsonNode",
"}",
"with",
"a",
"custom",
"class",
"loader",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/JacksonUtils.java#L53-L55 |
hazelcast/hazelcast | hazelcast-client/src/main/java/com/hazelcast/client/util/ClientStateListener.java | ClientStateListener.awaitDisconnected | public boolean awaitDisconnected(long timeout, TimeUnit unit)
throws InterruptedException {
lock.lock();
try {
if (currentState.equals(CLIENT_DISCONNECTED) || currentState.equals(SHUTTING_DOWN) || currentState.equals(SHUTDOWN)) {
return true;
}
long duration = unit.toNanos(timeout);
while (duration > 0) {
duration = disconnectedCondition.awaitNanos(duration);
if (currentState.equals(CLIENT_DISCONNECTED) || currentState.equals(SHUTTING_DOWN) || currentState
.equals(SHUTDOWN)) {
return true;
}
}
return false;
} finally {
lock.unlock();
}
} | java | public boolean awaitDisconnected(long timeout, TimeUnit unit)
throws InterruptedException {
lock.lock();
try {
if (currentState.equals(CLIENT_DISCONNECTED) || currentState.equals(SHUTTING_DOWN) || currentState.equals(SHUTDOWN)) {
return true;
}
long duration = unit.toNanos(timeout);
while (duration > 0) {
duration = disconnectedCondition.awaitNanos(duration);
if (currentState.equals(CLIENT_DISCONNECTED) || currentState.equals(SHUTTING_DOWN) || currentState
.equals(SHUTDOWN)) {
return true;
}
}
return false;
} finally {
lock.unlock();
}
} | [
"public",
"boolean",
"awaitDisconnected",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"InterruptedException",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"currentState",
".",
"equals",
"(",
"CLIENT_DISCONNECTED",
")",
... | Waits until the client is disconnected from the cluster or the timeout expires.
Does not wait if the client is already shutting down or shutdown.
@param timeout the maximum time to wait
@param unit the time unit of the {@code timeout} argument
@return true if the client is disconnected to the cluster. On returning false,
you can check if timeout occured or the client is shutdown using {@code isShutdown} {@code getCurrentState}
@throws InterruptedException | [
"Waits",
"until",
"the",
"client",
"is",
"disconnected",
"from",
"the",
"cluster",
"or",
"the",
"timeout",
"expires",
".",
"Does",
"not",
"wait",
"if",
"the",
"client",
"is",
"already",
"shutting",
"down",
"or",
"shutdown",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast-client/src/main/java/com/hazelcast/client/util/ClientStateListener.java#L137-L159 |
alkacon/opencms-core | src/org/opencms/search/CmsVfsIndexer.java | CmsVfsIndexer.deleteResource | protected void deleteResource(I_CmsIndexWriter indexWriter, CmsPublishedResource resource) {
try {
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_DELETING_FROM_INDEX_1, resource.getRootPath()));
}
// delete all documents with this term from the index
indexWriter.deleteDocument(resource);
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_IO_INDEX_DOCUMENT_DELETE_2,
resource.getRootPath(),
m_index.getName()),
e);
}
}
} | java | protected void deleteResource(I_CmsIndexWriter indexWriter, CmsPublishedResource resource) {
try {
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_DELETING_FROM_INDEX_1, resource.getRootPath()));
}
// delete all documents with this term from the index
indexWriter.deleteDocument(resource);
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_IO_INDEX_DOCUMENT_DELETE_2,
resource.getRootPath(),
m_index.getName()),
e);
}
}
} | [
"protected",
"void",
"deleteResource",
"(",
"I_CmsIndexWriter",
"indexWriter",
",",
"CmsPublishedResource",
"resource",
")",
"{",
"try",
"{",
"if",
"(",
"LOG",
".",
"isInfoEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"info",
"(",
"Messages",
".",
"get",
"(",
... | Deletes a resource with the given index writer.<p>
@param indexWriter the index writer to resource the resource with
@param resource the root path of the resource to delete | [
"Deletes",
"a",
"resource",
"with",
"the",
"given",
"index",
"writer",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsVfsIndexer.java#L304-L322 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/OutputPropertyUtils.java | OutputPropertyUtils.getIntProperty | public static int getIntProperty(String key, Properties props)
{
String s = props.getProperty(key);
if (null == s)
return 0;
else
return Integer.parseInt(s);
} | java | public static int getIntProperty(String key, Properties props)
{
String s = props.getProperty(key);
if (null == s)
return 0;
else
return Integer.parseInt(s);
} | [
"public",
"static",
"int",
"getIntProperty",
"(",
"String",
"key",
",",
"Properties",
"props",
")",
"{",
"String",
"s",
"=",
"props",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"null",
"==",
"s",
")",
"return",
"0",
";",
"else",
"return",
"... | Searches for the int property with the specified key in the property list.
If the key is not found in this property list, the default property list,
and its defaults, recursively, are then checked. The method returns
<code>false</code> if the property is not found, or if the value is other
than "yes".
@param key the property key.
@param props the list of properties that will be searched.
@return the value in this property list as a int value, or 0
if null or not a number. | [
"Searches",
"for",
"the",
"int",
"property",
"with",
"the",
"specified",
"key",
"in",
"the",
"property",
"list",
".",
"If",
"the",
"key",
"is",
"not",
"found",
"in",
"this",
"property",
"list",
"the",
"default",
"property",
"list",
"and",
"its",
"defaults"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/OutputPropertyUtils.java#L72-L81 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/InputTypeUtil.java | InputTypeUtil.getPreProcessorForInputTypeCnnLayers | public static InputPreProcessor getPreProcessorForInputTypeCnnLayers(InputType inputType, String layerName) {
//To add x-to-CNN preprocessor: need to know image channels/width/height after reshaping
//But this can't be inferred from the FF/RNN activations directly (could be anything)
switch (inputType.getType()) {
case FF:
//FF -> CNN
// return new FeedForwardToCnnPreProcessor(inputSize[0], inputSize[1], inputDepth);
log.info("Automatic addition of FF -> CNN preprocessors: not yet implemented (layer name: \""
+ layerName + "\")");
return null;
case RNN:
//RNN -> CNN
// return new RnnToCnnPreProcessor(inputSize[0], inputSize[1], inputDepth);
log.warn("Automatic addition of RNN -> CNN preprocessors: not yet implemented (layer name: \""
+ layerName + "\")");
return null;
case CNN:
//CNN -> CNN: no preprocessor required
return null;
case CNNFlat:
//CNN (flat) -> CNN
InputType.InputTypeConvolutionalFlat f = (InputType.InputTypeConvolutionalFlat) inputType;
return new FeedForwardToCnnPreProcessor(f.getHeight(), f.getWidth(), f.getDepth());
default:
throw new RuntimeException("Unknown input type: " + inputType);
}
} | java | public static InputPreProcessor getPreProcessorForInputTypeCnnLayers(InputType inputType, String layerName) {
//To add x-to-CNN preprocessor: need to know image channels/width/height after reshaping
//But this can't be inferred from the FF/RNN activations directly (could be anything)
switch (inputType.getType()) {
case FF:
//FF -> CNN
// return new FeedForwardToCnnPreProcessor(inputSize[0], inputSize[1], inputDepth);
log.info("Automatic addition of FF -> CNN preprocessors: not yet implemented (layer name: \""
+ layerName + "\")");
return null;
case RNN:
//RNN -> CNN
// return new RnnToCnnPreProcessor(inputSize[0], inputSize[1], inputDepth);
log.warn("Automatic addition of RNN -> CNN preprocessors: not yet implemented (layer name: \""
+ layerName + "\")");
return null;
case CNN:
//CNN -> CNN: no preprocessor required
return null;
case CNNFlat:
//CNN (flat) -> CNN
InputType.InputTypeConvolutionalFlat f = (InputType.InputTypeConvolutionalFlat) inputType;
return new FeedForwardToCnnPreProcessor(f.getHeight(), f.getWidth(), f.getDepth());
default:
throw new RuntimeException("Unknown input type: " + inputType);
}
} | [
"public",
"static",
"InputPreProcessor",
"getPreProcessorForInputTypeCnnLayers",
"(",
"InputType",
"inputType",
",",
"String",
"layerName",
")",
"{",
"//To add x-to-CNN preprocessor: need to know image channels/width/height after reshaping",
"//But this can't be inferred from the FF/RNN ac... | Utility method for determining the appropriate preprocessor for CNN layers, such as {@link ConvolutionLayer} and
{@link SubsamplingLayer}
@param inputType Input type to get the preprocessor for
@return Null if no preprocessor is required; otherwise the appropriate preprocessor for the given input type | [
"Utility",
"method",
"for",
"determining",
"the",
"appropriate",
"preprocessor",
"for",
"CNN",
"layers",
"such",
"as",
"{",
"@link",
"ConvolutionLayer",
"}",
"and",
"{",
"@link",
"SubsamplingLayer",
"}"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/InputTypeUtil.java#L442-L470 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java | CmsDefaultXmlContentHandler.initRelations | protected void initRelations(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(root, APPINFO_RELATION);
while (i.hasNext()) {
// iterate all "checkrule" elements in the "checkrule" node
Element element = i.next();
String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT);
String invalidate = element.attributeValue(APPINFO_ATTR_INVALIDATE);
if (invalidate != null) {
invalidate = invalidate.toUpperCase();
}
String type = element.attributeValue(APPINFO_ATTR_TYPE);
if (type != null) {
type = type.toLowerCase();
}
if (elementName != null) {
// add a check rule for the element
addCheckRule(contentDefinition, elementName, invalidate, type);
}
}
} | java | protected void initRelations(Element root, CmsXmlContentDefinition contentDefinition) throws CmsXmlException {
Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(root, APPINFO_RELATION);
while (i.hasNext()) {
// iterate all "checkrule" elements in the "checkrule" node
Element element = i.next();
String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT);
String invalidate = element.attributeValue(APPINFO_ATTR_INVALIDATE);
if (invalidate != null) {
invalidate = invalidate.toUpperCase();
}
String type = element.attributeValue(APPINFO_ATTR_TYPE);
if (type != null) {
type = type.toLowerCase();
}
if (elementName != null) {
// add a check rule for the element
addCheckRule(contentDefinition, elementName, invalidate, type);
}
}
} | [
"protected",
"void",
"initRelations",
"(",
"Element",
"root",
",",
"CmsXmlContentDefinition",
"contentDefinition",
")",
"throws",
"CmsXmlException",
"{",
"Iterator",
"<",
"Element",
">",
"i",
"=",
"CmsXmlGenericWrapper",
".",
"elementIterator",
"(",
"root",
",",
"AP... | Initializes the relation configuration for this content handler.<p>
OpenCms performs link checks for all OPTIONAL links defined in XML content values of type
OpenCmsVfsFile. However, for most projects in the real world a more fine-grained control
over the link check process is required. For these cases, individual relation behavior can
be defined for the appinfo node.<p>
Additional here can be defined an optional type for the relations, for instance.<p>
@param root the "relations" element from the appinfo node of the XML content definition
@param contentDefinition the content definition the check rules belong to
@throws CmsXmlException if something goes wrong | [
"Initializes",
"the",
"relation",
"configuration",
"for",
"this",
"content",
"handler",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2845-L2865 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getUploadNewVersionRequest | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(InputStream fileInputStream, String destinationFileId){
BoxRequestsFile.UploadNewVersion request = new BoxRequestsFile.UploadNewVersion(fileInputStream, getFileUploadNewVersionUrl(destinationFileId), mSession);
return request;
} | java | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(InputStream fileInputStream, String destinationFileId){
BoxRequestsFile.UploadNewVersion request = new BoxRequestsFile.UploadNewVersion(fileInputStream, getFileUploadNewVersionUrl(destinationFileId), mSession);
return request;
} | [
"public",
"BoxRequestsFile",
".",
"UploadNewVersion",
"getUploadNewVersionRequest",
"(",
"InputStream",
"fileInputStream",
",",
"String",
"destinationFileId",
")",
"{",
"BoxRequestsFile",
".",
"UploadNewVersion",
"request",
"=",
"new",
"BoxRequestsFile",
".",
"UploadNewVers... | Gets a request that uploads a new file version from an input stream
@param fileInputStream input stream of the new file version
@param destinationFileId id of the file to upload a new version of
@return request to upload a new file version from an input stream | [
"Gets",
"a",
"request",
"that",
"uploads",
"a",
"new",
"file",
"version",
"from",
"an",
"input",
"stream"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L336-L339 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/parametrics/relatedsamples/PearsonCorrelation.java | PearsonCorrelation.scoreToPvalue | private static double scoreToPvalue(double score, int n) {
double T= score/Math.sqrt((1-score*score)/(n-2));
return ContinuousDistributions.studentsCdf(T, n-2);
} | java | private static double scoreToPvalue(double score, int n) {
double T= score/Math.sqrt((1-score*score)/(n-2));
return ContinuousDistributions.studentsCdf(T, n-2);
} | [
"private",
"static",
"double",
"scoreToPvalue",
"(",
"double",
"score",
",",
"int",
"n",
")",
"{",
"double",
"T",
"=",
"score",
"/",
"Math",
".",
"sqrt",
"(",
"(",
"1",
"-",
"score",
"*",
"score",
")",
"/",
"(",
"n",
"-",
"2",
")",
")",
";",
"r... | Returns the Pvalue for a particular score
@param score
@param n
@return | [
"Returns",
"the",
"Pvalue",
"for",
"a",
"particular",
"score"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/parametrics/relatedsamples/PearsonCorrelation.java#L101-L104 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/util/ValidationFileUtil.java | ValidationFileUtil.sendFileToHttpServiceResponse | public static void sendFileToHttpServiceResponse(String fileName, Object bodyObj, HttpServletResponse res) {
if (fileName == null || bodyObj == null) {
return;
}
String body = null;
try {
body = ValidationObjUtil.getDefaultObjectMapper().writeValueAsString(bodyObj);
} catch (JsonProcessingException e) {
log.info(e.getMessage());
}
String filename = getEncodingFileName(fileName);
initFileSendHeader(res, filename, null);
byte[] bytes = body.getBytes();
res.setContentLength(bytes.length);
try {
res.getOutputStream().write(bytes);
} catch (IOException e) {
throw new ValidationLibException("file io error :" + e.getMessage());
}
} | java | public static void sendFileToHttpServiceResponse(String fileName, Object bodyObj, HttpServletResponse res) {
if (fileName == null || bodyObj == null) {
return;
}
String body = null;
try {
body = ValidationObjUtil.getDefaultObjectMapper().writeValueAsString(bodyObj);
} catch (JsonProcessingException e) {
log.info(e.getMessage());
}
String filename = getEncodingFileName(fileName);
initFileSendHeader(res, filename, null);
byte[] bytes = body.getBytes();
res.setContentLength(bytes.length);
try {
res.getOutputStream().write(bytes);
} catch (IOException e) {
throw new ValidationLibException("file io error :" + e.getMessage());
}
} | [
"public",
"static",
"void",
"sendFileToHttpServiceResponse",
"(",
"String",
"fileName",
",",
"Object",
"bodyObj",
",",
"HttpServletResponse",
"res",
")",
"{",
"if",
"(",
"fileName",
"==",
"null",
"||",
"bodyObj",
"==",
"null",
")",
"{",
"return",
";",
"}",
"... | Send file to http service response.
@param fileName the file name
@param bodyObj the body obj
@param res the res | [
"Send",
"file",
"to",
"http",
"service",
"response",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationFileUtil.java#L133-L156 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java | StaticTypeCheckingVisitor.checkOrMarkPrivateAccess | private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) {
if (fn == null) return;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
if (fn.isPrivate() &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule()) {
if (!lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
// check for a public/protected getter since JavaBean getters haven't been recognised as properties
// at this point and we don't want private field access for that case which will be handled later
boolean isPrimBool = fn.getOriginType().equals(ClassHelper.boolean_TYPE);
String suffix = Verifier.capitalize(fn.getName());
MethodNode getterNode = findValidGetter(enclosingClassNode, "get" + suffix);
if (getterNode == null && isPrimBool) {
getterNode = findValidGetter(enclosingClassNode, "is" + suffix);
}
if (getterNode != null) {
source.putNodeMetaData(INFERRED_TYPE, getterNode.getReturnType());
return;
}
}
StaticTypesMarker marker = lhsOfAssignment ? StaticTypesMarker.PV_FIELDS_MUTATION : StaticTypesMarker.PV_FIELDS_ACCESS;
addPrivateFieldOrMethodAccess(source, declaringClass, marker, fn);
}
} | java | private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) {
if (fn == null) return;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
if (fn.isPrivate() &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule()) {
if (!lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
// check for a public/protected getter since JavaBean getters haven't been recognised as properties
// at this point and we don't want private field access for that case which will be handled later
boolean isPrimBool = fn.getOriginType().equals(ClassHelper.boolean_TYPE);
String suffix = Verifier.capitalize(fn.getName());
MethodNode getterNode = findValidGetter(enclosingClassNode, "get" + suffix);
if (getterNode == null && isPrimBool) {
getterNode = findValidGetter(enclosingClassNode, "is" + suffix);
}
if (getterNode != null) {
source.putNodeMetaData(INFERRED_TYPE, getterNode.getReturnType());
return;
}
}
StaticTypesMarker marker = lhsOfAssignment ? StaticTypesMarker.PV_FIELDS_MUTATION : StaticTypesMarker.PV_FIELDS_ACCESS;
addPrivateFieldOrMethodAccess(source, declaringClass, marker, fn);
}
} | [
"private",
"void",
"checkOrMarkPrivateAccess",
"(",
"Expression",
"source",
",",
"FieldNode",
"fn",
",",
"boolean",
"lhsOfAssignment",
")",
"{",
"if",
"(",
"fn",
"==",
"null",
")",
"return",
";",
"ClassNode",
"enclosingClassNode",
"=",
"typeCheckingContext",
".",
... | Given a field node, checks if we are accessing or setting a private field from an inner class. | [
"Given",
"a",
"field",
"node",
"checks",
"if",
"we",
"are",
"accessing",
"or",
"setting",
"a",
"private",
"field",
"from",
"an",
"inner",
"class",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L502-L526 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/util/ParameterUtil.java | ParameterUtil.isSet | public static boolean isSet (HttpServletRequest req, String name, boolean defaultValue)
{
String value = getParameter(req, name, true);
return (value == null) ? defaultValue : !StringUtil.isBlank(req.getParameter(name));
} | java | public static boolean isSet (HttpServletRequest req, String name, boolean defaultValue)
{
String value = getParameter(req, name, true);
return (value == null) ? defaultValue : !StringUtil.isBlank(req.getParameter(name));
} | [
"public",
"static",
"boolean",
"isSet",
"(",
"HttpServletRequest",
"req",
",",
"String",
"name",
",",
"boolean",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"getParameter",
"(",
"req",
",",
"name",
",",
"true",
")",
";",
"return",
"(",
"value",
"==",... | Returns true if the specified parameter is set to a non-blank value in the request, false if
the value is blank, or <code>defaultValue</code> if the parameter is unspecified.
@return true if the specified parameter is set to a non-blank value in the request, false if
the value is blank, or <code>defaultValue</code> if the parameter is unspecified. | [
"Returns",
"true",
"if",
"the",
"specified",
"parameter",
"is",
"set",
"to",
"a",
"non",
"-",
"blank",
"value",
"in",
"the",
"request",
"false",
"if",
"the",
"value",
"is",
"blank",
"or",
"<code",
">",
"defaultValue<",
"/",
"code",
">",
"if",
"the",
"p... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/util/ParameterUtil.java#L300-L304 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/routing/util/EncodingManager.java | EncodingManager.acceptWay | public boolean acceptWay(ReaderWay way, AcceptWay acceptWay) {
if (!acceptWay.isEmpty())
throw new IllegalArgumentException("AcceptWay must be empty");
for (AbstractFlagEncoder encoder : edgeEncoders) {
acceptWay.put(encoder.toString(), encoder.getAccess(way));
}
return acceptWay.hasAccepted();
} | java | public boolean acceptWay(ReaderWay way, AcceptWay acceptWay) {
if (!acceptWay.isEmpty())
throw new IllegalArgumentException("AcceptWay must be empty");
for (AbstractFlagEncoder encoder : edgeEncoders) {
acceptWay.put(encoder.toString(), encoder.getAccess(way));
}
return acceptWay.hasAccepted();
} | [
"public",
"boolean",
"acceptWay",
"(",
"ReaderWay",
"way",
",",
"AcceptWay",
"acceptWay",
")",
"{",
"if",
"(",
"!",
"acceptWay",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"AcceptWay must be empty\"",
")",
";",
"for",
"("... | Determine whether a way is routable for one of the added encoders.
@return if at least one encoder consumes the specified way. Additionally the specified acceptWay is changed
to provide more details. | [
"Determine",
"whether",
"a",
"way",
"is",
"routable",
"for",
"one",
"of",
"the",
"added",
"encoders",
"."
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java#L384-L392 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/favorites/FavoritesController.java | FavoritesController.initializeView | @RenderMapping
public String initializeView(PortletRequest req, Model model) {
final IUserInstance ui =
userInstanceManager.getUserInstance(portalRequestUtils.getCurrentPortalRequest());
final UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
final IUserLayoutManager ulm = upm.getUserLayoutManager();
final IUserLayout userLayout = ulm.getUserLayout();
// TODO: the portlet could predicate including a non-null marketplace portlet fname
// on the accessing user having permission to render the portlet referenced by that fname
// so that portlet would gracefully degrade when configured with bad marketplace portlet
// fname
// and also gracefully degrade when the accessing user doesn't have permission to access an
// otherwise
// viable configured marketplace. This complexity may not be worth it. Anyway it is not
// yet implemented.
model.addAttribute("marketplaceFname", this.marketplaceFName);
final List<IUserLayoutNodeDescription> collections =
favoritesUtils.getFavoriteCollections(userLayout);
model.addAttribute("collections", collections);
final List<IUserLayoutNodeDescription> rawFavorites =
favoritesUtils.getFavoritePortletLayoutNodes(userLayout);
/*
* Filter the collection by SUBSCRIBE permission.
*
* NOTE: In the "regular" (non-Favorites) layout, this permissions check is handled by
* the rendering engine. It will refuse to spawn a worker for a portlet to which you
* cannot SUBSCRIBE.
*/
final String username =
req.getRemoteUser() != null
? req.getRemoteUser()
: PersonFactory.getGuestUsernames().get(0); // First item is the default
final IAuthorizationPrincipal principal =
authorizationService.newPrincipal(username, IPerson.class);
final List<IUserLayoutNodeDescription> favorites = new ArrayList<>();
for (IUserLayoutNodeDescription nodeDescription : rawFavorites) {
if (nodeDescription instanceof IUserLayoutChannelDescription) {
final IUserLayoutChannelDescription channelDescription =
(IUserLayoutChannelDescription) nodeDescription;
if (principal.canRender(channelDescription.getChannelPublishId())) {
favorites.add(nodeDescription);
}
}
}
model.addAttribute("favorites", favorites);
// default to the regular old view
String viewName = "jsp/Favorites/view";
if (collections.isEmpty() && favorites.isEmpty()) {
// special edge case of zero favorites, switch to special view
viewName = "jsp/Favorites/view_zero";
}
logger.debug(
"Favorites Portlet VIEW mode render populated model [{}] for render by view {}.",
model,
viewName);
return viewName;
} | java | @RenderMapping
public String initializeView(PortletRequest req, Model model) {
final IUserInstance ui =
userInstanceManager.getUserInstance(portalRequestUtils.getCurrentPortalRequest());
final UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
final IUserLayoutManager ulm = upm.getUserLayoutManager();
final IUserLayout userLayout = ulm.getUserLayout();
// TODO: the portlet could predicate including a non-null marketplace portlet fname
// on the accessing user having permission to render the portlet referenced by that fname
// so that portlet would gracefully degrade when configured with bad marketplace portlet
// fname
// and also gracefully degrade when the accessing user doesn't have permission to access an
// otherwise
// viable configured marketplace. This complexity may not be worth it. Anyway it is not
// yet implemented.
model.addAttribute("marketplaceFname", this.marketplaceFName);
final List<IUserLayoutNodeDescription> collections =
favoritesUtils.getFavoriteCollections(userLayout);
model.addAttribute("collections", collections);
final List<IUserLayoutNodeDescription> rawFavorites =
favoritesUtils.getFavoritePortletLayoutNodes(userLayout);
/*
* Filter the collection by SUBSCRIBE permission.
*
* NOTE: In the "regular" (non-Favorites) layout, this permissions check is handled by
* the rendering engine. It will refuse to spawn a worker for a portlet to which you
* cannot SUBSCRIBE.
*/
final String username =
req.getRemoteUser() != null
? req.getRemoteUser()
: PersonFactory.getGuestUsernames().get(0); // First item is the default
final IAuthorizationPrincipal principal =
authorizationService.newPrincipal(username, IPerson.class);
final List<IUserLayoutNodeDescription> favorites = new ArrayList<>();
for (IUserLayoutNodeDescription nodeDescription : rawFavorites) {
if (nodeDescription instanceof IUserLayoutChannelDescription) {
final IUserLayoutChannelDescription channelDescription =
(IUserLayoutChannelDescription) nodeDescription;
if (principal.canRender(channelDescription.getChannelPublishId())) {
favorites.add(nodeDescription);
}
}
}
model.addAttribute("favorites", favorites);
// default to the regular old view
String viewName = "jsp/Favorites/view";
if (collections.isEmpty() && favorites.isEmpty()) {
// special edge case of zero favorites, switch to special view
viewName = "jsp/Favorites/view_zero";
}
logger.debug(
"Favorites Portlet VIEW mode render populated model [{}] for render by view {}.",
model,
viewName);
return viewName;
} | [
"@",
"RenderMapping",
"public",
"String",
"initializeView",
"(",
"PortletRequest",
"req",
",",
"Model",
"model",
")",
"{",
"final",
"IUserInstance",
"ui",
"=",
"userInstanceManager",
".",
"getUserInstance",
"(",
"portalRequestUtils",
".",
"getCurrentPortalRequest",
"(... | Handles all Favorites portlet VIEW mode renders. Populates model with user's favorites and
selects a view to display those favorites.
<p>View selection:
<p>Returns "jsp/Favorites/view" in the normal case where the user has at least one favorited
portlet or favorited collection.
<p>Returns "jsp/Favorites/view_zero" in the edge case where the user has zero favorited
portlets AND zero favorited collections.
<p>Model: marketPlaceFname --> String functional name of Marketplace portlet, or null if not
available. collections --> List of favorited collections (IUserLayoutNodeDescription s)
favorites --> List of favorited individual portlets (IUserLayoutNodeDescription s)
@param model . Spring model. This method adds three model attributes.
@return jsp/Favorites/view[_zero] | [
"Handles",
"all",
"Favorites",
"portlet",
"VIEW",
"mode",
"renders",
".",
"Populates",
"model",
"with",
"user",
"s",
"favorites",
"and",
"selects",
"a",
"view",
"to",
"display",
"those",
"favorites",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/favorites/FavoritesController.java#L86-L151 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/Driver.java | Driver.makeConnection | private static Connection makeConnection(String url, Properties props) throws SQLException {
return new PgConnection(hostSpecs(props), user(props), database(props), props, url);
} | java | private static Connection makeConnection(String url, Properties props) throws SQLException {
return new PgConnection(hostSpecs(props), user(props), database(props), props, url);
} | [
"private",
"static",
"Connection",
"makeConnection",
"(",
"String",
"url",
",",
"Properties",
"props",
")",
"throws",
"SQLException",
"{",
"return",
"new",
"PgConnection",
"(",
"hostSpecs",
"(",
"props",
")",
",",
"user",
"(",
"props",
")",
",",
"database",
... | Create a connection from URL and properties. Always does the connection work in the current
thread without enforcing a timeout, regardless of any timeout specified in the properties.
@param url the original URL
@param props the parsed/defaulted connection properties
@return a new connection
@throws SQLException if the connection could not be made | [
"Create",
"a",
"connection",
"from",
"URL",
"and",
"properties",
".",
"Always",
"does",
"the",
"connection",
"work",
"in",
"the",
"current",
"thread",
"without",
"enforcing",
"a",
"timeout",
"regardless",
"of",
"any",
"timeout",
"specified",
"in",
"the",
"prop... | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/Driver.java#L457-L459 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.audit.source/src/com/ibm/ws/security/audit/source/AuditServiceImpl.java | AuditServiceImpl.map2GenericData | private GenericData map2GenericData(GenericData gdo, Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
if (entry.getKey().equals(AuditEvent.TARGET_APPNAME)) {
gdo.addPair(entry.getKey(), AuditUtils.getJ2EEComponentName());
}
} else {
gdo.addPair(entry.getKey(), entry.getValue().toString());
}
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "gdo: " + gdo.toString());
}
return gdo;
} | java | private GenericData map2GenericData(GenericData gdo, Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
if (entry.getKey().equals(AuditEvent.TARGET_APPNAME)) {
gdo.addPair(entry.getKey(), AuditUtils.getJ2EEComponentName());
}
} else {
gdo.addPair(entry.getKey(), entry.getValue().toString());
}
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "gdo: " + gdo.toString());
}
return gdo;
} | [
"private",
"GenericData",
"map2GenericData",
"(",
"GenericData",
"gdo",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
... | Given a Map, add the corresponding audit data to the given GenericData object.
@param gdo - GenericData object
@param map - Java Map object | [
"Given",
"a",
"Map",
"add",
"the",
"corresponding",
"audit",
"data",
"to",
"the",
"given",
"GenericData",
"object",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.audit.source/src/com/ibm/ws/security/audit/source/AuditServiceImpl.java#L416-L430 |
Cornutum/tcases | tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java | TupleGenerator.completeSatisfied | private boolean completeSatisfied( TestCaseDef testCase, VarTupleSet tuples, List<VarDef> vars)
{
List<VarDef> varsRemaining = getVarsRemaining( vars, testCase);
VarDef varApplicable;
boolean complete;
// Any variables remaining unbound?
if( varsRemaining.isEmpty())
{
// No, this test case is complete.
complete = true;
}
// Any variables remaining that are currently applicable to this test case?
else if( (varApplicable = varsRemaining.stream().filter( v -> testCase.isApplicable(v)).findFirst().orElse( null)) == null)
{
// No, continue with an NA binding for the next variable
testCase.addCompatible( getNaBindingFor( varsRemaining.get( 0)));
complete = makeComplete( testCase, tuples, varsRemaining);
}
else
{
// Find an applicable binding that will lead to a complete test case
int prevBindings = testCase.getBindingCount();
Iterator<Tuple> bindingTuples = getBindingsFor( tuples, varApplicable);
for( complete = false;
// More tuples to try?
bindingTuples.hasNext()
&& !(
// Compatible tuple found?
testCase.addCompatible( (bindingTuples.next())) != null
// Did this tuple create an infeasible combination?
&& !testCase.isInfeasible()
// Can we complete bindings for remaining variables?
&& (complete = makeComplete( testCase, tuples, varsRemaining)));
// No path to completion with this tuple -- try the next one.
testCase.revertBindings( prevBindings));
}
return complete;
} | java | private boolean completeSatisfied( TestCaseDef testCase, VarTupleSet tuples, List<VarDef> vars)
{
List<VarDef> varsRemaining = getVarsRemaining( vars, testCase);
VarDef varApplicable;
boolean complete;
// Any variables remaining unbound?
if( varsRemaining.isEmpty())
{
// No, this test case is complete.
complete = true;
}
// Any variables remaining that are currently applicable to this test case?
else if( (varApplicable = varsRemaining.stream().filter( v -> testCase.isApplicable(v)).findFirst().orElse( null)) == null)
{
// No, continue with an NA binding for the next variable
testCase.addCompatible( getNaBindingFor( varsRemaining.get( 0)));
complete = makeComplete( testCase, tuples, varsRemaining);
}
else
{
// Find an applicable binding that will lead to a complete test case
int prevBindings = testCase.getBindingCount();
Iterator<Tuple> bindingTuples = getBindingsFor( tuples, varApplicable);
for( complete = false;
// More tuples to try?
bindingTuples.hasNext()
&& !(
// Compatible tuple found?
testCase.addCompatible( (bindingTuples.next())) != null
// Did this tuple create an infeasible combination?
&& !testCase.isInfeasible()
// Can we complete bindings for remaining variables?
&& (complete = makeComplete( testCase, tuples, varsRemaining)));
// No path to completion with this tuple -- try the next one.
testCase.revertBindings( prevBindings));
}
return complete;
} | [
"private",
"boolean",
"completeSatisfied",
"(",
"TestCaseDef",
"testCase",
",",
"VarTupleSet",
"tuples",
",",
"List",
"<",
"VarDef",
">",
"vars",
")",
"{",
"List",
"<",
"VarDef",
">",
"varsRemaining",
"=",
"getVarsRemaining",
"(",
"vars",
",",
"testCase",
")",... | Using selections from the given set of tuples, completes binding for all remaining variables.
Returns true if all variables have been bound. | [
"Using",
"selections",
"from",
"the",
"given",
"set",
"of",
"tuples",
"completes",
"binding",
"for",
"all",
"remaining",
"variables",
".",
"Returns",
"true",
"if",
"all",
"variables",
"have",
"been",
"bound",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java#L431-L476 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/JmsDestinationImpl.java | JmsDestinationImpl.isDifferent | private boolean isDifferent(String key, Object value) {
// Get the value from the properties Map for the specified key
Object currentVal = properties.get(key);
if (currentVal == null) {
// If the currentVal is null, then test value against null
return value != null;
}
else {
// For non-null, need to use object.equals method
return !currentVal.equals(value);
}
} | java | private boolean isDifferent(String key, Object value) {
// Get the value from the properties Map for the specified key
Object currentVal = properties.get(key);
if (currentVal == null) {
// If the currentVal is null, then test value against null
return value != null;
}
else {
// For non-null, need to use object.equals method
return !currentVal.equals(value);
}
} | [
"private",
"boolean",
"isDifferent",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"// Get the value from the properties Map for the specified key",
"Object",
"currentVal",
"=",
"properties",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"currentVal",
"==",... | Compare the specified value with that in the properties Map
This utility method is used from the set* methods to determine
if the value is being changed and hence the cache needs to be
cleared.
@param key The name of the property in the Map
@param value The value to be tested for equality
@return true if the values are different | [
"Compare",
"the",
"specified",
"value",
"with",
"that",
"in",
"the",
"properties",
"Map",
"This",
"utility",
"method",
"is",
"used",
"from",
"the",
"set",
"*",
"methods",
"to",
"determine",
"if",
"the",
"value",
"is",
"being",
"changed",
"and",
"hence",
"t... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/JmsDestinationImpl.java#L1489-L1500 |
alkacon/opencms-core | src/org/opencms/lock/CmsLockUtil.java | CmsLockUtil.ensureLock | public static CmsLockActionRecord ensureLock(CmsObject cms, CmsResource resource) throws CmsException {
LockChange change = LockChange.unchanged;
List<CmsResource> blockingResources = cms.getBlockingLockedResources(resource);
if ((blockingResources != null) && !blockingResources.isEmpty()) {
throw new CmsException(
Messages.get().container(
Messages.ERR_RESOURCE_HAS_BLOCKING_LOCKED_CHILDREN_1,
cms.getSitePath(resource)));
}
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsLock lock = cms.getLock(resource);
if (!lock.isOwnedBy(user)) {
cms.lockResourceTemporary(resource);
change = LockChange.locked;
lock = cms.getLock(resource);
} else if (!lock.isOwnedInProjectBy(user, cms.getRequestContext().getCurrentProject())) {
cms.changeLock(resource);
change = LockChange.changed;
lock = cms.getLock(resource);
}
return new CmsLockActionRecord(lock, change);
} | java | public static CmsLockActionRecord ensureLock(CmsObject cms, CmsResource resource) throws CmsException {
LockChange change = LockChange.unchanged;
List<CmsResource> blockingResources = cms.getBlockingLockedResources(resource);
if ((blockingResources != null) && !blockingResources.isEmpty()) {
throw new CmsException(
Messages.get().container(
Messages.ERR_RESOURCE_HAS_BLOCKING_LOCKED_CHILDREN_1,
cms.getSitePath(resource)));
}
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsLock lock = cms.getLock(resource);
if (!lock.isOwnedBy(user)) {
cms.lockResourceTemporary(resource);
change = LockChange.locked;
lock = cms.getLock(resource);
} else if (!lock.isOwnedInProjectBy(user, cms.getRequestContext().getCurrentProject())) {
cms.changeLock(resource);
change = LockChange.changed;
lock = cms.getLock(resource);
}
return new CmsLockActionRecord(lock, change);
} | [
"public",
"static",
"CmsLockActionRecord",
"ensureLock",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"LockChange",
"change",
"=",
"LockChange",
".",
"unchanged",
";",
"List",
"<",
"CmsResource",
">",
"blockingResource... | Static helper method to lock a resource.<p>
@param cms the CMS context to use
@param resource the resource to lock
@return the action that was taken
@throws CmsException if something goes wrong | [
"Static",
"helper",
"method",
"to",
"lock",
"a",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/lock/CmsLockUtil.java#L198-L220 |
igniterealtime/Smack | smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java | MediaNegotiator.receiveSessionInfoAction | private IQ receiveSessionInfoAction(Jingle jingle, JingleDescription description) throws JingleException {
IQ response = null;
PayloadType oldBestCommonAudioPt = bestCommonAudioPt;
List<PayloadType> offeredPayloads;
boolean ptChange = false;
offeredPayloads = description.getAudioPayloadTypesList();
if (!offeredPayloads.isEmpty()) {
synchronized (remoteAudioPts) {
remoteAudioPts.clear();
remoteAudioPts.addAll(offeredPayloads);
}
// Calculate the best common codec
bestCommonAudioPt = calculateBestCommonAudioPt(remoteAudioPts);
if (bestCommonAudioPt != null) {
// and send an accept if we have an agreement...
ptChange = !bestCommonAudioPt.equals(oldBestCommonAudioPt);
if (oldBestCommonAudioPt == null || ptChange) {
// response = createAcceptMessage();
}
} else {
throw new JingleException(JingleError.NO_COMMON_PAYLOAD);
}
}
// Parse the Jingle and get the payload accepted
return response;
} | java | private IQ receiveSessionInfoAction(Jingle jingle, JingleDescription description) throws JingleException {
IQ response = null;
PayloadType oldBestCommonAudioPt = bestCommonAudioPt;
List<PayloadType> offeredPayloads;
boolean ptChange = false;
offeredPayloads = description.getAudioPayloadTypesList();
if (!offeredPayloads.isEmpty()) {
synchronized (remoteAudioPts) {
remoteAudioPts.clear();
remoteAudioPts.addAll(offeredPayloads);
}
// Calculate the best common codec
bestCommonAudioPt = calculateBestCommonAudioPt(remoteAudioPts);
if (bestCommonAudioPt != null) {
// and send an accept if we have an agreement...
ptChange = !bestCommonAudioPt.equals(oldBestCommonAudioPt);
if (oldBestCommonAudioPt == null || ptChange) {
// response = createAcceptMessage();
}
} else {
throw new JingleException(JingleError.NO_COMMON_PAYLOAD);
}
}
// Parse the Jingle and get the payload accepted
return response;
} | [
"private",
"IQ",
"receiveSessionInfoAction",
"(",
"Jingle",
"jingle",
",",
"JingleDescription",
"description",
")",
"throws",
"JingleException",
"{",
"IQ",
"response",
"=",
"null",
";",
"PayloadType",
"oldBestCommonAudioPt",
"=",
"bestCommonAudioPt",
";",
"List",
"<",... | A content info has been received. This is done for publishing the
list of payload types...
@param jingle
The input packet
@return a Jingle packet
@throws JingleException | [
"A",
"content",
"info",
"has",
"been",
"received",
".",
"This",
"is",
"done",
"for",
"publishing",
"the",
"list",
"of",
"payload",
"types",
"..."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java#L271-L300 |
OwlPlatform/java-owl-sensor | src/main/java/com/owlplatform/sensor/SensorIoHandler.java | SensorIoHandler.messageSent | @Override
public void messageSent(IoSession session, Object message) throws Exception {
log.debug("{} --> {}", message, session);
if (this.sensorIoAdapter == null) {
log.warn("No SensorIoAdapter defined. Ignoring message to {}: {}",
session, message);
return;
}
if (message instanceof HandshakeMessage) {
log.debug("Handshake message sent to {}: {}", session, message);
if (this.sensorIoAdapter != null) {
this.sensorIoAdapter.handshakeMessageSent(session,
(HandshakeMessage) message);
}
} else if (message instanceof SampleMessage) {
if (this.sensorIoAdapter != null) {
this.sensorIoAdapter.sensorSampleSent(session,
(SampleMessage) message);
}
} else {
log.warn("Unhandled message type sent to {}: {}", session, message);
}
} | java | @Override
public void messageSent(IoSession session, Object message) throws Exception {
log.debug("{} --> {}", message, session);
if (this.sensorIoAdapter == null) {
log.warn("No SensorIoAdapter defined. Ignoring message to {}: {}",
session, message);
return;
}
if (message instanceof HandshakeMessage) {
log.debug("Handshake message sent to {}: {}", session, message);
if (this.sensorIoAdapter != null) {
this.sensorIoAdapter.handshakeMessageSent(session,
(HandshakeMessage) message);
}
} else if (message instanceof SampleMessage) {
if (this.sensorIoAdapter != null) {
this.sensorIoAdapter.sensorSampleSent(session,
(SampleMessage) message);
}
} else {
log.warn("Unhandled message type sent to {}: {}", session, message);
}
} | [
"@",
"Override",
"public",
"void",
"messageSent",
"(",
"IoSession",
"session",
",",
"Object",
"message",
")",
"throws",
"Exception",
"{",
"log",
".",
"debug",
"(",
"\"{} --> {}\"",
",",
"message",
",",
"session",
")",
";",
"if",
"(",
"this",
".",
"sensorIo... | Demultiplexes the sent message and passes it to the appropriate method of the IOAdapter.
@see SensorIoAdapter#sensorSampleSent(IoSession, SampleMessage)
@see SensorIoAdapter#handshakeMessageSent(IoSession, HandshakeMessage) | [
"Demultiplexes",
"the",
"sent",
"message",
"and",
"passes",
"it",
"to",
"the",
"appropriate",
"method",
"of",
"the",
"IOAdapter",
"."
] | train | https://github.com/OwlPlatform/java-owl-sensor/blob/7d98e985f2fc150dd696ca5683ad9ef6514be92b/src/main/java/com/owlplatform/sensor/SensorIoHandler.java#L114-L138 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java | LoggingHandlerEnvironmentFacet.create | public static LoggingHandlerEnvironmentFacet create(final Log mavenLog,
final Class<? extends AbstractJaxbMojo> caller,
final String encoding) {
// Check sanity
Validate.notNull(mavenLog, "mavenLog");
Validate.notNull(caller, "caller");
Validate.notEmpty(encoding, "encoding");
// Find the standard log prefix for the tool in question.
final String logPrefix = caller.getClass().getCanonicalName().toUpperCase().contains("XJC")
? "XJC"
: "SchemaGen";
// All done.
return new LoggingHandlerEnvironmentFacet(logPrefix, mavenLog, encoding, DEFAULT_LOGGER_NAMES);
} | java | public static LoggingHandlerEnvironmentFacet create(final Log mavenLog,
final Class<? extends AbstractJaxbMojo> caller,
final String encoding) {
// Check sanity
Validate.notNull(mavenLog, "mavenLog");
Validate.notNull(caller, "caller");
Validate.notEmpty(encoding, "encoding");
// Find the standard log prefix for the tool in question.
final String logPrefix = caller.getClass().getCanonicalName().toUpperCase().contains("XJC")
? "XJC"
: "SchemaGen";
// All done.
return new LoggingHandlerEnvironmentFacet(logPrefix, mavenLog, encoding, DEFAULT_LOGGER_NAMES);
} | [
"public",
"static",
"LoggingHandlerEnvironmentFacet",
"create",
"(",
"final",
"Log",
"mavenLog",
",",
"final",
"Class",
"<",
"?",
"extends",
"AbstractJaxbMojo",
">",
"caller",
",",
"final",
"String",
"encoding",
")",
"{",
"// Check sanity",
"Validate",
".",
"notNu... | Factory method creating a new LoggingHandlerEnvironmentFacet wrapping the supplied properties.
@param mavenLog The active Maven Log.
@param caller The AbstractJaxbMojo subclass which invoked this LoggingHandlerEnvironmentFacet factory method.
@param encoding The encoding used by the Maven Mojo subclass.
@return A fully set up LoggingHandlerEnvironmentFacet | [
"Factory",
"method",
"creating",
"a",
"new",
"LoggingHandlerEnvironmentFacet",
"wrapping",
"the",
"supplied",
"properties",
"."
] | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java#L142-L158 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.makeAdhocBibliography | public static Bibliography makeAdhocBibliography(String style, String outputFormat,
CSLItemData... items) throws IOException {
ItemDataProvider provider = new ListItemDataProvider(items);
try (CSL csl = new CSL(provider, style)) {
csl.setOutputFormat(outputFormat);
String[] ids = new String[items.length];
for (int i = 0; i < items.length; ++i) {
ids[i] = items[i].getId();
}
csl.registerCitationItems(ids);
return csl.makeBibliography();
}
} | java | public static Bibliography makeAdhocBibliography(String style, String outputFormat,
CSLItemData... items) throws IOException {
ItemDataProvider provider = new ListItemDataProvider(items);
try (CSL csl = new CSL(provider, style)) {
csl.setOutputFormat(outputFormat);
String[] ids = new String[items.length];
for (int i = 0; i < items.length; ++i) {
ids[i] = items[i].getId();
}
csl.registerCitationItems(ids);
return csl.makeBibliography();
}
} | [
"public",
"static",
"Bibliography",
"makeAdhocBibliography",
"(",
"String",
"style",
",",
"String",
"outputFormat",
",",
"CSLItemData",
"...",
"items",
")",
"throws",
"IOException",
"{",
"ItemDataProvider",
"provider",
"=",
"new",
"ListItemDataProvider",
"(",
"items",... | Creates an ad hoc bibliography from the given citation items. Calling
this method is rather expensive as it initializes the CSL processor.
If you need to create bibliographies multiple times in your application
you should create the processor yourself and cache it if necessary.
@param style the citation style to use. May either be a serialized
XML representation of the style or a style's name such as <code>ieee</code>.
In the latter case, the processor loads the style from the classpath (e.g.
<code>/ieee.csl</code>)
@param outputFormat the processor's output format (one of
<code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>,
<code>"fo"</code>, or <code>"rtf"</code>)
@param items the citation items to add to the bibliography
@return the bibliography
@throws IOException if the underlying JavaScript files or the CSL style
could not be loaded | [
"Creates",
"an",
"ad",
"hoc",
"bibliography",
"from",
"the",
"given",
"citation",
"items",
".",
"Calling",
"this",
"method",
"is",
"rather",
"expensive",
"as",
"it",
"initializes",
"the",
"CSL",
"processor",
".",
"If",
"you",
"need",
"to",
"create",
"bibliog... | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L952-L966 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/info/ChainedProperty.java | ChainedProperty.tail | public ChainedProperty<?> tail() {
if (getChainCount() == 0) {
throw new IllegalStateException();
}
if (getChainCount() == 1) {
if (!isOuterJoin(1)) {
return get(mChain[0]);
} else {
return get(mChain[0], null, new boolean[] {true});
}
}
StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
System.arraycopy(mChain, 1, newChain, 0, newChain.length);
boolean[] newOuterJoin = mOuterJoin;
if (newOuterJoin != null) {
newOuterJoin = new boolean[newChain.length + 1];
System.arraycopy(mOuterJoin, 1, newOuterJoin, 0, mOuterJoin.length - 1);
}
return get(mChain[0], newChain, newOuterJoin);
} | java | public ChainedProperty<?> tail() {
if (getChainCount() == 0) {
throw new IllegalStateException();
}
if (getChainCount() == 1) {
if (!isOuterJoin(1)) {
return get(mChain[0]);
} else {
return get(mChain[0], null, new boolean[] {true});
}
}
StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
System.arraycopy(mChain, 1, newChain, 0, newChain.length);
boolean[] newOuterJoin = mOuterJoin;
if (newOuterJoin != null) {
newOuterJoin = new boolean[newChain.length + 1];
System.arraycopy(mOuterJoin, 1, newOuterJoin, 0, mOuterJoin.length - 1);
}
return get(mChain[0], newChain, newOuterJoin);
} | [
"public",
"ChainedProperty",
"<",
"?",
">",
"tail",
"(",
")",
"{",
"if",
"(",
"getChainCount",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"}",
"if",
"(",
"getChainCount",
"(",
")",
"==",
"1",
")",
"{",
"i... | Returns a new ChainedProperty which contains everything that follows
this ChainedProperty's prime property.
@throws IllegalStateException if chain count is zero | [
"Returns",
"a",
"new",
"ChainedProperty",
"which",
"contains",
"everything",
"that",
"follows",
"this",
"ChainedProperty",
"s",
"prime",
"property",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/info/ChainedProperty.java#L440-L462 |
wildfly-swarm-archive/ARCHIVE-wildfly-swarm | container/runtime/src/main/java/org/wildfly/swarm/container/runtime/RuntimeServer.java | RuntimeServer.visitFractions | private <T> void visitFractions(Container container, T context, FractionProcessor<T> fn) {
OUTER:
for (ServerConfiguration eachConfig : this.configList) {
boolean found = false;
INNER:
for (Fraction eachFraction : container.fractions()) {
if (eachConfig.getType().isAssignableFrom(eachFraction.getClass())) {
found = true;
fn.accept(context, eachConfig, eachFraction);
break INNER;
}
}
if (!found && !eachConfig.isIgnorable()) {
System.err.println("*** unable to find fraction for: " + eachConfig.getType());
}
}
} | java | private <T> void visitFractions(Container container, T context, FractionProcessor<T> fn) {
OUTER:
for (ServerConfiguration eachConfig : this.configList) {
boolean found = false;
INNER:
for (Fraction eachFraction : container.fractions()) {
if (eachConfig.getType().isAssignableFrom(eachFraction.getClass())) {
found = true;
fn.accept(context, eachConfig, eachFraction);
break INNER;
}
}
if (!found && !eachConfig.isIgnorable()) {
System.err.println("*** unable to find fraction for: " + eachConfig.getType());
}
}
} | [
"private",
"<",
"T",
">",
"void",
"visitFractions",
"(",
"Container",
"container",
",",
"T",
"context",
",",
"FractionProcessor",
"<",
"T",
">",
"fn",
")",
"{",
"OUTER",
":",
"for",
"(",
"ServerConfiguration",
"eachConfig",
":",
"this",
".",
"configList",
... | Wraps common iteration pattern over fraction and server configurations
@param container
@param context processing context (i.e. accumulator)
@param fn a {@link org.wildfly.swarm.container.runtime.RuntimeServer.FractionProcessor} instance | [
"Wraps",
"common",
"iteration",
"pattern",
"over",
"fraction",
"and",
"server",
"configurations"
] | train | https://github.com/wildfly-swarm-archive/ARCHIVE-wildfly-swarm/blob/28ef71bcfa743a7267666e0ed2919c37b356c09b/container/runtime/src/main/java/org/wildfly/swarm/container/runtime/RuntimeServer.java#L577-L594 |
albfernandez/itext2 | src/main/java/com/lowagie/text/Image.java | Image.scaleAbsolute | public void scaleAbsolute(float newWidth, float newHeight) {
plainWidth = newWidth;
plainHeight = newHeight;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
} | java | public void scaleAbsolute(float newWidth, float newHeight) {
plainWidth = newWidth;
plainHeight = newHeight;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
} | [
"public",
"void",
"scaleAbsolute",
"(",
"float",
"newWidth",
",",
"float",
"newHeight",
")",
"{",
"plainWidth",
"=",
"newWidth",
";",
"plainHeight",
"=",
"newHeight",
";",
"float",
"[",
"]",
"matrix",
"=",
"matrix",
"(",
")",
";",
"scaledWidth",
"=",
"matr... | Scale the image to an absolute width and an absolute height.
@param newWidth
the new width
@param newHeight
the new height | [
"Scale",
"the",
"image",
"to",
"an",
"absolute",
"width",
"and",
"an",
"absolute",
"height",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Image.java#L1241-L1248 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/Muxer.java | Muxer.getNextRelativePts | protected long getNextRelativePts(long absPts, int trackIndex) {
if (mFirstPts == 0) {
mFirstPts = absPts;
return 0;
}
return getSafePts(absPts - mFirstPts, trackIndex);
} | java | protected long getNextRelativePts(long absPts, int trackIndex) {
if (mFirstPts == 0) {
mFirstPts = absPts;
return 0;
}
return getSafePts(absPts - mFirstPts, trackIndex);
} | [
"protected",
"long",
"getNextRelativePts",
"(",
"long",
"absPts",
",",
"int",
"trackIndex",
")",
"{",
"if",
"(",
"mFirstPts",
"==",
"0",
")",
"{",
"mFirstPts",
"=",
"absPts",
";",
"return",
"0",
";",
"}",
"return",
"getSafePts",
"(",
"absPts",
"-",
"mFir... | Return a relative pts given an absolute pts and trackIndex.
This method advances the state of the Muxer, and must only
be called once per call to {@link #writeSampleData(android.media.MediaCodec, int, int, java.nio.ByteBuffer, android.media.MediaCodec.BufferInfo)}. | [
"Return",
"a",
"relative",
"pts",
"given",
"an",
"absolute",
"pts",
"and",
"trackIndex",
"."
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/Muxer.java#L164-L170 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java | BingNewsImpl.searchAsync | public Observable<NewsModel> searchAsync(String query, SearchOptionalParameter searchOptionalParameter) {
return searchWithServiceResponseAsync(query, searchOptionalParameter).map(new Func1<ServiceResponse<NewsModel>, NewsModel>() {
@Override
public NewsModel call(ServiceResponse<NewsModel> response) {
return response.body();
}
});
} | java | public Observable<NewsModel> searchAsync(String query, SearchOptionalParameter searchOptionalParameter) {
return searchWithServiceResponseAsync(query, searchOptionalParameter).map(new Func1<ServiceResponse<NewsModel>, NewsModel>() {
@Override
public NewsModel call(ServiceResponse<NewsModel> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"NewsModel",
">",
"searchAsync",
"(",
"String",
"query",
",",
"SearchOptionalParameter",
"searchOptionalParameter",
")",
"{",
"return",
"searchWithServiceResponseAsync",
"(",
"query",
",",
"searchOptionalParameter",
")",
".",
"map",
"(",
"... | The News Search API lets you send a search query to Bing and get back a list of news that are relevant to the search query. This section provides technical details about the query parameters and headers that you use to request news and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the web for news](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-news-search/search-the-web).
@param query The user's search query string. The query string cannot be empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit news to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. Use this parameter only with the News Search API. Do not specify this parameter when calling the Trending Topics API or News Category API.
@param searchOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the NewsModel object | [
"The",
"News",
"Search",
"API",
"lets",
"you",
"send",
"a",
"search",
"query",
"to",
"Bing",
"and",
"get",
"back",
"a",
"list",
"of",
"news",
"that",
"are",
"relevant",
"to",
"the",
"search",
"query",
".",
"This",
"section",
"provides",
"technical",
"det... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java#L112-L119 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/JBaseToolbar.java | JBaseToolbar.init | public void init(Object parent, Object record)
{
super.init(parent, record);
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.addButtons();
} | java | public void init(Object parent, Object record)
{
super.init(parent, record);
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.addButtons();
} | [
"public",
"void",
"init",
"(",
"Object",
"parent",
",",
"Object",
"record",
")",
"{",
"super",
".",
"init",
"(",
"parent",
",",
"record",
")",
";",
"this",
".",
"setOpaque",
"(",
"false",
")",
";",
"this",
".",
"setLayout",
"(",
"new",
"BoxLayout",
"... | Constructor.
@param parent The parent screen.
@param record (null for a toolbar). | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/JBaseToolbar.java#L48-L54 |
gresrun/jesque | src/main/java/net/greghaines/jesque/utils/JedisUtils.java | JedisUtils.isKeyUsed | public static boolean isKeyUsed(final Jedis jedis, final String key) {
return !NONE.equalsIgnoreCase(jedis.type(key));
} | java | public static boolean isKeyUsed(final Jedis jedis, final String key) {
return !NONE.equalsIgnoreCase(jedis.type(key));
} | [
"public",
"static",
"boolean",
"isKeyUsed",
"(",
"final",
"Jedis",
"jedis",
",",
"final",
"String",
"key",
")",
"{",
"return",
"!",
"NONE",
".",
"equalsIgnoreCase",
"(",
"jedis",
".",
"type",
"(",
"key",
")",
")",
";",
"}"
] | Determines if the queue identified by the given key is used.
@param jedis
connection to Redis
@param key
the key that identifies a queue
@return true if the key is used, false otherwise | [
"Determines",
"if",
"the",
"queue",
"identified",
"by",
"the",
"given",
"key",
"is",
"used",
"."
] | train | https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/utils/JedisUtils.java#L150-L152 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/repository/store/graph/v1/DeleteHandlerV1.java | DeleteHandlerV1.deleteEdgeReference | public boolean deleteEdgeReference(AtlasEdge edge, TypeCategory typeCategory, boolean isOwned,
boolean forceDeleteStructTrait) throws AtlasBaseException {
// default edge direction is outward
return deleteEdgeReference(edge, typeCategory, isOwned, forceDeleteStructTrait, AtlasRelationshipEdgeDirection.OUT);
} | java | public boolean deleteEdgeReference(AtlasEdge edge, TypeCategory typeCategory, boolean isOwned,
boolean forceDeleteStructTrait) throws AtlasBaseException {
// default edge direction is outward
return deleteEdgeReference(edge, typeCategory, isOwned, forceDeleteStructTrait, AtlasRelationshipEdgeDirection.OUT);
} | [
"public",
"boolean",
"deleteEdgeReference",
"(",
"AtlasEdge",
"edge",
",",
"TypeCategory",
"typeCategory",
",",
"boolean",
"isOwned",
",",
"boolean",
"forceDeleteStructTrait",
")",
"throws",
"AtlasBaseException",
"{",
"// default edge direction is outward",
"return",
"delet... | Force delete is used to remove struct/trait in case of entity updates
@param edge
@param typeCategory
@param isOwned
@param forceDeleteStructTrait
@return returns true if the edge reference is hard deleted
@throws AtlasException | [
"Force",
"delete",
"is",
"used",
"to",
"remove",
"struct",
"/",
"trait",
"in",
"case",
"of",
"entity",
"updates"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/store/graph/v1/DeleteHandlerV1.java#L221-L226 |
alkacon/opencms-core | src/org/opencms/widgets/serialdate/CmsSerialDateBeanMonthlyWeeks.java | CmsSerialDateBeanMonthlyWeeks.toNextDate | private void toNextDate(Calendar date, int interval) {
long previousDate = date.getTimeInMillis();
if (!m_weekOfMonthIterator.hasNext()) {
date.add(Calendar.MONTH, interval);
m_weekOfMonthIterator = m_weeksOfMonth.iterator();
}
toCorrectDateWithDay(date, m_weekOfMonthIterator.next());
if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.
toNextDate(date);
}
} | java | private void toNextDate(Calendar date, int interval) {
long previousDate = date.getTimeInMillis();
if (!m_weekOfMonthIterator.hasNext()) {
date.add(Calendar.MONTH, interval);
m_weekOfMonthIterator = m_weeksOfMonth.iterator();
}
toCorrectDateWithDay(date, m_weekOfMonthIterator.next());
if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.
toNextDate(date);
}
} | [
"private",
"void",
"toNextDate",
"(",
"Calendar",
"date",
",",
"int",
"interval",
")",
"{",
"long",
"previousDate",
"=",
"date",
".",
"getTimeInMillis",
"(",
")",
";",
"if",
"(",
"!",
"m_weekOfMonthIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"date",
"... | Calculates the next date, starting from the provided date.
@param date the current date.
@param interval the number of month to add when moving to the next month. | [
"Calculates",
"the",
"next",
"date",
"starting",
"from",
"the",
"provided",
"date",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/serialdate/CmsSerialDateBeanMonthlyWeeks.java#L150-L162 |
javamelody/javamelody | javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MHtmlEncoder.java | MHtmlEncoder.encodeString | public static void encodeString(final StringBuilder sb, final String s) {
if (s == null) {
return;
}
final int len = s.length();
// réserve un peu plus de place dans le StringBuilder
sb.ensureCapacity(sb.length() + len + len / 4);
int i;
int index;
char c;
for (i = 0; i < len; i++) {
c = s.charAt(i);
// petite optimisation (qui represente 90% des cas...)
if (isSimpleLetterOrDigit(c)) {
sb.append(c);
} else {
// cherche dans le tableau des caractères
index = Arrays.binarySearch(TO_REPLACE, c);
if (index >= 0) {
// si trouvé, append la chaîne remplaçante
sb.append(REPLACE_BY[index]);
} else if (c < '\u0020' || c > '\u007e') {
// si c'est un caractère bizarre non reconnu, on code son numéro décimal (en charset iso-8859-1)
sb.append("&#").append(Integer.toString(c)).append(';');
} else {
// sinon append le caractère sans le modifier
sb.append(c); // nécessite un charset système genre windows-1252
}
}
}
} | java | public static void encodeString(final StringBuilder sb, final String s) {
if (s == null) {
return;
}
final int len = s.length();
// réserve un peu plus de place dans le StringBuilder
sb.ensureCapacity(sb.length() + len + len / 4);
int i;
int index;
char c;
for (i = 0; i < len; i++) {
c = s.charAt(i);
// petite optimisation (qui represente 90% des cas...)
if (isSimpleLetterOrDigit(c)) {
sb.append(c);
} else {
// cherche dans le tableau des caractères
index = Arrays.binarySearch(TO_REPLACE, c);
if (index >= 0) {
// si trouvé, append la chaîne remplaçante
sb.append(REPLACE_BY[index]);
} else if (c < '\u0020' || c > '\u007e') {
// si c'est un caractère bizarre non reconnu, on code son numéro décimal (en charset iso-8859-1)
sb.append("&#").append(Integer.toString(c)).append(';');
} else {
// sinon append le caractère sans le modifier
sb.append(c); // nécessite un charset système genre windows-1252
}
}
}
} | [
"public",
"static",
"void",
"encodeString",
"(",
"final",
"StringBuilder",
"sb",
",",
"final",
"String",
"s",
")",
"{",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"int",
"len",
"=",
"s",
".",
"length",
"(",
")",
";",
"// r... | Append une chaine à un StringBuilder apres l'avoir encodée. Plus la chaine à encoder est longue, plus les gains de perfs sont sensibles.
@param sb
String StringBuilder à appender.
@param s
String Chaine à encoder et à ajouter à <CODE>sb</CODE> | [
"Append",
"une",
"chaine",
"à",
"un",
"StringBuilder",
"apres",
"l",
"avoir",
"encodée",
".",
"Plus",
"la",
"chaine",
"à",
"encoder",
"est",
"longue",
"plus",
"les",
"gains",
"de",
"perfs",
"sont",
"sensibles",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MHtmlEncoder.java#L118-L148 |
alexholmes/htuple | core/src/main/java/org/htuple/Tuple.java | Tuple.setBytes | public Tuple setBytes(Enum<?> eval, BytesWritable val) {
set(eval, (Object) val);
return this;
} | java | public Tuple setBytes(Enum<?> eval, BytesWritable val) {
set(eval, (Object) val);
return this;
} | [
"public",
"Tuple",
"setBytes",
"(",
"Enum",
"<",
"?",
">",
"eval",
",",
"BytesWritable",
"val",
")",
"{",
"set",
"(",
"eval",
",",
"(",
"Object",
")",
"val",
")",
";",
"return",
"this",
";",
"}"
] | Sets a value at a specific position in the tuple.
@param eval the enum which is used to determine the index for the set operation
@param val the value to set
@return a handle to this object to enable builder operations
@see #set(Enum, Object) for more info | [
"Sets",
"a",
"value",
"at",
"a",
"specific",
"position",
"in",
"the",
"tuple",
"."
] | train | https://github.com/alexholmes/htuple/blob/5aba63f78a4a9bb505ad3de0a5b0b392724644c4/core/src/main/java/org/htuple/Tuple.java#L498-L501 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsXmlContent.java | CmsXmlContent.removeValuesInOtherLocales | private void removeValuesInOtherLocales(String elementPath, Locale sourceLocale) {
for (Locale locale : getLocales()) {
if (locale.equals(sourceLocale)) {
continue;
}
while (hasValue(elementPath, locale)) {
removeValue(elementPath, locale, 0);
}
}
} | java | private void removeValuesInOtherLocales(String elementPath, Locale sourceLocale) {
for (Locale locale : getLocales()) {
if (locale.equals(sourceLocale)) {
continue;
}
while (hasValue(elementPath, locale)) {
removeValue(elementPath, locale, 0);
}
}
} | [
"private",
"void",
"removeValuesInOtherLocales",
"(",
"String",
"elementPath",
",",
"Locale",
"sourceLocale",
")",
"{",
"for",
"(",
"Locale",
"locale",
":",
"getLocales",
"(",
")",
")",
"{",
"if",
"(",
"locale",
".",
"equals",
"(",
"sourceLocale",
")",
")",
... | Removes all values of the given path in the other locales.<p>
@param elementPath the element path
@param sourceLocale the source locale | [
"Removes",
"all",
"values",
"of",
"the",
"given",
"path",
"in",
"the",
"other",
"locales",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContent.java#L1112-L1122 |
apiman/apiman | gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java | JdbcRegistry.validateContract | private void validateContract(final Contract contract, Connection connection)
throws RegistrationException {
QueryRunner run = new QueryRunner();
try {
Api api = run.query(connection, "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
Handlers.API_HANDLER, contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion());
if (api == null) {
String apiId = contract.getApiId();
String orgId = contract.getApiOrgId();
throw new ApiNotFoundException(Messages.i18n.format("JdbcRegistry.ApiNotFoundInOrg", apiId, orgId)); //$NON-NLS-1$
}
} catch (SQLException e) {
throw new RegistrationException(Messages.i18n.format("JdbcRegistry.ErrorValidatingApp"), e); //$NON-NLS-1$
}
} | java | private void validateContract(final Contract contract, Connection connection)
throws RegistrationException {
QueryRunner run = new QueryRunner();
try {
Api api = run.query(connection, "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
Handlers.API_HANDLER, contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion());
if (api == null) {
String apiId = contract.getApiId();
String orgId = contract.getApiOrgId();
throw new ApiNotFoundException(Messages.i18n.format("JdbcRegistry.ApiNotFoundInOrg", apiId, orgId)); //$NON-NLS-1$
}
} catch (SQLException e) {
throw new RegistrationException(Messages.i18n.format("JdbcRegistry.ErrorValidatingApp"), e); //$NON-NLS-1$
}
} | [
"private",
"void",
"validateContract",
"(",
"final",
"Contract",
"contract",
",",
"Connection",
"connection",
")",
"throws",
"RegistrationException",
"{",
"QueryRunner",
"run",
"=",
"new",
"QueryRunner",
"(",
")",
";",
"try",
"{",
"Api",
"api",
"=",
"run",
"."... | Ensures that the api referenced by the Contract actually exists (is published).
@param contract
@param connection
@throws RegistrationException | [
"Ensures",
"that",
"the",
"api",
"referenced",
"by",
"the",
"Contract",
"actually",
"exists",
"(",
"is",
"published",
")",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java#L151-L165 |
romannurik/muzei | muzei-api/src/main/java/com/google/android/apps/muzei/api/Artwork.java | Artwork.fromJson | @NonNull
public static Artwork fromJson(@NonNull JSONObject jsonObject) {
@SuppressWarnings("WrongConstant") // Assume the KEY_META_FONT is valid
Builder builder = new Builder()
.title(jsonObject.optString(KEY_TITLE))
.byline(jsonObject.optString(KEY_BYLINE))
.attribution(jsonObject.optString(KEY_ATTRIBUTION))
.token(jsonObject.optString(KEY_TOKEN))
.metaFont(jsonObject.optString(KEY_META_FONT))
.dateAdded(new Date(jsonObject.optLong(KEY_DATE_ADDED, 0)));
String componentName = jsonObject.optString(KEY_COMPONENT_NAME);
if (!TextUtils.isEmpty(componentName)) {
builder.componentName(ComponentName.unflattenFromString(componentName));
}
String imageUri = jsonObject.optString(KEY_IMAGE_URI);
if (!TextUtils.isEmpty(imageUri)) {
builder.imageUri(Uri.parse(imageUri));
}
try {
String viewIntent = jsonObject.optString(KEY_VIEW_INTENT);
String detailsUri = jsonObject.optString(KEY_DETAILS_URI);
if (!TextUtils.isEmpty(viewIntent)) {
builder.viewIntent(Intent.parseUri(viewIntent, Intent.URI_INTENT_SCHEME));
} else if (!TextUtils.isEmpty(detailsUri)) {
builder.viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(detailsUri)));
}
} catch (URISyntaxException ignored) {
}
return builder.build();
} | java | @NonNull
public static Artwork fromJson(@NonNull JSONObject jsonObject) {
@SuppressWarnings("WrongConstant") // Assume the KEY_META_FONT is valid
Builder builder = new Builder()
.title(jsonObject.optString(KEY_TITLE))
.byline(jsonObject.optString(KEY_BYLINE))
.attribution(jsonObject.optString(KEY_ATTRIBUTION))
.token(jsonObject.optString(KEY_TOKEN))
.metaFont(jsonObject.optString(KEY_META_FONT))
.dateAdded(new Date(jsonObject.optLong(KEY_DATE_ADDED, 0)));
String componentName = jsonObject.optString(KEY_COMPONENT_NAME);
if (!TextUtils.isEmpty(componentName)) {
builder.componentName(ComponentName.unflattenFromString(componentName));
}
String imageUri = jsonObject.optString(KEY_IMAGE_URI);
if (!TextUtils.isEmpty(imageUri)) {
builder.imageUri(Uri.parse(imageUri));
}
try {
String viewIntent = jsonObject.optString(KEY_VIEW_INTENT);
String detailsUri = jsonObject.optString(KEY_DETAILS_URI);
if (!TextUtils.isEmpty(viewIntent)) {
builder.viewIntent(Intent.parseUri(viewIntent, Intent.URI_INTENT_SCHEME));
} else if (!TextUtils.isEmpty(detailsUri)) {
builder.viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(detailsUri)));
}
} catch (URISyntaxException ignored) {
}
return builder.build();
} | [
"@",
"NonNull",
"public",
"static",
"Artwork",
"fromJson",
"(",
"@",
"NonNull",
"JSONObject",
"jsonObject",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"WrongConstant\"",
")",
"// Assume the KEY_META_FONT is valid",
"Builder",
"builder",
"=",
"new",
"Builder",
"(",
")... | Deserializes an artwork object from a {@link JSONObject}.
@param jsonObject JSON representation generated by {@link #toJson} to deserialize.
@return the artwork from the given {@link JSONObject} | [
"Deserializes",
"an",
"artwork",
"object",
"from",
"a",
"{",
"@link",
"JSONObject",
"}",
"."
] | train | https://github.com/romannurik/muzei/blob/d00777a5fc59f34471be338c814ea85ddcbde304/muzei-api/src/main/java/com/google/android/apps/muzei/api/Artwork.java#L618-L651 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java | BitvUnit.assertAccessibility | public static void assertAccessibility(Reader reader, Testable testable) {
assertThat(reader, is(compliantTo(testable)));
} | java | public static void assertAccessibility(Reader reader, Testable testable) {
assertThat(reader, is(compliantTo(testable)));
} | [
"public",
"static",
"void",
"assertAccessibility",
"(",
"Reader",
"reader",
",",
"Testable",
"testable",
")",
"{",
"assertThat",
"(",
"reader",
",",
"is",
"(",
"compliantTo",
"(",
"testable",
")",
")",
")",
";",
"}"
] | JUnit Assertion to verify a {@link java.io.Reader} instance for accessibility.
@param reader {@link java.io.Reader} instance
@param testable rule(s) to apply | [
"JUnit",
"Assertion",
"to",
"verify",
"a",
"{",
"@link",
"java",
".",
"io",
".",
"Reader",
"}",
"instance",
"for",
"accessibility",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java#L68-L70 |
pedrovgs/Nox | nox/src/main/java/com/github/pedrovgs/nox/shape/Shape.java | Shape.setNoxItemYPosition | protected final void setNoxItemYPosition(int position, float y) {
noxItemsYPositions[position] = y;
minY = (int) Math.min(y, minY);
maxY = (int) Math.max(y, maxY);
} | java | protected final void setNoxItemYPosition(int position, float y) {
noxItemsYPositions[position] = y;
minY = (int) Math.min(y, minY);
maxY = (int) Math.max(y, maxY);
} | [
"protected",
"final",
"void",
"setNoxItemYPosition",
"(",
"int",
"position",
",",
"float",
"y",
")",
"{",
"noxItemsYPositions",
"[",
"position",
"]",
"=",
"y",
";",
"minY",
"=",
"(",
"int",
")",
"Math",
".",
"min",
"(",
"y",
",",
"minY",
")",
";",
"m... | Configures the Y position for a given NoxItem indicated with the item position. This method
uses two counters to calculate the Shape minimum and maximum Y position used to configure the
Shape scroll. | [
"Configures",
"the",
"Y",
"position",
"for",
"a",
"given",
"NoxItem",
"indicated",
"with",
"the",
"item",
"position",
".",
"This",
"method",
"uses",
"two",
"counters",
"to",
"calculate",
"the",
"Shape",
"minimum",
"and",
"maximum",
"Y",
"position",
"used",
"... | train | https://github.com/pedrovgs/Nox/blob/b4dfe37895e1b7bf2084d60139931dd4fb12f3f4/nox/src/main/java/com/github/pedrovgs/nox/shape/Shape.java#L191-L195 |
tzaeschke/zoodb | src/org/zoodb/internal/server/StorageWriter.java | StorageWriter.allocateAndSeekAP | @Override
public int allocateAndSeekAP(PAGE_TYPE type, int prevPage, long header) {
//isAutoPaging = true;
currentDataType = type;
classOid = header;
int pageId = allocateAndSeekPage(prevPage);
//auto-paging is true
return pageId;
} | java | @Override
public int allocateAndSeekAP(PAGE_TYPE type, int prevPage, long header) {
//isAutoPaging = true;
currentDataType = type;
classOid = header;
int pageId = allocateAndSeekPage(prevPage);
//auto-paging is true
return pageId;
} | [
"@",
"Override",
"public",
"int",
"allocateAndSeekAP",
"(",
"PAGE_TYPE",
"type",
",",
"int",
"prevPage",
",",
"long",
"header",
")",
"{",
"//isAutoPaging = true;",
"currentDataType",
"=",
"type",
";",
"classOid",
"=",
"header",
";",
"int",
"pageId",
"=",
"allo... | Assumes autoPaging=true;
@return the page ID of the allocated page | [
"Assumes",
"autoPaging",
"=",
"true",
";"
] | train | https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/server/StorageWriter.java#L102-L111 |
pressgang-ccms/PressGangCCMSContentSpec | src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java | EntityUtilities.getCSNodeTopicEntity | public static TopicWrapper getCSNodeTopicEntity(final CSNodeWrapper node, final TopicProvider topicProvider) {
if (!isNodeATopic(node)) return null;
return topicProvider.getTopic(node.getEntityId(), node.getEntityRevision());
} | java | public static TopicWrapper getCSNodeTopicEntity(final CSNodeWrapper node, final TopicProvider topicProvider) {
if (!isNodeATopic(node)) return null;
return topicProvider.getTopic(node.getEntityId(), node.getEntityRevision());
} | [
"public",
"static",
"TopicWrapper",
"getCSNodeTopicEntity",
"(",
"final",
"CSNodeWrapper",
"node",
",",
"final",
"TopicProvider",
"topicProvider",
")",
"{",
"if",
"(",
"!",
"isNodeATopic",
"(",
"node",
")",
")",
"return",
"null",
";",
"return",
"topicProvider",
... | Gets the CSNode Topic entity that is represented by the node.
@param node The node that represents a topic entry.
@param topicProvider The topic provider to lookup the topic entity from.
@return The topic entity represented by the node, or null if there isn't one that matches. | [
"Gets",
"the",
"CSNode",
"Topic",
"entity",
"that",
"is",
"represented",
"by",
"the",
"node",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java#L371-L375 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/InstanceFailoverGroupsInner.java | InstanceFailoverGroupsInner.beginDelete | public void beginDelete(String resourceGroupName, String locationName, String failoverGroupName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String locationName, String failoverGroupName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"locationName",
",",
"String",
"failoverGroupName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"locationName",
",",
"failoverGroupName",
")",
".",
"t... | Deletes a failover group.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param locationName The name of the region where the resource is located.
@param failoverGroupName The name of the failover group.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"a",
"failover",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/InstanceFailoverGroupsInner.java#L476-L478 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.fax_customDomains_POST | public OvhMailDomain2Service fax_customDomains_POST(String domain) throws IOException {
String qPath = "/me/fax/customDomains";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "domain", domain);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMailDomain2Service.class);
} | java | public OvhMailDomain2Service fax_customDomains_POST(String domain) throws IOException {
String qPath = "/me/fax/customDomains";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "domain", domain);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMailDomain2Service.class);
} | [
"public",
"OvhMailDomain2Service",
"fax_customDomains_POST",
"(",
"String",
"domain",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/fax/customDomains\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
")",
";",
"HashMap",
"<",
"String",
... | Create a custom domain for your fax services
REST: POST /me/fax/customDomains
@param domain [required] The custom domain of your fax services | [
"Create",
"a",
"custom",
"domain",
"for",
"your",
"fax",
"services"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L1651-L1658 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/ArrayUtils.java | ArrayUtils.subArray | public static <T> T subArray(final T array, final int start, final int end) {
if (isEmpty(array) || start < 0 || start > end || end >= Array.getLength(array)) {
return array;
}
int newArraySize = end - start + 1;
@SuppressWarnings("unchecked")
T newArray = (T) buildArray(ClassUtils.getPrimitiveClass(ClassUtils.getComponentClass(array)),
newArraySize, null);
System.arraycopy(array, start, newArray, 0, newArraySize);
return newArray;
} | java | public static <T> T subArray(final T array, final int start, final int end) {
if (isEmpty(array) || start < 0 || start > end || end >= Array.getLength(array)) {
return array;
}
int newArraySize = end - start + 1;
@SuppressWarnings("unchecked")
T newArray = (T) buildArray(ClassUtils.getPrimitiveClass(ClassUtils.getComponentClass(array)),
newArraySize, null);
System.arraycopy(array, start, newArray, 0, newArraySize);
return newArray;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"subArray",
"(",
"final",
"T",
"array",
",",
"final",
"int",
"start",
",",
"final",
"int",
"end",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"array",
")",
"||",
"start",
"<",
"0",
"||",
"start",
">",
"end",
"||",... | 裁剪数组。
@param array 源数组。
@param start 裁剪的起始位置的索引。
@param end 裁剪的结束位置的索引。
@return
一个新的数组,包含从指定索引开始到指定索引结束的所有元素。如果数组为空或起始索引小于0,或起始索引大于结束索引,或结束大于数组本身索引长度
,则返回数组本身。 | [
"裁剪数组。"
] | train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/ArrayUtils.java#L274-L285 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/workspace/VoiceApi.java | VoiceApi.reconnectCall | public void reconnectCall(
String connId,
String heldConnId,
KeyValueCollection reasons,
KeyValueCollection extensions
) throws WorkspaceApiException {
try {
VoicecallsidreconnectData reconnectData = new VoicecallsidreconnectData();
reconnectData.setHeldConnId(heldConnId);
reconnectData.setReasons(Util.toKVList(reasons));
reconnectData.setExtensions(Util.toKVList(extensions));
ReconnectData data = new ReconnectData();
data.data(reconnectData);
ApiSuccessResponse response = this.voiceApi.reconnect(connId, data);
throwIfNotOk("reconnectCall", response);
} catch (ApiException e) {
throw new WorkspaceApiException("reconnectCall failed.", e);
}
} | java | public void reconnectCall(
String connId,
String heldConnId,
KeyValueCollection reasons,
KeyValueCollection extensions
) throws WorkspaceApiException {
try {
VoicecallsidreconnectData reconnectData = new VoicecallsidreconnectData();
reconnectData.setHeldConnId(heldConnId);
reconnectData.setReasons(Util.toKVList(reasons));
reconnectData.setExtensions(Util.toKVList(extensions));
ReconnectData data = new ReconnectData();
data.data(reconnectData);
ApiSuccessResponse response = this.voiceApi.reconnect(connId, data);
throwIfNotOk("reconnectCall", response);
} catch (ApiException e) {
throw new WorkspaceApiException("reconnectCall failed.", e);
}
} | [
"public",
"void",
"reconnectCall",
"(",
"String",
"connId",
",",
"String",
"heldConnId",
",",
"KeyValueCollection",
"reasons",
",",
"KeyValueCollection",
"extensions",
")",
"throws",
"WorkspaceApiException",
"{",
"try",
"{",
"VoicecallsidreconnectData",
"reconnectData",
... | Reconnect the specified call. This releases the established call and retrieves the held call
in one step. This is a quick way to to do `releaseCall()` and `retrieveCall()`.
@param connId The connection ID of the established call (will be released).
@param heldConnId The ID of the held call (will be retrieved).
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons). (optional)
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional) | [
"Reconnect",
"the",
"specified",
"call",
".",
"This",
"releases",
"the",
"established",
"call",
"and",
"retrieves",
"the",
"held",
"call",
"in",
"one",
"step",
".",
"This",
"is",
"a",
"quick",
"way",
"to",
"to",
"do",
"releaseCall",
"()",
"and",
"retrieveC... | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L1292-L1312 |
aeshell/aesh-readline | readline/src/main/java/org/aesh/readline/util/Parser.java | Parser.canDisplayColumns | private static boolean canDisplayColumns(List<TerminalString> displayList, int numRows, int terminalWidth) {
int numColumns = displayList.size() / numRows;
if (displayList.size() % numRows > 0) {
numColumns++;
}
int[] columnSizes = calculateColumnSizes(displayList, numColumns, numRows, terminalWidth);
int totalSize = 0;
for (int columnSize : columnSizes) {
totalSize += columnSize;
}
return totalSize <= terminalWidth;
} | java | private static boolean canDisplayColumns(List<TerminalString> displayList, int numRows, int terminalWidth) {
int numColumns = displayList.size() / numRows;
if (displayList.size() % numRows > 0) {
numColumns++;
}
int[] columnSizes = calculateColumnSizes(displayList, numColumns, numRows, terminalWidth);
int totalSize = 0;
for (int columnSize : columnSizes) {
totalSize += columnSize;
}
return totalSize <= terminalWidth;
} | [
"private",
"static",
"boolean",
"canDisplayColumns",
"(",
"List",
"<",
"TerminalString",
">",
"displayList",
",",
"int",
"numRows",
",",
"int",
"terminalWidth",
")",
"{",
"int",
"numColumns",
"=",
"displayList",
".",
"size",
"(",
")",
"/",
"numRows",
";",
"i... | Decides if it's possible to format provided Strings into calculated number of columns while the output will not exceed
terminal width
@param displayList
@param numRows
@param terminalWidth
@return true if it's possible to format strings to columns and false otherwise. | [
"Decides",
"if",
"it",
"s",
"possible",
"to",
"format",
"provided",
"Strings",
"into",
"calculated",
"number",
"of",
"columns",
"while",
"the",
"output",
"will",
"not",
"exceed",
"terminal",
"width"
] | train | https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L253-L267 |
gwtplus/google-gin | src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java | SourceWriteUtil.writeMethod | public void writeMethod(SourceWriter writer, String signature, String body) {
writer.println(signature + " {");
writer.indent();
writer.println(body);
writer.outdent();
writer.println("}");
writer.println();
} | java | public void writeMethod(SourceWriter writer, String signature, String body) {
writer.println(signature + " {");
writer.indent();
writer.println(body);
writer.outdent();
writer.println("}");
writer.println();
} | [
"public",
"void",
"writeMethod",
"(",
"SourceWriter",
"writer",
",",
"String",
"signature",
",",
"String",
"body",
")",
"{",
"writer",
".",
"println",
"(",
"signature",
"+",
"\" {\"",
")",
";",
"writer",
".",
"indent",
"(",
")",
";",
"writer",
".",
"prin... | Writes a method with the given signature and body to the source writer.
@param writer writer that the method is written to
@param signature method's signature
@param body method's body | [
"Writes",
"a",
"method",
"with",
"the",
"given",
"signature",
"and",
"body",
"to",
"the",
"source",
"writer",
"."
] | train | https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L260-L267 |
hal/elemento | core/src/main/java/org/jboss/gwt/elemento/core/Elements.java | Elements.onAttach | public static void onAttach(HTMLElement element, ObserverCallback callback) {
if (element != null) {
BodyObserver.addAttachObserver(element, callback);
}
} | java | public static void onAttach(HTMLElement element, ObserverCallback callback) {
if (element != null) {
BodyObserver.addAttachObserver(element, callback);
}
} | [
"public",
"static",
"void",
"onAttach",
"(",
"HTMLElement",
"element",
",",
"ObserverCallback",
"callback",
")",
"{",
"if",
"(",
"element",
"!=",
"null",
")",
"{",
"BodyObserver",
".",
"addAttachObserver",
"(",
"element",
",",
"callback",
")",
";",
"}",
"}"
... | Registers a callback when an element is appended to the document body. Note that the callback will be called
only once, if the element is appended more than once a new callback should be registered.
@param element the HTML element which is going to be added to the body
@param callback {@link ObserverCallback} | [
"Registers",
"a",
"callback",
"when",
"an",
"element",
"is",
"appended",
"to",
"the",
"document",
"body",
".",
"Note",
"that",
"the",
"callback",
"will",
"be",
"called",
"only",
"once",
"if",
"the",
"element",
"is",
"appended",
"more",
"than",
"once",
"a",... | train | https://github.com/hal/elemento/blob/26da2d5a1fe2ec55b779737dbaeda25a942eee61/core/src/main/java/org/jboss/gwt/elemento/core/Elements.java#L742-L746 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/InternalOutputStreamManager.java | InternalOutputStreamManager.getStreamSet | public StreamSet getStreamSet(SIBUuid12 streamID, boolean create)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getStreamSet", new Object[] { streamID, Boolean.valueOf(create) });
StreamSet streamSet = null;
synchronized (streamSets)
{
if (shellStreamSetOnly)
{
// We have yet to fully initialise the StreamSet managed by this object. Start by
// retrieving the shell StreamSet object
streamSet = streamSets.get(null);
// remove the shell from the Collection
streamSets.remove(null);
shellStreamSetOnly = false;
// Set the streamID into the StreamSet
if (streamSet != null)
{
// Set the StreamId into the shell StreamSet
streamSet.setStreamID(streamID);
// Store the StreamSet in the Collection keyed on StreamId.
streamSets.put(streamID, streamSet);
}
}
else
{
streamSet = streamSets.get(streamID);
}
if ((streamSet == null) && create)
{
streamSet = new StreamSet(streamID,
targetMEUuid,
0,
isLink ? StreamSet.Type.LINK_INTERNAL_OUTPUT : StreamSet.Type.INTERNAL_OUTPUT);
streamSets.put(streamID, streamSet);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getStreamSet", streamSet);
return streamSet;
} | java | public StreamSet getStreamSet(SIBUuid12 streamID, boolean create)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getStreamSet", new Object[] { streamID, Boolean.valueOf(create) });
StreamSet streamSet = null;
synchronized (streamSets)
{
if (shellStreamSetOnly)
{
// We have yet to fully initialise the StreamSet managed by this object. Start by
// retrieving the shell StreamSet object
streamSet = streamSets.get(null);
// remove the shell from the Collection
streamSets.remove(null);
shellStreamSetOnly = false;
// Set the streamID into the StreamSet
if (streamSet != null)
{
// Set the StreamId into the shell StreamSet
streamSet.setStreamID(streamID);
// Store the StreamSet in the Collection keyed on StreamId.
streamSets.put(streamID, streamSet);
}
}
else
{
streamSet = streamSets.get(streamID);
}
if ((streamSet == null) && create)
{
streamSet = new StreamSet(streamID,
targetMEUuid,
0,
isLink ? StreamSet.Type.LINK_INTERNAL_OUTPUT : StreamSet.Type.INTERNAL_OUTPUT);
streamSets.put(streamID, streamSet);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getStreamSet", streamSet);
return streamSet;
} | [
"public",
"StreamSet",
"getStreamSet",
"(",
"SIBUuid12",
"streamID",
",",
"boolean",
"create",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
... | Get a StreamSet for a given streamID. Optionally create the StreamSet
if it doesn't already exit.
@param streamID The streamID to map to a StreamSet.
@param create If TRUE then create the StreamSet if it doesn't already exit.
@return An instance of StreamSet | [
"Get",
"a",
"StreamSet",
"for",
"a",
"given",
"streamID",
".",
"Optionally",
"create",
"the",
"StreamSet",
"if",
"it",
"doesn",
"t",
"already",
"exit",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/InternalOutputStreamManager.java#L140-L183 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java | TransformerRegistry.getServerRegistration | public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);
return new TransformersSubRegistrationImpl(range, domain, address);
} | java | public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);
return new TransformersSubRegistrationImpl(range, domain, address);
} | [
"public",
"TransformersSubRegistration",
"getServerRegistration",
"(",
"final",
"ModelVersionRange",
"range",
")",
"{",
"final",
"PathAddress",
"address",
"=",
"PathAddress",
".",
"EMPTY_ADDRESS",
".",
"append",
"(",
"HOST",
",",
"SERVER",
")",
";",
"return",
"new",... | Get the sub registry for the servers.
@param range the version range
@return the sub registry | [
"Get",
"the",
"sub",
"registry",
"for",
"the",
"servers",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java#L185-L188 |
Alluxio/alluxio | integration/fuse/src/main/java/alluxio/fuse/AlluxioFuse.java | AlluxioFuse.main | public static void main(String[] args) {
AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults());
final AlluxioFuseOptions opts = parseOptions(args, conf);
if (opts == null) {
System.exit(1);
}
final FileSystem tfs = FileSystem.Factory.create(conf);
final AlluxioFuseFileSystem fs = new AlluxioFuseFileSystem(tfs, opts, conf);
final List<String> fuseOpts = opts.getFuseOpts();
// Force direct_io in FUSE: writes and reads bypass the kernel page
// cache and go directly to alluxio. This avoids extra memory copies
// in the write path.
fuseOpts.add("-odirect_io");
try {
fs.mount(Paths.get(opts.getMountPoint()), true, opts.isDebug(),
fuseOpts.toArray(new String[0]));
} finally {
fs.umount();
}
} | java | public static void main(String[] args) {
AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults());
final AlluxioFuseOptions opts = parseOptions(args, conf);
if (opts == null) {
System.exit(1);
}
final FileSystem tfs = FileSystem.Factory.create(conf);
final AlluxioFuseFileSystem fs = new AlluxioFuseFileSystem(tfs, opts, conf);
final List<String> fuseOpts = opts.getFuseOpts();
// Force direct_io in FUSE: writes and reads bypass the kernel page
// cache and go directly to alluxio. This avoids extra memory copies
// in the write path.
fuseOpts.add("-odirect_io");
try {
fs.mount(Paths.get(opts.getMountPoint()), true, opts.isDebug(),
fuseOpts.toArray(new String[0]));
} finally {
fs.umount();
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"AlluxioConfiguration",
"conf",
"=",
"new",
"InstancedConfiguration",
"(",
"ConfigurationUtils",
".",
"defaults",
"(",
")",
")",
";",
"final",
"AlluxioFuseOptions",
"opts",
"=",
"pa... | Running this class will mount the file system according to
the options passed to this function {@link #parseOptions(String[], AlluxioConfiguration)}.
The user-space fuse application will stay on the foreground and keep
the file system mounted. The user can unmount the file system by
gracefully killing (SIGINT) the process.
@param args arguments to run the command line | [
"Running",
"this",
"class",
"will",
"mount",
"the",
"file",
"system",
"according",
"to",
"the",
"options",
"passed",
"to",
"this",
"function",
"{",
"@link",
"#parseOptions",
"(",
"String",
"[]",
"AlluxioConfiguration",
")",
"}",
".",
"The",
"user",
"-",
"spa... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/integration/fuse/src/main/java/alluxio/fuse/AlluxioFuse.java#L55-L76 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/MethodDesc.java | MethodDesc.forArguments | public static MethodDesc forArguments(TypeDesc ret, TypeDesc[] params, String[] paramNames) {
if (ret == null) {
ret = TypeDesc.VOID;
}
if (params == null || params.length == 0) {
params = EMPTY_PARAMS;
}
if (paramNames == null || paramNames.length == 0) {
paramNames = EMPTY_PARAM_NAMES;
}
return intern(new MethodDesc(ret, params, paramNames));
} | java | public static MethodDesc forArguments(TypeDesc ret, TypeDesc[] params, String[] paramNames) {
if (ret == null) {
ret = TypeDesc.VOID;
}
if (params == null || params.length == 0) {
params = EMPTY_PARAMS;
}
if (paramNames == null || paramNames.length == 0) {
paramNames = EMPTY_PARAM_NAMES;
}
return intern(new MethodDesc(ret, params, paramNames));
} | [
"public",
"static",
"MethodDesc",
"forArguments",
"(",
"TypeDesc",
"ret",
",",
"TypeDesc",
"[",
"]",
"params",
",",
"String",
"[",
"]",
"paramNames",
")",
"{",
"if",
"(",
"ret",
"==",
"null",
")",
"{",
"ret",
"=",
"TypeDesc",
".",
"VOID",
";",
"}",
"... | Acquire a MethodDesc from a set of arguments.
@param ret return type of method; null implies void
@param params parameters to method; null implies none
@param paramNames parameter names to method; null implies none | [
"Acquire",
"a",
"MethodDesc",
"from",
"a",
"set",
"of",
"arguments",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/MethodDesc.java#L70-L81 |
ops4j/org.ops4j.base | ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java | ZipExploder.processZips | @Deprecated
public void processZips(String[] zipNames, String destDir) throws IOException {
//Delegation to preferred method
processZips(FileUtils.pathNamesToFiles(zipNames), new File(destDir));
} | java | @Deprecated
public void processZips(String[] zipNames, String destDir) throws IOException {
//Delegation to preferred method
processZips(FileUtils.pathNamesToFiles(zipNames), new File(destDir));
} | [
"@",
"Deprecated",
"public",
"void",
"processZips",
"(",
"String",
"[",
"]",
"zipNames",
",",
"String",
"destDir",
")",
"throws",
"IOException",
"{",
"//Delegation to preferred method",
"processZips",
"(",
"FileUtils",
".",
"pathNamesToFiles",
"(",
"zipNames",
")",
... | Explode source ZIP files into a target directory
@param zipNames
names of source files
@param destDir
target directory name (should already exist)
@exception IOException
error creating a target file
@deprecated use {@link #processZips(File[], File)} for a type save
variant | [
"Explode",
"source",
"ZIP",
"files",
"into",
"a",
"target",
"directory"
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java#L186-L190 |
jbundle/jbundle | main/db/src/main/java/org/jbundle/main/db/PropertiesRecord.java | PropertiesRecord.addPropertiesFieldBehavior | public void addPropertiesFieldBehavior(BaseField fldDisplay, String strProperty)
{
BaseField fldProperties = this.getField(PropertiesRecord.PROPERTIES);
FieldListener listener = new CopyConvertersHandler(new PropertiesConverter(fldProperties, strProperty));
listener.setRespondsToMode(DBConstants.INIT_MOVE, false);
listener.setRespondsToMode(DBConstants.READ_MOVE, false);
fldDisplay.addListener(listener);
listener = new CopyConvertersHandler(fldDisplay, new PropertiesConverter(fldProperties, strProperty));
fldProperties.addListener(listener);
} | java | public void addPropertiesFieldBehavior(BaseField fldDisplay, String strProperty)
{
BaseField fldProperties = this.getField(PropertiesRecord.PROPERTIES);
FieldListener listener = new CopyConvertersHandler(new PropertiesConverter(fldProperties, strProperty));
listener.setRespondsToMode(DBConstants.INIT_MOVE, false);
listener.setRespondsToMode(DBConstants.READ_MOVE, false);
fldDisplay.addListener(listener);
listener = new CopyConvertersHandler(fldDisplay, new PropertiesConverter(fldProperties, strProperty));
fldProperties.addListener(listener);
} | [
"public",
"void",
"addPropertiesFieldBehavior",
"(",
"BaseField",
"fldDisplay",
",",
"String",
"strProperty",
")",
"{",
"BaseField",
"fldProperties",
"=",
"this",
".",
"getField",
"(",
"PropertiesRecord",
".",
"PROPERTIES",
")",
";",
"FieldListener",
"listener",
"="... | Add the behaviors to sync this property to this virtual field. | [
"Add",
"the",
"behaviors",
"to",
"sync",
"this",
"property",
"to",
"this",
"virtual",
"field",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/main/db/src/main/java/org/jbundle/main/db/PropertiesRecord.java#L88-L97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.