repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/jsf/ComponentSupport.java | ComponentSupport.getLocale | public static Locale getLocale(FaceletContext ctx, TagAttribute attr) throws TagAttributeException
{
Object obj = attr.getObject(ctx);
if (obj instanceof Locale)
{
return (Locale) obj;
}
if (obj instanceof String)
{
String s = (String) obj;
if (s.length() == 2)
{
return new Locale(s);
}
if (s.length() == 5)
{
return new Locale(s.substring(0, 2), s.substring(3, 5).toUpperCase());
}
if (s.length() >= 7)
{
return new Locale(s.substring(0, 2), s.substring(3, 5).toUpperCase(), s.substring(6, s.length()));
}
throw new TagAttributeException(attr, "Invalid Locale Specified: " + s);
}
else
{
throw new TagAttributeException(attr, "Attribute did not evaluate to a String or Locale: " + obj);
}
} | java | public static Locale getLocale(FaceletContext ctx, TagAttribute attr) throws TagAttributeException
{
Object obj = attr.getObject(ctx);
if (obj instanceof Locale)
{
return (Locale) obj;
}
if (obj instanceof String)
{
String s = (String) obj;
if (s.length() == 2)
{
return new Locale(s);
}
if (s.length() == 5)
{
return new Locale(s.substring(0, 2), s.substring(3, 5).toUpperCase());
}
if (s.length() >= 7)
{
return new Locale(s.substring(0, 2), s.substring(3, 5).toUpperCase(), s.substring(6, s.length()));
}
throw new TagAttributeException(attr, "Invalid Locale Specified: " + s);
}
else
{
throw new TagAttributeException(attr, "Attribute did not evaluate to a String or Locale: " + obj);
}
} | [
"public",
"static",
"Locale",
"getLocale",
"(",
"FaceletContext",
"ctx",
",",
"TagAttribute",
"attr",
")",
"throws",
"TagAttributeException",
"{",
"Object",
"obj",
"=",
"attr",
".",
"getObject",
"(",
"ctx",
")",
";",
"if",
"(",
"obj",
"instanceof",
"Locale",
... | According to JSF 1.2 tag specs, this helper method will use the TagAttribute passed in determining the Locale
intended.
@param ctx
FaceletContext to evaluate from
@param attr
TagAttribute representing a Locale
@return Locale found
@throws TagAttributeException
if the Locale cannot be determined | [
"According",
"to",
"JSF",
"1",
".",
"2",
"tag",
"specs",
"this",
"helper",
"method",
"will",
"use",
"the",
"TagAttribute",
"passed",
"in",
"determining",
"the",
"Locale",
"intended",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/jsf/ComponentSupport.java#L405-L436 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/DatabaseHelper.java | DatabaseHelper.psSetString | public void psSetString(PreparedStatement pstmtImpl, int i, String x) throws SQLException {
pstmtImpl.setString(i, x);
} | java | public void psSetString(PreparedStatement pstmtImpl, int i, String x) throws SQLException {
pstmtImpl.setString(i, x);
} | [
"public",
"void",
"psSetString",
"(",
"PreparedStatement",
"pstmtImpl",
",",
"int",
"i",
",",
"String",
"x",
")",
"throws",
"SQLException",
"{",
"pstmtImpl",
".",
"setString",
"(",
"i",
",",
"x",
")",
";",
"}"
] | Allow for special handling of Oracle prepared statement setString
This method just does the normal setString call, Oracle helper overrides it | [
"Allow",
"for",
"special",
"handling",
"of",
"Oracle",
"prepared",
"statement",
"setString",
"This",
"method",
"just",
"does",
"the",
"normal",
"setString",
"call",
"Oracle",
"helper",
"overrides",
"it"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/DatabaseHelper.java#L623-L625 |
canoo/open-dolphin | subprojects/shared/src/main/groovy/org/opendolphin/core/ModelStoreConfig.java | ModelStoreConfig.ensurePowerOfTwo | private void ensurePowerOfTwo(String parameter, int number) {
if (Integer.bitCount(number) > 1) {
if (log.isLoggable(Level.WARNING)) {
log.warning("Parameter '" + parameter + "' should be power of two but was " + number);
}
}
} | java | private void ensurePowerOfTwo(String parameter, int number) {
if (Integer.bitCount(number) > 1) {
if (log.isLoggable(Level.WARNING)) {
log.warning("Parameter '" + parameter + "' should be power of two but was " + number);
}
}
} | [
"private",
"void",
"ensurePowerOfTwo",
"(",
"String",
"parameter",
",",
"int",
"number",
")",
"{",
"if",
"(",
"Integer",
".",
"bitCount",
"(",
"number",
")",
">",
"1",
")",
"{",
"if",
"(",
"log",
".",
"isLoggable",
"(",
"Level",
".",
"WARNING",
")",
... | all the capacities will be used to initialize HashMaps so they should be powers of two | [
"all",
"the",
"capacities",
"will",
"be",
"used",
"to",
"initialize",
"HashMaps",
"so",
"they",
"should",
"be",
"powers",
"of",
"two"
] | train | https://github.com/canoo/open-dolphin/blob/50166defc3ef2de473d7a7246c32dc04304d80ef/subprojects/shared/src/main/groovy/org/opendolphin/core/ModelStoreConfig.java#L82-L88 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/dsl/Disruptor.java | Disruptor.publishEvent | public <A, B> void publishEvent(final EventTranslatorTwoArg<T, A, B> eventTranslator, final A arg0, final B arg1)
{
ringBuffer.publishEvent(eventTranslator, arg0, arg1);
} | java | public <A, B> void publishEvent(final EventTranslatorTwoArg<T, A, B> eventTranslator, final A arg0, final B arg1)
{
ringBuffer.publishEvent(eventTranslator, arg0, arg1);
} | [
"public",
"<",
"A",
",",
"B",
">",
"void",
"publishEvent",
"(",
"final",
"EventTranslatorTwoArg",
"<",
"T",
",",
"A",
",",
"B",
">",
"eventTranslator",
",",
"final",
"A",
"arg0",
",",
"final",
"B",
"arg1",
")",
"{",
"ringBuffer",
".",
"publishEvent",
"... | Publish an event to the ring buffer.
@param <A> Class of the user supplied argument.
@param <B> Class of the user supplied argument.
@param eventTranslator the translator that will load data into the event.
@param arg0 The first argument to load into the event
@param arg1 The second argument to load into the event | [
"Publish",
"an",
"event",
"to",
"the",
"ring",
"buffer",
"."
] | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/dsl/Disruptor.java#L367-L370 |
spring-projects/spring-loaded | springloaded/src/main/java/org/springsource/loaded/Utils.java | Utils.insertPopsForAllParameters | public static int insertPopsForAllParameters(MethodVisitor mv, String desc) {
String descSequence = Utils.getParamSequence(desc);
if (descSequence == null) {
return 0; // nothing to do, there are no parameters
}
int count = descSequence.length();
for (int dpos = count - 1; dpos >= 0; dpos--) {
char ch = descSequence.charAt(dpos);
switch (ch) {
case 'O':
case 'I':
case 'Z':
case 'F':
case 'S':
case 'C':
case 'B':
mv.visitInsn(POP);
break;
case 'J': // long - double slot
case 'D': // double - double slot
mv.visitInsn(POP2);
break;
default:
throw new IllegalStateException("Unexpected character: " + ch + " from " + desc + ":" + dpos);
}
}
return count;
} | java | public static int insertPopsForAllParameters(MethodVisitor mv, String desc) {
String descSequence = Utils.getParamSequence(desc);
if (descSequence == null) {
return 0; // nothing to do, there are no parameters
}
int count = descSequence.length();
for (int dpos = count - 1; dpos >= 0; dpos--) {
char ch = descSequence.charAt(dpos);
switch (ch) {
case 'O':
case 'I':
case 'Z':
case 'F':
case 'S':
case 'C':
case 'B':
mv.visitInsn(POP);
break;
case 'J': // long - double slot
case 'D': // double - double slot
mv.visitInsn(POP2);
break;
default:
throw new IllegalStateException("Unexpected character: " + ch + " from " + desc + ":" + dpos);
}
}
return count;
} | [
"public",
"static",
"int",
"insertPopsForAllParameters",
"(",
"MethodVisitor",
"mv",
",",
"String",
"desc",
")",
"{",
"String",
"descSequence",
"=",
"Utils",
".",
"getParamSequence",
"(",
"desc",
")",
";",
"if",
"(",
"descSequence",
"==",
"null",
")",
"{",
"... | Looks at the supplied descriptor and inserts enough pops to remove all parameters. Should be used when about to
avoid a method call.
@param mv the method visitor to append instructions to
@param desc the method descriptor for the parameter sequence (e.g. (Ljava/lang/String;IZZ)V)
@return number of parameters popped | [
"Looks",
"at",
"the",
"supplied",
"descriptor",
"and",
"inserts",
"enough",
"pops",
"to",
"remove",
"all",
"parameters",
".",
"Should",
"be",
"used",
"when",
"about",
"to",
"avoid",
"a",
"method",
"call",
"."
] | train | https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1760-L1787 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.nestedBeanNull | public static void nestedBeanNull(String currentField, String destinationClass, String destinationField, String sourceClass, String sourceField, boolean safeNavigationOperator){
throw new NestedBeanNullException(MSG.INSTANCE.message(nestedBeanNullException,currentField,destinationClass,destinationField,sourceClass,sourceField), safeNavigationOperator);
} | java | public static void nestedBeanNull(String currentField, String destinationClass, String destinationField, String sourceClass, String sourceField, boolean safeNavigationOperator){
throw new NestedBeanNullException(MSG.INSTANCE.message(nestedBeanNullException,currentField,destinationClass,destinationField,sourceClass,sourceField), safeNavigationOperator);
} | [
"public",
"static",
"void",
"nestedBeanNull",
"(",
"String",
"currentField",
",",
"String",
"destinationClass",
",",
"String",
"destinationField",
",",
"String",
"sourceClass",
",",
"String",
"sourceField",
",",
"boolean",
"safeNavigationOperator",
")",
"{",
"throw",
... | Thrown when the source field is null in a mapping of nested type.
@param currentField current field
@param destinationClass destination class
@param destinationField destination field
@param sourceClass source class
@param sourceField source field | [
"Thrown",
"when",
"the",
"source",
"field",
"is",
"null",
"in",
"a",
"mapping",
"of",
"nested",
"type",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L126-L128 |
cloudendpoints/endpoints-management-java | endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigSupplier.java | ServiceConfigSupplier.get | @Override
public Service get() {
String serviceName = this.environment.getVariable(SERVICE_NAME_KEY);
if (Strings.isNullOrEmpty(serviceName)) {
String errorMessage =
String.format("Environment variable '%s' is not set", SERVICE_NAME_KEY);
throw new IllegalArgumentException(errorMessage);
}
String serviceVersion = this.environment.getVariable(SERVICE_VERSION_KEY);
return fetch(serviceName, serviceVersion);
} | java | @Override
public Service get() {
String serviceName = this.environment.getVariable(SERVICE_NAME_KEY);
if (Strings.isNullOrEmpty(serviceName)) {
String errorMessage =
String.format("Environment variable '%s' is not set", SERVICE_NAME_KEY);
throw new IllegalArgumentException(errorMessage);
}
String serviceVersion = this.environment.getVariable(SERVICE_VERSION_KEY);
return fetch(serviceName, serviceVersion);
} | [
"@",
"Override",
"public",
"Service",
"get",
"(",
")",
"{",
"String",
"serviceName",
"=",
"this",
".",
"environment",
".",
"getVariable",
"(",
"SERVICE_NAME_KEY",
")",
";",
"if",
"(",
"Strings",
".",
"isNullOrEmpty",
"(",
"serviceName",
")",
")",
"{",
"Str... | Fetches the service configuration using the service name and the service
version read from the environment variables.
@return a {@link Service} object generated by the JSON response from Google
Service Management. | [
"Fetches",
"the",
"service",
"configuration",
"using",
"the",
"service",
"name",
"and",
"the",
"service",
"version",
"read",
"from",
"the",
"environment",
"variables",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigSupplier.java#L121-L132 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.readString | public static String readString(File file, Charset charset) throws IORuntimeException {
return FileReader.create(file, charset).readString();
} | java | public static String readString(File file, Charset charset) throws IORuntimeException {
return FileReader.create(file, charset).readString();
} | [
"public",
"static",
"String",
"readString",
"(",
"File",
"file",
",",
"Charset",
"charset",
")",
"throws",
"IORuntimeException",
"{",
"return",
"FileReader",
".",
"create",
"(",
"file",
",",
"charset",
")",
".",
"readString",
"(",
")",
";",
"}"
] | 读取文件内容
@param file 文件
@param charset 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"读取文件内容"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2102-L2104 |
jayantk/jklol | src/com/jayantkrish/jklol/ccg/data/CcgExampleFormat.java | CcgExampleFormat.parseFrom | @Override
public CcgExample parseFrom(String exampleString) {
String[] parts = exampleString.split("###");
List<String> words = Arrays.asList(parts[0].split("\\s+"));
Set<DependencyStructure> dependencies = Sets.newHashSet();
String[] dependencyParts = new CsvParser(CsvParser.DEFAULT_SEPARATOR,
CsvParser.DEFAULT_QUOTE, CsvParser.NULL_ESCAPE).parseLine(parts[1]);
for (int i = 0; i < dependencyParts.length; i++) {
if (dependencyParts[i].trim().length() == 0) {
continue;
}
String[] dep = dependencyParts[i].split("\\s+");
Preconditions.checkState(dep.length >= 6, "Illegal dependency string: " + dependencyParts[i]);
dependencies.add(new DependencyStructure(dep[0], Integer.parseInt(dep[2]),
HeadedSyntacticCategory.parseFrom(dep[1]).getCanonicalForm(), dep[4],
Integer.parseInt(dep[5]), Integer.parseInt(dep[3])));
}
// Parse out a CCG syntactic tree, if one is provided.
CcgSyntaxTree tree = null;
List<String> posTags = null;
if (parts.length >= 3 && parts[2].length() > 0) {
tree = syntaxTreeReader.parseFrom(parts[2]);
posTags = tree.getAllSpannedPosTags();
} else {
posTags = Collections.nCopies(words.size(), ParametricCcgParser.DEFAULT_POS_TAG);
}
// Parse out a logical form, if one is provided.
Expression2 logicalForm = null;
if (parts.length >= 4 && parts[3].length() > 0) {
logicalForm = ExpressionParser.expression2().parse(parts[3]);
}
if (!ignoreSemantics) {
return new CcgExample(new AnnotatedSentence(words, posTags), dependencies, tree,
logicalForm);
} else {
return new CcgExample(new AnnotatedSentence(words, posTags), null, tree,
logicalForm);
}
} | java | @Override
public CcgExample parseFrom(String exampleString) {
String[] parts = exampleString.split("###");
List<String> words = Arrays.asList(parts[0].split("\\s+"));
Set<DependencyStructure> dependencies = Sets.newHashSet();
String[] dependencyParts = new CsvParser(CsvParser.DEFAULT_SEPARATOR,
CsvParser.DEFAULT_QUOTE, CsvParser.NULL_ESCAPE).parseLine(parts[1]);
for (int i = 0; i < dependencyParts.length; i++) {
if (dependencyParts[i].trim().length() == 0) {
continue;
}
String[] dep = dependencyParts[i].split("\\s+");
Preconditions.checkState(dep.length >= 6, "Illegal dependency string: " + dependencyParts[i]);
dependencies.add(new DependencyStructure(dep[0], Integer.parseInt(dep[2]),
HeadedSyntacticCategory.parseFrom(dep[1]).getCanonicalForm(), dep[4],
Integer.parseInt(dep[5]), Integer.parseInt(dep[3])));
}
// Parse out a CCG syntactic tree, if one is provided.
CcgSyntaxTree tree = null;
List<String> posTags = null;
if (parts.length >= 3 && parts[2].length() > 0) {
tree = syntaxTreeReader.parseFrom(parts[2]);
posTags = tree.getAllSpannedPosTags();
} else {
posTags = Collections.nCopies(words.size(), ParametricCcgParser.DEFAULT_POS_TAG);
}
// Parse out a logical form, if one is provided.
Expression2 logicalForm = null;
if (parts.length >= 4 && parts[3].length() > 0) {
logicalForm = ExpressionParser.expression2().parse(parts[3]);
}
if (!ignoreSemantics) {
return new CcgExample(new AnnotatedSentence(words, posTags), dependencies, tree,
logicalForm);
} else {
return new CcgExample(new AnnotatedSentence(words, posTags), null, tree,
logicalForm);
}
} | [
"@",
"Override",
"public",
"CcgExample",
"parseFrom",
"(",
"String",
"exampleString",
")",
"{",
"String",
"[",
"]",
"parts",
"=",
"exampleString",
".",
"split",
"(",
"\"###\"",
")",
";",
"List",
"<",
"String",
">",
"words",
"=",
"Arrays",
".",
"asList",
... | Expected format is (space-separated words)###(,-separated
dependency structures)###(@@@-separated lexicon entries
(optional)).
@param exampleString
@return | [
"Expected",
"format",
"is",
"(",
"space",
"-",
"separated",
"words",
")",
"###",
"(",
"-",
"separated",
"dependency",
"structures",
")",
"###",
"(",
"@@@",
"-",
"separated",
"lexicon",
"entries",
"(",
"optional",
"))",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/data/CcgExampleFormat.java#L40-L83 |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/ImageFormatList.java | ImageFormatList.sortLists | private void sortLists(){
//sort RGBformats
//if native RGB24 is supported, put it first
moveToFirstIfNative(RGBformats, V4L4JConstants.IMF_RGB24);
//sort BGRformats
//if native BGR24 is supported, put it first
moveToFirstIfNative(BGRformats, V4L4JConstants.IMF_BGR24);
//sort YUV420formats
//if native YUV420 is supported, put it first
moveToFirstIfNative(YUV420formats, V4L4JConstants.IMF_YUV420);
//sort YVU420formats
//if native YVU420 is supported, put it first
moveToFirstIfNative(YVU420formats, V4L4JConstants.IMF_YVU420);
//sort JPEGformats
//put native formats first and libvideo converted ones next
moveNativeFirst(JPEGformats);
//if native RGB32 is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_RGB32);
//if native RGB24 is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_RGB24);
//if native UYVY is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_UYVY);
//if native YUYV is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_YUYV);
//if native YUV420P is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_YUV420);
//if native MJPEG is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_MJPEG);
//if native JPEG is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_JPEG);
} | java | private void sortLists(){
//sort RGBformats
//if native RGB24 is supported, put it first
moveToFirstIfNative(RGBformats, V4L4JConstants.IMF_RGB24);
//sort BGRformats
//if native BGR24 is supported, put it first
moveToFirstIfNative(BGRformats, V4L4JConstants.IMF_BGR24);
//sort YUV420formats
//if native YUV420 is supported, put it first
moveToFirstIfNative(YUV420formats, V4L4JConstants.IMF_YUV420);
//sort YVU420formats
//if native YVU420 is supported, put it first
moveToFirstIfNative(YVU420formats, V4L4JConstants.IMF_YVU420);
//sort JPEGformats
//put native formats first and libvideo converted ones next
moveNativeFirst(JPEGformats);
//if native RGB32 is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_RGB32);
//if native RGB24 is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_RGB24);
//if native UYVY is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_UYVY);
//if native YUYV is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_YUYV);
//if native YUV420P is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_YUV420);
//if native MJPEG is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_MJPEG);
//if native JPEG is supported, put it first
moveToFirstIfNative(JPEGformats, V4L4JConstants.IMF_JPEG);
} | [
"private",
"void",
"sortLists",
"(",
")",
"{",
"//sort RGBformats",
"//if native RGB24 is supported, put it first",
"moveToFirstIfNative",
"(",
"RGBformats",
",",
"V4L4JConstants",
".",
"IMF_RGB24",
")",
";",
"//sort BGRformats",
"//if native BGR24 is supported, put it first",
... | This method sorts the {@link #JPEGformats}, {@link #RGBformats},
{@link #BGRformats}, {@link #YUV420formats} & {@link #YVU420formats}
lists, so that formats more suited to conversion are first. | [
"This",
"method",
"sorts",
"the",
"{"
] | train | https://github.com/sarxos/v4l4j/blob/4fc0eec2c3a1a4260593f6ac03b7a8013e3804c9/src/main/java/au/edu/jcu/v4l4j/ImageFormatList.java#L120-L154 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFieldSetRenderer.java | WFieldSetRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WFieldSet fieldSet = (WFieldSet) component;
XmlStringBuilder xml = renderContext.getWriter();
xml.appendTagOpen("ui:fieldset");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", fieldSet.isHidden(), "true");
switch (fieldSet.getFrameType()) {
case NO_BORDER:
xml.appendOptionalAttribute("frame", "noborder");
break;
case NO_TEXT:
xml.appendOptionalAttribute("frame", "notext");
break;
case NONE:
xml.appendOptionalAttribute("frame", "none");
break;
case NORMAL:
default:
break;
}
xml.appendOptionalAttribute("required", fieldSet.isMandatory(), "true");
xml.appendClose();
// Render margin
MarginRendererUtil.renderMargin(fieldSet, renderContext);
// Label
WDecoratedLabel label = fieldSet.getTitle();
label.paint(renderContext);
// Children
xml.appendTag("ui:content");
int size = fieldSet.getChildCount();
for (int i = 0; i < size; i++) {
WComponent child = fieldSet.getChildAt(i);
// Skip label, as it has already been painted
if (child != label) {
child.paint(renderContext);
}
}
xml.appendEndTag("ui:content");
DiagnosticRenderUtil.renderDiagnostics(fieldSet, renderContext);
xml.appendEndTag("ui:fieldset");
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WFieldSet fieldSet = (WFieldSet) component;
XmlStringBuilder xml = renderContext.getWriter();
xml.appendTagOpen("ui:fieldset");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", fieldSet.isHidden(), "true");
switch (fieldSet.getFrameType()) {
case NO_BORDER:
xml.appendOptionalAttribute("frame", "noborder");
break;
case NO_TEXT:
xml.appendOptionalAttribute("frame", "notext");
break;
case NONE:
xml.appendOptionalAttribute("frame", "none");
break;
case NORMAL:
default:
break;
}
xml.appendOptionalAttribute("required", fieldSet.isMandatory(), "true");
xml.appendClose();
// Render margin
MarginRendererUtil.renderMargin(fieldSet, renderContext);
// Label
WDecoratedLabel label = fieldSet.getTitle();
label.paint(renderContext);
// Children
xml.appendTag("ui:content");
int size = fieldSet.getChildCount();
for (int i = 0; i < size; i++) {
WComponent child = fieldSet.getChildAt(i);
// Skip label, as it has already been painted
if (child != label) {
child.paint(renderContext);
}
}
xml.appendEndTag("ui:content");
DiagnosticRenderUtil.renderDiagnostics(fieldSet, renderContext);
xml.appendEndTag("ui:fieldset");
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WFieldSet",
"fieldSet",
"=",
"(",
"WFieldSet",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"renderCo... | Paints the given WFieldSet.
@param component the WFieldSet to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WFieldSet",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFieldSetRenderer.java#L23-L78 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/AbstractList.java | AbstractList.checkRangeFromTo | protected static void checkRangeFromTo(int from, int to, int theSize) {
if (to==from-1) return;
if (from<0 || from>to || to>=theSize)
throw new IndexOutOfBoundsException("from: "+from+", to: "+to+", size="+theSize);
} | java | protected static void checkRangeFromTo(int from, int to, int theSize) {
if (to==from-1) return;
if (from<0 || from>to || to>=theSize)
throw new IndexOutOfBoundsException("from: "+from+", to: "+to+", size="+theSize);
} | [
"protected",
"static",
"void",
"checkRangeFromTo",
"(",
"int",
"from",
",",
"int",
"to",
",",
"int",
"theSize",
")",
"{",
"if",
"(",
"to",
"==",
"from",
"-",
"1",
")",
"return",
";",
"if",
"(",
"from",
"<",
"0",
"||",
"from",
">",
"to",
"||",
"to... | Checks if the given range is within the contained array's bounds.
@throws IndexOutOfBoundsException if <tt>to!=from-1 || from<0 || from>to || to>=size()</tt>. | [
"Checks",
"if",
"the",
"given",
"range",
"is",
"within",
"the",
"contained",
"array",
"s",
"bounds",
"."
] | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/AbstractList.java#L75-L79 |
sailthru/sailthru-java-client | src/main/com/sailthru/client/SailthruClient.java | SailthruClient.deleteAlert | public JsonResponse deleteAlert(String email, String alertId) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Alert.PARAM_EMAIL, email);
data.put(Alert.PARAM_ALERT_ID, alertId);
return apiDelete(ApiAction.alert, data);
} | java | public JsonResponse deleteAlert(String email, String alertId) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Alert.PARAM_EMAIL, email);
data.put(Alert.PARAM_ALERT_ID, alertId);
return apiDelete(ApiAction.alert, data);
} | [
"public",
"JsonResponse",
"deleteAlert",
"(",
"String",
"email",
",",
"String",
"alertId",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"data... | Delete existing user alert
@param email User.java Email
@param alertId Alert ID
@throws IOException | [
"Delete",
"existing",
"user",
"alert"
] | train | https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L353-L358 |
alkacon/opencms-core | src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyController.java | CmsPatternPanelMonthlyController.weeksChange | public void weeksChange(String week, Boolean value) {
final WeekOfMonth changedWeek = WeekOfMonth.valueOf(week);
boolean newValue = (null != value) && value.booleanValue();
boolean currentValue = m_model.getWeeksOfMonth().contains(changedWeek);
if (newValue != currentValue) {
if (newValue) {
setPatternScheme(true, false);
m_model.addWeekOfMonth(changedWeek);
onValueChange();
} else {
removeExceptionsOnChange(new Command() {
public void execute() {
m_model.removeWeekOfMonth(changedWeek);
onValueChange();
}
});
}
}
} | java | public void weeksChange(String week, Boolean value) {
final WeekOfMonth changedWeek = WeekOfMonth.valueOf(week);
boolean newValue = (null != value) && value.booleanValue();
boolean currentValue = m_model.getWeeksOfMonth().contains(changedWeek);
if (newValue != currentValue) {
if (newValue) {
setPatternScheme(true, false);
m_model.addWeekOfMonth(changedWeek);
onValueChange();
} else {
removeExceptionsOnChange(new Command() {
public void execute() {
m_model.removeWeekOfMonth(changedWeek);
onValueChange();
}
});
}
}
} | [
"public",
"void",
"weeksChange",
"(",
"String",
"week",
",",
"Boolean",
"value",
")",
"{",
"final",
"WeekOfMonth",
"changedWeek",
"=",
"WeekOfMonth",
".",
"valueOf",
"(",
"week",
")",
";",
"boolean",
"newValue",
"=",
"(",
"null",
"!=",
"value",
")",
"&&",
... | Handle a change in the weeks of month.
@param week the changed weeks checkbox's internal value.
@param value the new value of the changed checkbox. | [
"Handle",
"a",
"change",
"in",
"the",
"weeks",
"of",
"month",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyController.java#L115-L136 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java | JsonService.getShortValue | public static Short getShortValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isNumber() != null) {
double number = ((JSONNumber) value).doubleValue();
return new Short((short) number);
}
return null;
} | java | public static Short getShortValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isNumber() != null) {
double number = ((JSONNumber) value).doubleValue();
return new Short((short) number);
}
return null;
} | [
"public",
"static",
"Short",
"getShortValue",
"(",
"JSONObject",
"jsonObject",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"checkArguments",
"(",
"jsonObject",
",",
"key",
")",
";",
"JSONValue",
"value",
"=",
"jsonObject",
".",
"get",
"(",
"key"... | Get a short value from a {@link JSONObject}.
@param jsonObject The object to get the key value from.
@param key The name of the key to search the value for.
@return Returns the value for the key in the object .
@throws JSONException Thrown in case the key could not be found in the JSON object. | [
"Get",
"a",
"short",
"value",
"from",
"a",
"{",
"@link",
"JSONObject",
"}",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L313-L321 |
finnyb/javampd | src/main/java/org/bff/javampd/playlist/MPDPlaylist.java | MPDPlaylist.firePlaylistChangeEvent | protected synchronized void firePlaylistChangeEvent(PlaylistChangeEvent.Event event) {
PlaylistChangeEvent pce = new PlaylistChangeEvent(this, event);
for (PlaylistChangeListener pcl : listeners) {
pcl.playlistChanged(pce);
}
} | java | protected synchronized void firePlaylistChangeEvent(PlaylistChangeEvent.Event event) {
PlaylistChangeEvent pce = new PlaylistChangeEvent(this, event);
for (PlaylistChangeListener pcl : listeners) {
pcl.playlistChanged(pce);
}
} | [
"protected",
"synchronized",
"void",
"firePlaylistChangeEvent",
"(",
"PlaylistChangeEvent",
".",
"Event",
"event",
")",
"{",
"PlaylistChangeEvent",
"pce",
"=",
"new",
"PlaylistChangeEvent",
"(",
"this",
",",
"event",
")",
";",
"for",
"(",
"PlaylistChangeListener",
"... | Sends the appropriate {@link PlaylistChangeEvent} to all registered
{@link PlaylistChangeListener}.
@param event the {@link PlaylistChangeEvent.Event} to send | [
"Sends",
"the",
"appropriate",
"{",
"@link",
"PlaylistChangeEvent",
"}",
"to",
"all",
"registered",
"{",
"@link",
"PlaylistChangeListener",
"}",
"."
] | train | https://github.com/finnyb/javampd/blob/186736e85fc238b4208cc9ee23373f9249376b4c/src/main/java/org/bff/javampd/playlist/MPDPlaylist.java#L82-L88 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/Matrix.java | Matrix.transposeMultiply | public Matrix transposeMultiply(Matrix B, ExecutorService threadPool)
{
Matrix C = new DenseMatrix(this.cols(), B.cols());
transposeMultiply(B, C, threadPool);
return C;
} | java | public Matrix transposeMultiply(Matrix B, ExecutorService threadPool)
{
Matrix C = new DenseMatrix(this.cols(), B.cols());
transposeMultiply(B, C, threadPool);
return C;
} | [
"public",
"Matrix",
"transposeMultiply",
"(",
"Matrix",
"B",
",",
"ExecutorService",
"threadPool",
")",
"{",
"Matrix",
"C",
"=",
"new",
"DenseMatrix",
"(",
"this",
".",
"cols",
"(",
")",
",",
"B",
".",
"cols",
"(",
")",
")",
";",
"transposeMultiply",
"("... | Computes the result matrix of <i>A'*B</i>, or the same result as <br>
<code>
A.{@link #transpose() transpose()}.{@link #multiply(jsat.linear.Matrix) multiply(B)}
</code>
@param B the matrix to multiply by
@param threadPool the source of threads to do computation in parallel
@return a new matrix equal to <i>A'*B</i> | [
"Computes",
"the",
"result",
"matrix",
"of",
"<i",
">",
"A",
"*",
"B<",
"/",
"i",
">",
"or",
"the",
"same",
"result",
"as",
"<br",
">",
"<code",
">",
"A",
".",
"{",
"@link",
"#transpose",
"()",
"transpose",
"()",
"}",
".",
"{",
"@link",
"#multiply"... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/Matrix.java#L489-L494 |
sahan/RoboZombie | robozombie/src/main/java/org/apache/http42/client/utils/URLEncodedUtils.java | URLEncodedUtils.decodeFormFields | private static String decodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true);
} | java | private static String decodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true);
} | [
"private",
"static",
"String",
"decodeFormFields",
"(",
"final",
"String",
"content",
",",
"final",
"String",
"charset",
")",
"{",
"if",
"(",
"content",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"urldecode",
"(",
"content",
",",
"charse... | Decode/unescape www-url-form-encoded content.
@param content the content to decode, will decode '+' as space
@param charset the charset to use
@return | [
"Decode",
"/",
"unescape",
"www",
"-",
"url",
"-",
"form",
"-",
"encoded",
"content",
"."
] | train | https://github.com/sahan/RoboZombie/blob/2e02f0d41647612e9d89360c5c48811ea86b33c8/robozombie/src/main/java/org/apache/http42/client/utils/URLEncodedUtils.java#L447-L452 |
Azure/azure-sdk-for-java | edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/BandwidthSchedulesInner.java | BandwidthSchedulesInner.beginCreateOrUpdateAsync | public Observable<BandwidthScheduleInner> beginCreateOrUpdateAsync(String deviceName, String name, String resourceGroupName, BandwidthScheduleInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, parameters).map(new Func1<ServiceResponse<BandwidthScheduleInner>, BandwidthScheduleInner>() {
@Override
public BandwidthScheduleInner call(ServiceResponse<BandwidthScheduleInner> response) {
return response.body();
}
});
} | java | public Observable<BandwidthScheduleInner> beginCreateOrUpdateAsync(String deviceName, String name, String resourceGroupName, BandwidthScheduleInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, parameters).map(new Func1<ServiceResponse<BandwidthScheduleInner>, BandwidthScheduleInner>() {
@Override
public BandwidthScheduleInner call(ServiceResponse<BandwidthScheduleInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BandwidthScheduleInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"deviceName",
",",
"String",
"name",
",",
"String",
"resourceGroupName",
",",
"BandwidthScheduleInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceRe... | Creates or updates a bandwidth schedule.
@param deviceName The device name.
@param name The bandwidth schedule name which needs to be added/updated.
@param resourceGroupName The resource group name.
@param parameters The bandwidth schedule to be added or updated.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BandwidthScheduleInner object | [
"Creates",
"or",
"updates",
"a",
"bandwidth",
"schedule",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/BandwidthSchedulesInner.java#L435-L442 |
kiegroup/droolsjbpm-integration | kie-maven-plugin/src/main/java/org/kie/maven/plugin/BytecodeInjectReactive.java | BytecodeInjectReactive.addMethod | private static int addMethod(ConstPool cPool, CtMethod method) {
// addMethodrefInfo is a safe add, if constant already present it return the existing value without adding.
return cPool.addMethodrefInfo( cPool.getThisClassInfo(), method.getName(), method.getSignature() );
} | java | private static int addMethod(ConstPool cPool, CtMethod method) {
// addMethodrefInfo is a safe add, if constant already present it return the existing value without adding.
return cPool.addMethodrefInfo( cPool.getThisClassInfo(), method.getName(), method.getSignature() );
} | [
"private",
"static",
"int",
"addMethod",
"(",
"ConstPool",
"cPool",
",",
"CtMethod",
"method",
")",
"{",
"// addMethodrefInfo is a safe add, if constant already present it return the existing value without adding.",
"return",
"cPool",
".",
"addMethodrefInfo",
"(",
"cPool",
".",... | Add Method to ConstPool. If method was not in the ConstPool will add and return index, otherwise will return index of already existing entry of constpool | [
"Add",
"Method",
"to",
"ConstPool",
".",
"If",
"method",
"was",
"not",
"in",
"the",
"ConstPool",
"will",
"add",
"and",
"return",
"index",
"otherwise",
"will",
"return",
"index",
"of",
"already",
"existing",
"entry",
"of",
"constpool"
] | train | https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-maven-plugin/src/main/java/org/kie/maven/plugin/BytecodeInjectReactive.java#L215-L218 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java | BitmapAnalyser.analyse | public static BitmapStatistics analyse(RoaringBitmap r) {
int acCount = 0;
int acCardinalitySum = 0;
int bcCount = 0;
int rcCount = 0;
ContainerPointer cp = r.getContainerPointer();
while (cp.getContainer() != null) {
if (cp.isBitmapContainer()) {
bcCount += 1;
} else if (cp.isRunContainer()) {
rcCount += 1;
} else {
acCount += 1;
acCardinalitySum += cp.getCardinality();
}
cp.advance();
}
BitmapStatistics.ArrayContainersStats acStats =
new BitmapStatistics.ArrayContainersStats(acCount, acCardinalitySum);
return new BitmapStatistics(acStats, bcCount, rcCount);
} | java | public static BitmapStatistics analyse(RoaringBitmap r) {
int acCount = 0;
int acCardinalitySum = 0;
int bcCount = 0;
int rcCount = 0;
ContainerPointer cp = r.getContainerPointer();
while (cp.getContainer() != null) {
if (cp.isBitmapContainer()) {
bcCount += 1;
} else if (cp.isRunContainer()) {
rcCount += 1;
} else {
acCount += 1;
acCardinalitySum += cp.getCardinality();
}
cp.advance();
}
BitmapStatistics.ArrayContainersStats acStats =
new BitmapStatistics.ArrayContainersStats(acCount, acCardinalitySum);
return new BitmapStatistics(acStats, bcCount, rcCount);
} | [
"public",
"static",
"BitmapStatistics",
"analyse",
"(",
"RoaringBitmap",
"r",
")",
"{",
"int",
"acCount",
"=",
"0",
";",
"int",
"acCardinalitySum",
"=",
"0",
";",
"int",
"bcCount",
"=",
"0",
";",
"int",
"rcCount",
"=",
"0",
";",
"ContainerPointer",
"cp",
... | Analyze the internal representation of bitmap
@param r the bitmap
@return the statistics | [
"Analyze",
"the",
"internal",
"representation",
"of",
"bitmap"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/insights/BitmapAnalyser.java#L15-L35 |
UrielCh/ovh-java-sdk | ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java | ApiOvhDomain.serviceName_configurations_obfuscatedEmails_GET | public ArrayList<OvhObfuscatedEmails> serviceName_configurations_obfuscatedEmails_GET(String serviceName) throws IOException {
String qPath = "/domain/{serviceName}/configurations/obfuscatedEmails";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t9);
} | java | public ArrayList<OvhObfuscatedEmails> serviceName_configurations_obfuscatedEmails_GET(String serviceName) throws IOException {
String qPath = "/domain/{serviceName}/configurations/obfuscatedEmails";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t9);
} | [
"public",
"ArrayList",
"<",
"OvhObfuscatedEmails",
">",
"serviceName_configurations_obfuscatedEmails_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/domain/{serviceName}/configurations/obfuscatedEmails\"",
";",
"StringBuilder",
... | Retrieve obfuscated emails configuration
REST: GET /domain/{serviceName}/configurations/obfuscatedEmails
@param serviceName [required] The internal name of your domain | [
"Retrieve",
"obfuscated",
"emails",
"configuration"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L1576-L1581 |
andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java | AbstractAdminController.resolveLocale | protected void resolveLocale(String language, HttpServletRequest request, HttpServletResponse response){
final LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(language);
resolveLocale((Locale) localeEditor.getValue(), request, response);
} | java | protected void resolveLocale(String language, HttpServletRequest request, HttpServletResponse response){
final LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(language);
resolveLocale((Locale) localeEditor.getValue(), request, response);
} | [
"protected",
"void",
"resolveLocale",
"(",
"String",
"language",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"final",
"LocaleEditor",
"localeEditor",
"=",
"new",
"LocaleEditor",
"(",
")",
";",
"localeEditor",
".",
"setAsTe... | manually resolve of locale ... to request. useful for path variables
@param language locale representation as string
@param request
@param response | [
"manually",
"resolve",
"of",
"locale",
"...",
"to",
"request",
".",
"useful",
"for",
"path",
"variables"
] | train | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java#L136-L140 |
OpenLiberty/open-liberty | dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/util/BlockingList.java | BlockingList.putIfAbsent | @FFDCIgnore(IllegalArgumentException.class)
public boolean putIfAbsent(K key, E element) {
try {
put(key, element);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} | java | @FFDCIgnore(IllegalArgumentException.class)
public boolean putIfAbsent(K key, E element) {
try {
put(key, element);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} | [
"@",
"FFDCIgnore",
"(",
"IllegalArgumentException",
".",
"class",
")",
"public",
"boolean",
"putIfAbsent",
"(",
"K",
"key",
",",
"E",
"element",
")",
"{",
"try",
"{",
"put",
"(",
"key",
",",
"element",
")",
";",
"return",
"true",
";",
"}",
"catch",
"("... | Add the element associated with the given key into the list at the established position for that key.
@param key the key to use to add the element, which must match one of the keys provided to the constructor
@param element the element to add
@return <code>true</code> if the element was added and <code>false</code> otherwise | [
"Add",
"the",
"element",
"associated",
"with",
"the",
"given",
"key",
"into",
"the",
"list",
"at",
"the",
"established",
"position",
"for",
"that",
"key",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/util/BlockingList.java#L484-L492 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/BaasACL.java | BaasACL.hasUserGrant | public boolean hasUserGrant(Grant grant,BaasUser user){
if (user==null) throw new IllegalArgumentException("username cannot be null");
return hasUserGrant(grant, user.getName());
} | java | public boolean hasUserGrant(Grant grant,BaasUser user){
if (user==null) throw new IllegalArgumentException("username cannot be null");
return hasUserGrant(grant, user.getName());
} | [
"public",
"boolean",
"hasUserGrant",
"(",
"Grant",
"grant",
",",
"BaasUser",
"user",
")",
"{",
"if",
"(",
"user",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"username cannot be null\"",
")",
";",
"return",
"hasUserGrant",
"(",
"grant",... | Checks if the {@code user} has the specified {@code grant}
@param grant a {@link com.baasbox.android.Grant}
@param user a {@link com.baasbox.android.BaasUser}
@return | [
"Checks",
"if",
"the",
"{"
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasACL.java#L114-L117 |
Azure/azure-sdk-for-java | dns/resource-manager/v2016_04_01/src/main/java/com/microsoft/azure/management/dns/v2016_04_01/implementation/RecordSetsInner.java | RecordSetsInner.createOrUpdate | public RecordSetInner createOrUpdate(String resourceGroupName, String zoneName, String relativeRecordSetName, RecordType recordType, RecordSetInner parameters, String ifMatch, String ifNoneMatch) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch).toBlocking().single().body();
} | java | public RecordSetInner createOrUpdate(String resourceGroupName, String zoneName, String relativeRecordSetName, RecordType recordType, RecordSetInner parameters, String ifMatch, String ifNoneMatch) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch).toBlocking().single().body();
} | [
"public",
"RecordSetInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"zoneName",
",",
"String",
"relativeRecordSetName",
",",
"RecordType",
"recordType",
",",
"RecordSetInner",
"parameters",
",",
"String",
"ifMatch",
",",
"String",
"ifNoneMat... | Creates or updates a record set within a DNS zone.
@param resourceGroupName The name of the resource group.
@param zoneName The name of the DNS zone (without a terminating dot).
@param relativeRecordSetName The name of the record set, relative to the name of the zone.
@param recordType The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
@param parameters Parameters supplied to the CreateOrUpdate operation.
@param ifMatch The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwritting any concurrent changes.
@param ifNoneMatch Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored.
@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 RecordSetInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"record",
"set",
"within",
"a",
"DNS",
"zone",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2016_04_01/src/main/java/com/microsoft/azure/management/dns/v2016_04_01/implementation/RecordSetsInner.java#L432-L434 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/Polygon.java | Polygon.pointsAsRect | public static ArrayList<IGeoPoint> pointsAsRect(GeoPoint center, double lengthInMeters, double widthInMeters){
ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4);
GeoPoint east = center.destinationPoint(lengthInMeters*0.5, 90.0f);
GeoPoint south = center.destinationPoint(widthInMeters*0.5, 180.0f);
double westLon = center.getLongitude()*2 - east.getLongitude();
double northLat = center.getLatitude()*2 - south.getLatitude();
points.add(new GeoPoint(south.getLatitude(), east.getLongitude()));
points.add(new GeoPoint(south.getLatitude(), westLon));
points.add(new GeoPoint(northLat, westLon));
points.add(new GeoPoint(northLat, east.getLongitude()));
return points;
} | java | public static ArrayList<IGeoPoint> pointsAsRect(GeoPoint center, double lengthInMeters, double widthInMeters){
ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4);
GeoPoint east = center.destinationPoint(lengthInMeters*0.5, 90.0f);
GeoPoint south = center.destinationPoint(widthInMeters*0.5, 180.0f);
double westLon = center.getLongitude()*2 - east.getLongitude();
double northLat = center.getLatitude()*2 - south.getLatitude();
points.add(new GeoPoint(south.getLatitude(), east.getLongitude()));
points.add(new GeoPoint(south.getLatitude(), westLon));
points.add(new GeoPoint(northLat, westLon));
points.add(new GeoPoint(northLat, east.getLongitude()));
return points;
} | [
"public",
"static",
"ArrayList",
"<",
"IGeoPoint",
">",
"pointsAsRect",
"(",
"GeoPoint",
"center",
",",
"double",
"lengthInMeters",
",",
"double",
"widthInMeters",
")",
"{",
"ArrayList",
"<",
"IGeoPoint",
">",
"points",
"=",
"new",
"ArrayList",
"<",
"IGeoPoint",... | Build a list of GeoPoint as a rectangle.
@param center of the rectangle
@param lengthInMeters on longitude
@param widthInMeters on latitude
@return the list of 4 GeoPoint | [
"Build",
"a",
"list",
"of",
"GeoPoint",
"as",
"a",
"rectangle",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/Polygon.java#L228-L239 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/Client.java | Client.controlEventHandler | public void controlEventHandler(final ControlEventHandler controlEventHandler) {
env.setControlEventHandler(new ControlEventHandler() {
@Override
public void onEvent(ChannelFlowController flowController, ByteBuf event) {
if (DcpSnapshotMarkerRequest.is(event)) {
// Keep snapshot information in the session state, but also forward event to user
short partition = DcpSnapshotMarkerRequest.partition(event);
PartitionState ps = sessionState().get(partition);
ps.setSnapshotStartSeqno(DcpSnapshotMarkerRequest.startSeqno(event));
ps.setSnapshotEndSeqno(DcpSnapshotMarkerRequest.endSeqno(event));
sessionState().set(partition, ps);
} else if (DcpFailoverLogResponse.is(event)) {
// Do not forward failover log responses for now since their info is kept
// in the session state transparently
handleFailoverLogResponse(event);
event.release();
return;
} else if (RollbackMessage.is(event)) {
// even if forwarded to the user, warn in case the user is not
// aware of rollback messages.
LOGGER.warn(
"Received rollback for vbucket {} to seqno {}",
RollbackMessage.vbucket(event),
RollbackMessage.seqno(event)
);
}
// Forward event to user.
controlEventHandler.onEvent(flowController, event);
}
});
} | java | public void controlEventHandler(final ControlEventHandler controlEventHandler) {
env.setControlEventHandler(new ControlEventHandler() {
@Override
public void onEvent(ChannelFlowController flowController, ByteBuf event) {
if (DcpSnapshotMarkerRequest.is(event)) {
// Keep snapshot information in the session state, but also forward event to user
short partition = DcpSnapshotMarkerRequest.partition(event);
PartitionState ps = sessionState().get(partition);
ps.setSnapshotStartSeqno(DcpSnapshotMarkerRequest.startSeqno(event));
ps.setSnapshotEndSeqno(DcpSnapshotMarkerRequest.endSeqno(event));
sessionState().set(partition, ps);
} else if (DcpFailoverLogResponse.is(event)) {
// Do not forward failover log responses for now since their info is kept
// in the session state transparently
handleFailoverLogResponse(event);
event.release();
return;
} else if (RollbackMessage.is(event)) {
// even if forwarded to the user, warn in case the user is not
// aware of rollback messages.
LOGGER.warn(
"Received rollback for vbucket {} to seqno {}",
RollbackMessage.vbucket(event),
RollbackMessage.seqno(event)
);
}
// Forward event to user.
controlEventHandler.onEvent(flowController, event);
}
});
} | [
"public",
"void",
"controlEventHandler",
"(",
"final",
"ControlEventHandler",
"controlEventHandler",
")",
"{",
"env",
".",
"setControlEventHandler",
"(",
"new",
"ControlEventHandler",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onEvent",
"(",
"ChannelFlowContro... | Stores a {@link ControlEventHandler} to be called when control events happen.
<p>
All events (passed as {@link ByteBuf}s) that the callback receives need to be handled
and at least released (by using {@link ByteBuf#release()}, otherwise they will leak.
<p>
The following messages can happen and should be handled depending on the needs of the
client:
<p>
- {@link RollbackMessage}: If during a connect phase the server responds with rollback
information, this event is forwarded to the callback. Does not need to be acknowledged.
<p>
- {@link DcpSnapshotMarkerRequest}: Server transmits data in batches called snapshots
before sending anything, it send marker message, which contains start and end sequence
numbers of the data in it. Need to be acknowledged.
<p>
Keep in mind that the callback is executed on the IO thread (netty's thread pool for the
event loops) so further synchronization is needed if the data needs to be used on a different
thread in a thread safe manner.
@param controlEventHandler the event handler to use. | [
"Stores",
"a",
"{",
"@link",
"ControlEventHandler",
"}",
"to",
"be",
"called",
"when",
"control",
"events",
"happen",
".",
"<p",
">",
"All",
"events",
"(",
"passed",
"as",
"{",
"@link",
"ByteBuf",
"}",
"s",
")",
"that",
"the",
"callback",
"receives",
"ne... | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/Client.java#L219-L250 |
spring-projects/spring-social | spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java | ConnectController.connectionStatus | @RequestMapping(value="/{providerId}", method=RequestMethod.GET)
public String connectionStatus(@PathVariable String providerId, NativeWebRequest request, Model model) {
setNoCache(request);
processFlash(request, model);
List<Connection<?>> connections = connectionRepository.findConnections(providerId);
setNoCache(request);
if (connections.isEmpty()) {
return connectView(providerId);
} else {
model.addAttribute("connections", connections);
return connectedView(providerId);
}
} | java | @RequestMapping(value="/{providerId}", method=RequestMethod.GET)
public String connectionStatus(@PathVariable String providerId, NativeWebRequest request, Model model) {
setNoCache(request);
processFlash(request, model);
List<Connection<?>> connections = connectionRepository.findConnections(providerId);
setNoCache(request);
if (connections.isEmpty()) {
return connectView(providerId);
} else {
model.addAttribute("connections", connections);
return connectedView(providerId);
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/{providerId}\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"String",
"connectionStatus",
"(",
"@",
"PathVariable",
"String",
"providerId",
",",
"NativeWebRequest",
"request",
",",
"Model",
"model"... | Render the status of the connections to the service provider to the user as HTML in their web browser.
@param providerId the ID of the provider to show connection status
@param request the request
@param model the model
@return the view name of the connection status page for all providers | [
"Render",
"the",
"status",
"of",
"the",
"connections",
"to",
"the",
"service",
"provider",
"to",
"the",
"user",
"as",
"HTML",
"in",
"their",
"web",
"browser",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java#L222-L234 |
jamesagnew/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java | ModelScanner.pullAnnotation | static <T extends Annotation> T pullAnnotation(AnnotatedElement theTarget, Class<T> theAnnotationType) {
T retVal = theTarget.getAnnotation(theAnnotationType);
return retVal;
} | java | static <T extends Annotation> T pullAnnotation(AnnotatedElement theTarget, Class<T> theAnnotationType) {
T retVal = theTarget.getAnnotation(theAnnotationType);
return retVal;
} | [
"static",
"<",
"T",
"extends",
"Annotation",
">",
"T",
"pullAnnotation",
"(",
"AnnotatedElement",
"theTarget",
",",
"Class",
"<",
"T",
">",
"theAnnotationType",
")",
"{",
"T",
"retVal",
"=",
"theTarget",
".",
"getAnnotation",
"(",
"theAnnotationType",
")",
";"... | There are two implementations of all of the annotations (e.g. {@link Child} since the HL7.org ones will eventually replace the HAPI
ones. Annotations can't extend each other or implement interfaces or anything like that, so rather than duplicate all of the annotation processing code this method just creates an interface
Proxy to simulate the HAPI annotations if the HL7.org ones are found instead. | [
"There",
"are",
"two",
"implementations",
"of",
"all",
"of",
"the",
"annotations",
"(",
"e",
".",
"g",
".",
"{"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java#L463-L466 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/Effects.java | Effects.queueAnimation | public void queueAnimation(final GQAnimation anim, final int duration) {
if (isOff()) {
anim.onStart();
anim.onComplete();
} else {
queue(anim.e, DEFAULT_NAME, new Function() {
public void cancel(Element e) {
Animation anim = (Animation) data(e, GQAnimation.ACTUAL_ANIMATION, null);
if (anim != null) {
anim.cancel();
}
}
public void f(Element e) {
anim.run(duration);
}
});
}
} | java | public void queueAnimation(final GQAnimation anim, final int duration) {
if (isOff()) {
anim.onStart();
anim.onComplete();
} else {
queue(anim.e, DEFAULT_NAME, new Function() {
public void cancel(Element e) {
Animation anim = (Animation) data(e, GQAnimation.ACTUAL_ANIMATION, null);
if (anim != null) {
anim.cancel();
}
}
public void f(Element e) {
anim.run(duration);
}
});
}
} | [
"public",
"void",
"queueAnimation",
"(",
"final",
"GQAnimation",
"anim",
",",
"final",
"int",
"duration",
")",
"{",
"if",
"(",
"isOff",
"(",
")",
")",
"{",
"anim",
".",
"onStart",
"(",
")",
";",
"anim",
".",
"onComplete",
"(",
")",
";",
"}",
"else",
... | Queue an animation for an element.
The goal of this method is to reuse animations.
@param e
@param anim
@param duration | [
"Queue",
"an",
"animation",
"for",
"an",
"element",
"."
] | train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/Effects.java#L122-L140 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java | ResourceGroovyMethods.eachFileMatch | public static void eachFileMatch(final File self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure)
throws FileNotFoundException, IllegalArgumentException {
eachFileMatch(self, FileType.ANY, nameFilter, closure);
} | java | public static void eachFileMatch(final File self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure)
throws FileNotFoundException, IllegalArgumentException {
eachFileMatch(self, FileType.ANY, nameFilter, closure);
} | [
"public",
"static",
"void",
"eachFileMatch",
"(",
"final",
"File",
"self",
",",
"final",
"Object",
"nameFilter",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"java.io.File\"",
")",
"final",
"Closure",
"closur... | Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory
- calling the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Both regular files and subdirectories are matched.
@param self a File (that happens to be a folder/directory)
@param nameFilter the nameFilter to perform on the name of the file (using the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method)
@param closure the closure to invoke
@throws FileNotFoundException if the given directory does not exist
@throws IllegalArgumentException if the provided File object does not represent a directory
@see #eachFileMatch(java.io.File, groovy.io.FileType, java.lang.Object, groovy.lang.Closure)
@since 1.5.0 | [
"Invokes",
"the",
"closure",
"for",
"each",
"file",
"whose",
"name",
"(",
"file",
".",
"name",
")",
"matches",
"the",
"given",
"nameFilter",
"in",
"the",
"given",
"directory",
"-",
"calling",
"the",
"{",
"@link",
"DefaultGroovyMethods#isCase",
"(",
"java",
"... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L1563-L1566 |
dejv78/javafx-commons | jfx-controls/src/main/java/dejv/jfx/controls/radialmenu1/ContextRadialMenu.java | ContextRadialMenu.showAt | public void showAt(Node target, double x, double y) {
requireNonNull(target, "Parameter 'target' is null");
internalShow(pointer, target, x, y);
pointer.setVisible(true);
} | java | public void showAt(Node target, double x, double y) {
requireNonNull(target, "Parameter 'target' is null");
internalShow(pointer, target, x, y);
pointer.setVisible(true);
} | [
"public",
"void",
"showAt",
"(",
"Node",
"target",
",",
"double",
"x",
",",
"double",
"y",
")",
"{",
"requireNonNull",
"(",
"target",
",",
"\"Parameter 'target' is null\"",
")",
";",
"internalShow",
"(",
"pointer",
",",
"target",
",",
"x",
",",
"y",
")",
... | Shows the <code>ContextRadialMenu</code> at specified coordinates.
@param target Target node. This will be sent as parameter to all triggered actions.
@param x X-coord
@param y Y-coord | [
"Shows",
"the",
"<code",
">",
"ContextRadialMenu<",
"/",
"code",
">",
"at",
"specified",
"coordinates",
"."
] | train | https://github.com/dejv78/javafx-commons/blob/ea846eeeb4ed43a7628a40931a3e6f27d513592f/jfx-controls/src/main/java/dejv/jfx/controls/radialmenu1/ContextRadialMenu.java#L134-L139 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/database/CmsHtmlImport.java | CmsHtmlImport.getAbsoluteUri | public String getAbsoluteUri(String relativeUri, String baseUri) {
if ((relativeUri == null) || (relativeUri.charAt(0) == '/') || (relativeUri.startsWith("#"))) {
return relativeUri;
}
// if we are on a windows system, we must add a ":" in the uri later
String windowsAddition = "";
if (File.separator.equals("\\")) {
windowsAddition = ":";
}
try {
URL baseUrl = new URL("file://");
URL url = new URL(new URL(baseUrl, "file://" + baseUri), relativeUri);
if (url.getQuery() == null) {
if (url.getRef() == null) {
return url.getHost() + windowsAddition + url.getPath();
} else {
return url.getHost() + windowsAddition + url.getPath() + "#" + url.getRef();
}
} else {
return url.getHost() + windowsAddition + url.getPath() + "?" + url.getQuery();
}
} catch (MalformedURLException e) {
return relativeUri;
}
} | java | public String getAbsoluteUri(String relativeUri, String baseUri) {
if ((relativeUri == null) || (relativeUri.charAt(0) == '/') || (relativeUri.startsWith("#"))) {
return relativeUri;
}
// if we are on a windows system, we must add a ":" in the uri later
String windowsAddition = "";
if (File.separator.equals("\\")) {
windowsAddition = ":";
}
try {
URL baseUrl = new URL("file://");
URL url = new URL(new URL(baseUrl, "file://" + baseUri), relativeUri);
if (url.getQuery() == null) {
if (url.getRef() == null) {
return url.getHost() + windowsAddition + url.getPath();
} else {
return url.getHost() + windowsAddition + url.getPath() + "#" + url.getRef();
}
} else {
return url.getHost() + windowsAddition + url.getPath() + "?" + url.getQuery();
}
} catch (MalformedURLException e) {
return relativeUri;
}
} | [
"public",
"String",
"getAbsoluteUri",
"(",
"String",
"relativeUri",
",",
"String",
"baseUri",
")",
"{",
"if",
"(",
"(",
"relativeUri",
"==",
"null",
")",
"||",
"(",
"relativeUri",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
")",
"||",
"(",
"relativeU... | Calculates an absolute uri from a relative "uri" and the given absolute "baseUri".<p>
If "uri" is already absolute, it is returned unchanged.
This method also returns "uri" unchanged if it is not well-formed.<p>
@param relativeUri the relative uri to calculate an absolute uri for
@param baseUri the base uri, this must be an absolute uri
@return an absolute uri calculated from "uri" and "baseUri" | [
"Calculates",
"an",
"absolute",
"uri",
"from",
"a",
"relative",
"uri",
"and",
"the",
"given",
"absolute",
"baseUri",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/database/CmsHtmlImport.java#L224-L252 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/birch/CFTree.java | CFTree.findLeaf | public ClusteringFeature findLeaf(NumberVector nv) {
if(root == null) {
throw new IllegalStateException("CFTree not yet built.");
}
return findLeaf(root, nv);
} | java | public ClusteringFeature findLeaf(NumberVector nv) {
if(root == null) {
throw new IllegalStateException("CFTree not yet built.");
}
return findLeaf(root, nv);
} | [
"public",
"ClusteringFeature",
"findLeaf",
"(",
"NumberVector",
"nv",
")",
"{",
"if",
"(",
"root",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"CFTree not yet built.\"",
")",
";",
"}",
"return",
"findLeaf",
"(",
"root",
",",
"nv",
... | Find the leaf of a cluster, to get the final cluster assignment.
<p>
In contrast to {@link #insert}, this does not modify the tree.
@param nv Object data
@return Leaf this vector should be assigned to | [
"Find",
"the",
"leaf",
"of",
"a",
"cluster",
"to",
"get",
"the",
"final",
"cluster",
"assignment",
".",
"<p",
">",
"In",
"contrast",
"to",
"{",
"@link",
"#insert",
"}",
"this",
"does",
"not",
"modify",
"the",
"tree",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/birch/CFTree.java#L307-L312 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/MutableArray.java | MutableArray.setNumber | @NonNull
@Override
public MutableArray setNumber(int index, Number value) {
return setValue(index, value);
} | java | @NonNull
@Override
public MutableArray setNumber(int index, Number value) {
return setValue(index, value);
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"MutableArray",
"setNumber",
"(",
"int",
"index",
",",
"Number",
"value",
")",
"{",
"return",
"setValue",
"(",
"index",
",",
"value",
")",
";",
"}"
] | Sets an NSNumber object at the given index.
@param index the index. This value must not exceed the bounds of the array.
@param value the Number object
@return The self object | [
"Sets",
"an",
"NSNumber",
"object",
"at",
"the",
"given",
"index",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableArray.java#L130-L134 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/util/VelocityParser.java | VelocityParser.getTableElement | public int getTableElement(char[] array, int currentIndex, StringBuffer velocityBlock,
VelocityParserContext context)
{
return getParameters(array, currentIndex, velocityBlock, ']', context);
} | java | public int getTableElement(char[] array, int currentIndex, StringBuffer velocityBlock,
VelocityParserContext context)
{
return getParameters(array, currentIndex, velocityBlock, ']', context);
} | [
"public",
"int",
"getTableElement",
"(",
"char",
"[",
"]",
"array",
",",
"int",
"currentIndex",
",",
"StringBuffer",
"velocityBlock",
",",
"VelocityParserContext",
"context",
")",
"{",
"return",
"getParameters",
"(",
"array",
",",
"currentIndex",
",",
"velocityBlo... | Get a Velocity table.
@param array the source to parse
@param currentIndex the current index in the <code>array</code>
@param velocityBlock the buffer where to append matched velocity block
@param context the parser context to put some informations
@return the index in the <code>array</code> after the matched block | [
"Get",
"a",
"Velocity",
"table",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/util/VelocityParser.java#L517-L521 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/generator/simple/WikipediaTemplateInfoDumpWriter.java | WikipediaTemplateInfoDumpWriter.writeSQL | void writeSQL(boolean revTableExists, boolean pageTableExists, GeneratorMode mode)
{
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new BufferedOutputStream(new FileOutputStream(outputPath)), charset))){
StringBuilder dataToDump = new StringBuilder();
dataToDump.append(generateTemplateIdSQLStatement(this.tableExists));
if (mode.active_for_pages) {
dataToDump.append(generatePageSQLStatement(pageTableExists,
mode.templateNameToPageId));
}
if (mode.active_for_revisions) {
dataToDump.append(generateRevisionSQLStatement(revTableExists,
mode.templateNameToRevId));
}
writer.write(dataToDump.toString());
}
catch (IOException e) {
logger.error("Error writing SQL file: {}", e.getMessage(), e);
}
} | java | void writeSQL(boolean revTableExists, boolean pageTableExists, GeneratorMode mode)
{
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new BufferedOutputStream(new FileOutputStream(outputPath)), charset))){
StringBuilder dataToDump = new StringBuilder();
dataToDump.append(generateTemplateIdSQLStatement(this.tableExists));
if (mode.active_for_pages) {
dataToDump.append(generatePageSQLStatement(pageTableExists,
mode.templateNameToPageId));
}
if (mode.active_for_revisions) {
dataToDump.append(generateRevisionSQLStatement(revTableExists,
mode.templateNameToRevId));
}
writer.write(dataToDump.toString());
}
catch (IOException e) {
logger.error("Error writing SQL file: {}", e.getMessage(), e);
}
} | [
"void",
"writeSQL",
"(",
"boolean",
"revTableExists",
",",
"boolean",
"pageTableExists",
",",
"GeneratorMode",
"mode",
")",
"{",
"try",
"(",
"Writer",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"BufferedOutputStream",
"("... | Generate and write sql statements to output file
@param revTableExists
if revision table does not exists -> create index
@param pageTableExists
if page table does not exists -> create index
@param mode
generation mode | [
"Generate",
"and",
"write",
"sql",
"statements",
"to",
"output",
"file"
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/generator/simple/WikipediaTemplateInfoDumpWriter.java#L223-L244 |
xcesco/kripton | kripton-core/src/main/java/com/abubusoft/kripton/common/PrimitiveUtils.java | PrimitiveUtils.readByte | public static Byte readByte(String value, Byte defaultValue) {
if (!StringUtils.hasText(value)) return defaultValue;
return Byte.valueOf(value);
} | java | public static Byte readByte(String value, Byte defaultValue) {
if (!StringUtils.hasText(value)) return defaultValue;
return Byte.valueOf(value);
} | [
"public",
"static",
"Byte",
"readByte",
"(",
"String",
"value",
",",
"Byte",
"defaultValue",
")",
"{",
"if",
"(",
"!",
"StringUtils",
".",
"hasText",
"(",
"value",
")",
")",
"return",
"defaultValue",
";",
"return",
"Byte",
".",
"valueOf",
"(",
"value",
"... | Read byte.
@param value the value
@param defaultValue the default value
@return the byte | [
"Read",
"byte",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-core/src/main/java/com/abubusoft/kripton/common/PrimitiveUtils.java#L56-L60 |
wdtinc/mapbox-vector-tile-java | src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java | JtsAdapter.createTileGeom | public static TileGeomResult createTileGeom(List<Geometry> g,
Envelope tileEnvelope,
Envelope clipEnvelope,
GeometryFactory geomFactory,
MvtLayerParams mvtLayerParams,
IGeometryFilter filter) {
final Geometry tileClipGeom = geomFactory.toGeometry(clipEnvelope);
final AffineTransformation t = new AffineTransformation();
final double xDiff = tileEnvelope.getWidth();
final double yDiff = tileEnvelope.getHeight();
final double xOffset = -tileEnvelope.getMinX();
final double yOffset = -tileEnvelope.getMinY();
// Transform Setup: Shift to 0 as minimum value
t.translate(xOffset, yOffset);
// Transform Setup: Scale X and Y to tile extent values, flip Y values
t.scale(1d / (xDiff / (double) mvtLayerParams.extent),
-1d / (yDiff / (double) mvtLayerParams.extent));
// Transform Setup: Bump Y values to positive quadrant
t.translate(0d, (double) mvtLayerParams.extent);
// The area contained in BOTH the 'original geometry', g, AND the 'clip envelope geometry' is the 'tile geometry'
final List<Geometry> intersectedGeoms = flatIntersection(tileClipGeom, g);
final List<Geometry> transformedGeoms = new ArrayList<>(intersectedGeoms.size());
// Transform intersected geometry
Geometry nextTransformGeom;
Object nextUserData;
for(Geometry nextInterGeom : intersectedGeoms) {
nextUserData = nextInterGeom.getUserData();
nextTransformGeom = t.transform(nextInterGeom);
// Floating --> Integer, still contained within doubles
nextTransformGeom.apply(RoundingFilter.INSTANCE);
// TODO: Refactor line simplification
nextTransformGeom = TopologyPreservingSimplifier.simplify(nextTransformGeom, .1d); // Can't use 0d, specify value < .5d
nextTransformGeom.setUserData(nextUserData);
// Apply filter on transformed geometry
if(filter.accept(nextTransformGeom)) {
transformedGeoms.add(nextTransformGeom);
}
}
return new TileGeomResult(intersectedGeoms, transformedGeoms);
} | java | public static TileGeomResult createTileGeom(List<Geometry> g,
Envelope tileEnvelope,
Envelope clipEnvelope,
GeometryFactory geomFactory,
MvtLayerParams mvtLayerParams,
IGeometryFilter filter) {
final Geometry tileClipGeom = geomFactory.toGeometry(clipEnvelope);
final AffineTransformation t = new AffineTransformation();
final double xDiff = tileEnvelope.getWidth();
final double yDiff = tileEnvelope.getHeight();
final double xOffset = -tileEnvelope.getMinX();
final double yOffset = -tileEnvelope.getMinY();
// Transform Setup: Shift to 0 as minimum value
t.translate(xOffset, yOffset);
// Transform Setup: Scale X and Y to tile extent values, flip Y values
t.scale(1d / (xDiff / (double) mvtLayerParams.extent),
-1d / (yDiff / (double) mvtLayerParams.extent));
// Transform Setup: Bump Y values to positive quadrant
t.translate(0d, (double) mvtLayerParams.extent);
// The area contained in BOTH the 'original geometry', g, AND the 'clip envelope geometry' is the 'tile geometry'
final List<Geometry> intersectedGeoms = flatIntersection(tileClipGeom, g);
final List<Geometry> transformedGeoms = new ArrayList<>(intersectedGeoms.size());
// Transform intersected geometry
Geometry nextTransformGeom;
Object nextUserData;
for(Geometry nextInterGeom : intersectedGeoms) {
nextUserData = nextInterGeom.getUserData();
nextTransformGeom = t.transform(nextInterGeom);
// Floating --> Integer, still contained within doubles
nextTransformGeom.apply(RoundingFilter.INSTANCE);
// TODO: Refactor line simplification
nextTransformGeom = TopologyPreservingSimplifier.simplify(nextTransformGeom, .1d); // Can't use 0d, specify value < .5d
nextTransformGeom.setUserData(nextUserData);
// Apply filter on transformed geometry
if(filter.accept(nextTransformGeom)) {
transformedGeoms.add(nextTransformGeom);
}
}
return new TileGeomResult(intersectedGeoms, transformedGeoms);
} | [
"public",
"static",
"TileGeomResult",
"createTileGeom",
"(",
"List",
"<",
"Geometry",
">",
"g",
",",
"Envelope",
"tileEnvelope",
",",
"Envelope",
"clipEnvelope",
",",
"GeometryFactory",
"geomFactory",
",",
"MvtLayerParams",
"mvtLayerParams",
",",
"IGeometryFilter",
"f... | <p>Create geometry clipped and then converted to MVT 'extent' coordinates. Result
contains both clipped geometry (intersection) and transformed geometry for encoding to MVT.</p>
<p>Allows specifying separate tile and clipping coordinates. {@code clipEnvelope} can be bigger than
{@code tileEnvelope} to have geometry exist outside the MVT tile extent.</p>
@param g original 'source' geometry, passed through {@link #flatFeatureList(Geometry)}
@param tileEnvelope world coordinate bounds for tile, used for transforms
@param clipEnvelope world coordinates to clip tile by
@param geomFactory creates a geometry for the tile envelope
@param mvtLayerParams specifies vector tile properties
@param filter geometry values that fail filter after transforms are removed
@return tile geometry result
@see TileGeomResult | [
"<p",
">",
"Create",
"geometry",
"clipped",
"and",
"then",
"converted",
"to",
"MVT",
"extent",
"coordinates",
".",
"Result",
"contains",
"both",
"clipped",
"geometry",
"(",
"intersection",
")",
"and",
"transformed",
"geometry",
"for",
"encoding",
"to",
"MVT",
... | train | https://github.com/wdtinc/mapbox-vector-tile-java/blob/e5e3df3fc2260709e289f972a1348c0a1ea30339/src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java#L87-L141 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.doEntryEquals | private static boolean doEntryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) throws IOException {
InputStream is1 = null;
InputStream is2 = null;
try {
ZipEntry e1 = zf1.getEntry(path1);
ZipEntry e2 = zf2.getEntry(path2);
if (e1 == null && e2 == null) {
return true;
}
if (e1 == null || e2 == null) {
return false;
}
is1 = zf1.getInputStream(e1);
is2 = zf2.getInputStream(e2);
if (is1 == null && is2 == null) {
return true;
}
if (is1 == null || is2 == null) {
return false;
}
return IOUtils.contentEquals(is1, is2);
}
finally {
IOUtils.closeQuietly(is1);
IOUtils.closeQuietly(is2);
}
} | java | private static boolean doEntryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) throws IOException {
InputStream is1 = null;
InputStream is2 = null;
try {
ZipEntry e1 = zf1.getEntry(path1);
ZipEntry e2 = zf2.getEntry(path2);
if (e1 == null && e2 == null) {
return true;
}
if (e1 == null || e2 == null) {
return false;
}
is1 = zf1.getInputStream(e1);
is2 = zf2.getInputStream(e2);
if (is1 == null && is2 == null) {
return true;
}
if (is1 == null || is2 == null) {
return false;
}
return IOUtils.contentEquals(is1, is2);
}
finally {
IOUtils.closeQuietly(is1);
IOUtils.closeQuietly(is2);
}
} | [
"private",
"static",
"boolean",
"doEntryEquals",
"(",
"ZipFile",
"zf1",
",",
"ZipFile",
"zf2",
",",
"String",
"path1",
",",
"String",
"path2",
")",
"throws",
"IOException",
"{",
"InputStream",
"is1",
"=",
"null",
";",
"InputStream",
"is2",
"=",
"null",
";",
... | Compares two ZIP entries (byte-by-byte). .
@param zf1
first ZIP file.
@param zf2
second ZIP file.
@param path1
name of the first entry.
@param path2
name of the second entry.
@return <code>true</code> if the contents of the entries were same. | [
"Compares",
"two",
"ZIP",
"entries",
"(",
"byte",
"-",
"by",
"-",
"byte",
")",
".",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L3285-L3315 |
leancloud/java-sdk-all | android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/game/GameLoginSignUtil.java | GameLoginSignUtil.doCheck | private static void doCheck(String appId, String cpId, String privateKey, String publicKey, GameUserData userData, ICheckLoginSignHandler callback) {
// 创建body参数
byte[] body = getRequestBody(appId, cpId, privateKey, userData);
// 发送请求
sendRequest(URL, body, publicKey, callback);
} | java | private static void doCheck(String appId, String cpId, String privateKey, String publicKey, GameUserData userData, ICheckLoginSignHandler callback) {
// 创建body参数
byte[] body = getRequestBody(appId, cpId, privateKey, userData);
// 发送请求
sendRequest(URL, body, publicKey, callback);
} | [
"private",
"static",
"void",
"doCheck",
"(",
"String",
"appId",
",",
"String",
"cpId",
",",
"String",
"privateKey",
",",
"String",
"publicKey",
",",
"GameUserData",
"userData",
",",
"ICheckLoginSignHandler",
"callback",
")",
"{",
"// 创建body参数\r",
"byte",
"[",
"]... | 验签
@param appId 应用程序id,来源于华为开发者联盟上参数
@param cpId 开发者id,来源于开发者联盟
@param privateKey 私钥,来源于开发者联盟,非常重要的信息,注意保存避免泄露
@param publicKey 公钥,用来验签服务端返回的结果
@param userData 用户的登录结果数据
@param callback 验签结果回调 | [
"验签"
] | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/game/GameLoginSignUtil.java#L78-L84 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/FileSystem.java | FileSystem.getFileBlockLocations | public BlockLocation[] getFileBlockLocations(FileStatus file,
long start, long len) throws IOException {
if (file == null) {
return null;
}
if ( (start<0) || (len < 0) ) {
throw new IllegalArgumentException("Invalid start or len parameter");
}
if (file.getLen() < start) {
return new BlockLocation[0];
}
String[] name = { "localhost:50010" };
String[] host = { "localhost" };
return new BlockLocation[] { new BlockLocation(name, host, 0, file.getLen()) };
} | java | public BlockLocation[] getFileBlockLocations(FileStatus file,
long start, long len) throws IOException {
if (file == null) {
return null;
}
if ( (start<0) || (len < 0) ) {
throw new IllegalArgumentException("Invalid start or len parameter");
}
if (file.getLen() < start) {
return new BlockLocation[0];
}
String[] name = { "localhost:50010" };
String[] host = { "localhost" };
return new BlockLocation[] { new BlockLocation(name, host, 0, file.getLen()) };
} | [
"public",
"BlockLocation",
"[",
"]",
"getFileBlockLocations",
"(",
"FileStatus",
"file",
",",
"long",
"start",
",",
"long",
"len",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"(",
... | Return an array containing hostnames, offset and size of
portions of the given file. For a nonexistent
file or regions, null will be returned.
This call is most helpful with DFS, where it returns
hostnames of machines that contain the given file.
The FileSystem will simply return an elt containing 'localhost'. | [
"Return",
"an",
"array",
"containing",
"hostnames",
"offset",
"and",
"size",
"of",
"portions",
"of",
"the",
"given",
"file",
".",
"For",
"a",
"nonexistent",
"file",
"or",
"regions",
"null",
"will",
"be",
"returned",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L399-L416 |
aws/aws-sdk-java | aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/UnlinkIdentityRequest.java | UnlinkIdentityRequest.withLogins | public UnlinkIdentityRequest withLogins(java.util.Map<String, String> logins) {
setLogins(logins);
return this;
} | java | public UnlinkIdentityRequest withLogins(java.util.Map<String, String> logins) {
setLogins(logins);
return this;
} | [
"public",
"UnlinkIdentityRequest",
"withLogins",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"logins",
")",
"{",
"setLogins",
"(",
"logins",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A set of optional name-value pairs that map provider names to provider tokens.
</p>
@param logins
A set of optional name-value pairs that map provider names to provider tokens.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"set",
"of",
"optional",
"name",
"-",
"value",
"pairs",
"that",
"map",
"provider",
"names",
"to",
"provider",
"tokens",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/UnlinkIdentityRequest.java#L125-L128 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/AsyncTableEntryReader.java | AsyncTableEntryReader.readEntry | static AsyncTableEntryReader<TableEntry> readEntry(ArrayView soughtKey, long keyVersion, EntrySerializer serializer, TimeoutTimer timer) {
return new EntryReader(soughtKey, keyVersion, serializer, timer);
} | java | static AsyncTableEntryReader<TableEntry> readEntry(ArrayView soughtKey, long keyVersion, EntrySerializer serializer, TimeoutTimer timer) {
return new EntryReader(soughtKey, keyVersion, serializer, timer);
} | [
"static",
"AsyncTableEntryReader",
"<",
"TableEntry",
">",
"readEntry",
"(",
"ArrayView",
"soughtKey",
",",
"long",
"keyVersion",
",",
"EntrySerializer",
"serializer",
",",
"TimeoutTimer",
"timer",
")",
"{",
"return",
"new",
"EntryReader",
"(",
"soughtKey",
",",
"... | Creates a new {@link AsyncTableEntryReader} that can be used to read a {@link TableEntry} with a an optional
matching key.
@param soughtKey (Optional) An {@link ArrayView} representing the Key to match. If provided, a {@link TableEntry}
will only be returned if its {@link TableEntry#getKey()} matches this value.
@param keyVersion The version of the {@link TableEntry} that is located at this position. This will be used for
constructing the result and has no bearing on the reading/matching logic.
@param serializer The {@link EntrySerializer} to use for deserializing the {@link TableEntry} instance.
@param timer Timer for the whole operation.
@return A new instance of the {@link AsyncTableEntryReader} class. The {@link #getResult()} will be completed with
a {@link TableEntry} instance once the Key is matched. | [
"Creates",
"a",
"new",
"{",
"@link",
"AsyncTableEntryReader",
"}",
"that",
"can",
"be",
"used",
"to",
"read",
"a",
"{",
"@link",
"TableEntry",
"}",
"with",
"a",
"an",
"optional",
"matching",
"key",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/AsyncTableEntryReader.java#L91-L93 |
carewebframework/carewebframework-core | org.carewebframework.messaging-parent/org.carewebframework.messaging.amqp-parent/org.carewebframework.messaging.amqp.rabbitmq/src/main/java/org/carewebframework/messaging/amqp/rabbitmq/Broker.java | Broker.createChannel | private synchronized void createChannel(String channel) {
if (!channelExists(channel)) {
Queue queue = new Queue(channel, true, false, true);
admin.declareQueue(queue);
Binding binding = new Binding(channel, DestinationType.QUEUE, exchange.getName(), channel + ".#", null);
admin.declareBinding(binding);
}
} | java | private synchronized void createChannel(String channel) {
if (!channelExists(channel)) {
Queue queue = new Queue(channel, true, false, true);
admin.declareQueue(queue);
Binding binding = new Binding(channel, DestinationType.QUEUE, exchange.getName(), channel + ".#", null);
admin.declareBinding(binding);
}
} | [
"private",
"synchronized",
"void",
"createChannel",
"(",
"String",
"channel",
")",
"{",
"if",
"(",
"!",
"channelExists",
"(",
"channel",
")",
")",
"{",
"Queue",
"queue",
"=",
"new",
"Queue",
"(",
"channel",
",",
"true",
",",
"false",
",",
"true",
")",
... | Creates an event queue (thread safe) with the correct binding.
@param channel Name of event handled by queue. | [
"Creates",
"an",
"event",
"queue",
"(",
"thread",
"safe",
")",
"with",
"the",
"correct",
"binding",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.messaging-parent/org.carewebframework.messaging.amqp-parent/org.carewebframework.messaging.amqp.rabbitmq/src/main/java/org/carewebframework/messaging/amqp/rabbitmq/Broker.java#L89-L96 |
maven-nar/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/platforms/WindowsPlatform.java | WindowsPlatform.hasSameContent | private static boolean hasSameContent(final InputStream stream1, final InputStream stream2) throws IOException {
int byte1 = -1;
int byte2 = -1;
do {
byte1 = stream1.read();
byte2 = stream2.read();
} while (byte1 == byte2 && byte1 != -1);
return byte1 == byte2;
} | java | private static boolean hasSameContent(final InputStream stream1, final InputStream stream2) throws IOException {
int byte1 = -1;
int byte2 = -1;
do {
byte1 = stream1.read();
byte2 = stream2.read();
} while (byte1 == byte2 && byte1 != -1);
return byte1 == byte2;
} | [
"private",
"static",
"boolean",
"hasSameContent",
"(",
"final",
"InputStream",
"stream1",
",",
"final",
"InputStream",
"stream2",
")",
"throws",
"IOException",
"{",
"int",
"byte1",
"=",
"-",
"1",
";",
"int",
"byte2",
"=",
"-",
"1",
";",
"do",
"{",
"byte1",... | Compare two input streams for duplicate content
Naive implementation, but should not be performance issue.
@param stream1
stream
@param stream2
stream
@return true if streams are identical in content
@throws IOException
if error reading streams | [
"Compare",
"two",
"input",
"streams",
"for",
"duplicate",
"content"
] | train | https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/platforms/WindowsPlatform.java#L149-L158 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/brk/BreakpointMessageHandler.java | BreakpointMessageHandler.handleMessageReceivedFromServer | public boolean handleMessageReceivedFromServer(Message aMessage, boolean onlyIfInScope) {
if (! isBreakpoint(aMessage, false, onlyIfInScope)) {
return true;
}
// Do this outside of the semaphore loop so that the 'continue' button can apply to all queued break points
// but be reset when the next break point is hit
breakPanel.breakpointHit();
synchronized(semaphore) {
//breakPanel.breakpointHit();
if (breakPanel.isHoldMessage()) {
setBreakDisplay(aMessage, false);
waitUntilContinue(false);
}
}
breakPanel.clearAndDisableResponse();
return ! breakPanel.isToBeDropped();
} | java | public boolean handleMessageReceivedFromServer(Message aMessage, boolean onlyIfInScope) {
if (! isBreakpoint(aMessage, false, onlyIfInScope)) {
return true;
}
// Do this outside of the semaphore loop so that the 'continue' button can apply to all queued break points
// but be reset when the next break point is hit
breakPanel.breakpointHit();
synchronized(semaphore) {
//breakPanel.breakpointHit();
if (breakPanel.isHoldMessage()) {
setBreakDisplay(aMessage, false);
waitUntilContinue(false);
}
}
breakPanel.clearAndDisableResponse();
return ! breakPanel.isToBeDropped();
} | [
"public",
"boolean",
"handleMessageReceivedFromServer",
"(",
"Message",
"aMessage",
",",
"boolean",
"onlyIfInScope",
")",
"{",
"if",
"(",
"!",
"isBreakpoint",
"(",
"aMessage",
",",
"false",
",",
"onlyIfInScope",
")",
")",
"{",
"return",
"true",
";",
"}",
"// D... | Do not call if in {@link Mode#safe}.
@param aMessage
@param onlyIfInScope
@return False if message should be dropped. | [
"Do",
"not",
"call",
"if",
"in",
"{",
"@link",
"Mode#safe",
"}",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/brk/BreakpointMessageHandler.java#L97-L116 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/services/DefaultMetadataService.java | DefaultMetadataService.validateUniqueAttribute | private void validateUniqueAttribute(String entityType, String attributeName) throws AtlasException {
ClassType type = typeSystem.getDataType(ClassType.class, entityType);
AttributeInfo attribute = type.fieldMapping().fields.get(attributeName);
if(attribute == null) {
throw new IllegalArgumentException(
String.format("%s is not an attribute in %s", attributeName, entityType));
}
if (!attribute.isUnique) {
throw new IllegalArgumentException(
String.format("%s.%s is not a unique attribute", entityType, attributeName));
}
} | java | private void validateUniqueAttribute(String entityType, String attributeName) throws AtlasException {
ClassType type = typeSystem.getDataType(ClassType.class, entityType);
AttributeInfo attribute = type.fieldMapping().fields.get(attributeName);
if(attribute == null) {
throw new IllegalArgumentException(
String.format("%s is not an attribute in %s", attributeName, entityType));
}
if (!attribute.isUnique) {
throw new IllegalArgumentException(
String.format("%s.%s is not a unique attribute", entityType, attributeName));
}
} | [
"private",
"void",
"validateUniqueAttribute",
"(",
"String",
"entityType",
",",
"String",
"attributeName",
")",
"throws",
"AtlasException",
"{",
"ClassType",
"type",
"=",
"typeSystem",
".",
"getDataType",
"(",
"ClassType",
".",
"class",
",",
"entityType",
")",
";"... | Validate that attribute is unique attribute
@param entityType the entity type
@param attributeName the name of the attribute | [
"Validate",
"that",
"attribute",
"is",
"unique",
"attribute"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/services/DefaultMetadataService.java#L353-L364 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/AppUtil.java | AppUtil.startGalleryApp | public static void startGalleryApp(@NonNull final Activity activity, final int requestCode) {
Condition.INSTANCE.ensureNotNull(activity, "The activity may not be null");
Intent intent =
new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(activity.getPackageManager()) == null) {
throw new ActivityNotFoundException("Gallery app not available");
}
activity.startActivityForResult(intent, requestCode);
} | java | public static void startGalleryApp(@NonNull final Activity activity, final int requestCode) {
Condition.INSTANCE.ensureNotNull(activity, "The activity may not be null");
Intent intent =
new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(activity.getPackageManager()) == null) {
throw new ActivityNotFoundException("Gallery app not available");
}
activity.startActivityForResult(intent, requestCode);
} | [
"public",
"static",
"void",
"startGalleryApp",
"(",
"@",
"NonNull",
"final",
"Activity",
"activity",
",",
"final",
"int",
"requestCode",
")",
"{",
"Condition",
".",
"INSTANCE",
".",
"ensureNotNull",
"(",
"activity",
",",
"\"The activity may not be null\"",
")",
";... | Starts the gallery app in order to choose a picture. In an error occurs while starting the
gallery app, an {@link ActivityNotFoundException} will be thrown.
@param activity
The activity, the chosen image should be passed to by calling its
<code>onActivityResult</code> method, as an instance of the class {@link Activity}.
The activity may not be null
@param requestCode
The request code, which should be used to pass the captured picture to the given
activity, as an {@link Integer} value | [
"Starts",
"the",
"gallery",
"app",
"in",
"order",
"to",
"choose",
"a",
"picture",
".",
"In",
"an",
"error",
"occurs",
"while",
"starting",
"the",
"gallery",
"app",
"an",
"{",
"@link",
"ActivityNotFoundException",
"}",
"will",
"be",
"thrown",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/AppUtil.java#L112-L122 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/SeleniumSpec.java | SeleniumSpec.assertSeleniumNElementExists | @Then("^'(\\d+?)' elements? exists? with '([^:]*?):(.+?)'$")
public void assertSeleniumNElementExists(Integer expectedCount, String method, String element) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = commonspec.locateElement(method, element, expectedCount);
PreviousWebElements pwel = new PreviousWebElements(wel);
commonspec.setPreviousWebElements(pwel);
} | java | @Then("^'(\\d+?)' elements? exists? with '([^:]*?):(.+?)'$")
public void assertSeleniumNElementExists(Integer expectedCount, String method, String element) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = commonspec.locateElement(method, element, expectedCount);
PreviousWebElements pwel = new PreviousWebElements(wel);
commonspec.setPreviousWebElements(pwel);
} | [
"@",
"Then",
"(",
"\"^'(\\\\d+?)' elements? exists? with '([^:]*?):(.+?)'$\"",
")",
"public",
"void",
"assertSeleniumNElementExists",
"(",
"Integer",
"expectedCount",
",",
"String",
"method",
",",
"String",
"element",
")",
"throws",
"ClassNotFoundException",
",",
"NoSuchFie... | Checks if {@code expectedCount} webelements are found, with a location {@code method}.
@param expectedCount
@param method
@param element
@throws IllegalAccessException
@throws IllegalArgumentException
@throws SecurityException
@throws NoSuchFieldException
@throws ClassNotFoundException | [
"Checks",
"if",
"{",
"@code",
"expectedCount",
"}",
"webelements",
"are",
"found",
"with",
"a",
"location",
"{",
"@code",
"method",
"}",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/SeleniumSpec.java#L435-L440 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/WServlet.java | WServlet.serviceInt | protected void serviceInt(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// Check for resource request
boolean continueProcess = ServletUtil.checkResourceRequest(request, response);
if (!continueProcess) {
return;
}
// Create a support class to coordinate the web request.
WServletHelper helper = createServletHelper(request, response);
// Get the interceptors that will be used to plug in features.
InterceptorComponent interceptorChain = createInterceptorChain(request);
// Get the WComponent that represents the application we are serving.
WComponent ui = getUI(request);
ServletUtil.processRequest(helper, ui, interceptorChain);
} | java | protected void serviceInt(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// Check for resource request
boolean continueProcess = ServletUtil.checkResourceRequest(request, response);
if (!continueProcess) {
return;
}
// Create a support class to coordinate the web request.
WServletHelper helper = createServletHelper(request, response);
// Get the interceptors that will be used to plug in features.
InterceptorComponent interceptorChain = createInterceptorChain(request);
// Get the WComponent that represents the application we are serving.
WComponent ui = getUI(request);
ServletUtil.processRequest(helper, ui, interceptorChain);
} | [
"protected",
"void",
"serviceInt",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"// Check for resource request",
"boolean",
"continueProcess",
"=",
"ServletUtil",
... | Service internal. This method does the real work in servicing the http request. It integrates wcomponents into a
servlet environment via a servlet specific helper class.
@param request the http servlet request.
@param response the http servlet response.
@throws IOException an IO exception
@throws ServletException a servlet exception | [
"Service",
"internal",
".",
"This",
"method",
"does",
"the",
"real",
"work",
"in",
"servicing",
"the",
"http",
"request",
".",
"It",
"integrates",
"wcomponents",
"into",
"a",
"servlet",
"environment",
"via",
"a",
"servlet",
"specific",
"helper",
"class",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/WServlet.java#L130-L148 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/converter/json/ListExtractor.java | ListExtractor.extractObject | public Object extractObject(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts,boolean jsonify)
throws AttributeNotFoundException {
List list = (List) pValue;
int length = pConverter.getCollectionLength(list.size());
String pathPart = pPathParts.isEmpty() ? null : pPathParts.pop();
if (pathPart != null) {
return extractWithPath(pConverter, list, pPathParts, jsonify, pathPart);
} else {
return jsonify ? extractListAsJson(pConverter, list, pPathParts, length) : list;
}
} | java | public Object extractObject(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts,boolean jsonify)
throws AttributeNotFoundException {
List list = (List) pValue;
int length = pConverter.getCollectionLength(list.size());
String pathPart = pPathParts.isEmpty() ? null : pPathParts.pop();
if (pathPart != null) {
return extractWithPath(pConverter, list, pPathParts, jsonify, pathPart);
} else {
return jsonify ? extractListAsJson(pConverter, list, pPathParts, length) : list;
}
} | [
"public",
"Object",
"extractObject",
"(",
"ObjectToJsonConverter",
"pConverter",
",",
"Object",
"pValue",
",",
"Stack",
"<",
"String",
">",
"pPathParts",
",",
"boolean",
"jsonify",
")",
"throws",
"AttributeNotFoundException",
"{",
"List",
"list",
"=",
"(",
"List",... | Extract a list and, if to be jsonified, put it into an {@link JSONArray}. An index can be used (on top of
the extra args stack) in order to specify a single value within the list.
@param pConverter the global converter in order to be able do dispatch for
serializing inner data types
@param pValue the value to convert (must be a {@link List})
@param pPathParts extra arguments stack, which is popped to get an index for extracting a single element
of the list
@param jsonify whether to convert to a JSON object/list or whether the plain object
should be returned. The later is required for writing an inner value
@return the extracted object
@throws AttributeNotFoundException
@throws IndexOutOfBoundsException if an index is used which points outside the given list | [
"Extract",
"a",
"list",
"and",
"if",
"to",
"be",
"jsonified",
"put",
"it",
"into",
"an",
"{",
"@link",
"JSONArray",
"}",
".",
"An",
"index",
"can",
"be",
"used",
"(",
"on",
"top",
"of",
"the",
"extra",
"args",
"stack",
")",
"in",
"order",
"to",
"sp... | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/ListExtractor.java#L57-L67 |
JadiraOrg/jadira | bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java | BasicBinder.registerBinding | public final <S, T> void registerBinding(Class<S> source, Class<T> target, Binding<S, T> converter, Class<? extends Annotation> qualifier) {
registerBinding(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier), converter);
} | java | public final <S, T> void registerBinding(Class<S> source, Class<T> target, Binding<S, T> converter, Class<? extends Annotation> qualifier) {
registerBinding(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier), converter);
} | [
"public",
"final",
"<",
"S",
",",
"T",
">",
"void",
"registerBinding",
"(",
"Class",
"<",
"S",
">",
"source",
",",
"Class",
"<",
"T",
">",
"target",
",",
"Binding",
"<",
"S",
",",
"T",
">",
"converter",
",",
"Class",
"<",
"?",
"extends",
"Annotatio... | Register a Binding with the given source and target class.
A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
The source class is considered the owning class of the binding. The source can be marshalled
into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
@param source The source (owning) class
@param target The target (foreign) class
@param converter The binding to be registered
@param qualifier The qualifier for which the binding must be registered | [
"Register",
"a",
"Binding",
"with",
"the",
"given",
"source",
"and",
"target",
"class",
".",
"A",
"binding",
"unifies",
"a",
"marshaller",
"and",
"an",
"unmarshaller",
"and",
"both",
"must",
"be",
"available",
"to",
"resolve",
"a",
"binding",
"."
] | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L596-L598 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/admin/program/esjp/EFapsClassLoader.java | EFapsClassLoader.getOfflineInstance | public static synchronized EFapsClassLoader getOfflineInstance(final ClassLoader _parent)
{
if (EFapsClassLoader.CLASSLOADER == null) {
EFapsClassLoader.CLASSLOADER = new EFapsClassLoader(_parent, true);
}
return EFapsClassLoader.CLASSLOADER;
} | java | public static synchronized EFapsClassLoader getOfflineInstance(final ClassLoader _parent)
{
if (EFapsClassLoader.CLASSLOADER == null) {
EFapsClassLoader.CLASSLOADER = new EFapsClassLoader(_parent, true);
}
return EFapsClassLoader.CLASSLOADER;
} | [
"public",
"static",
"synchronized",
"EFapsClassLoader",
"getOfflineInstance",
"(",
"final",
"ClassLoader",
"_parent",
")",
"{",
"if",
"(",
"EFapsClassLoader",
".",
"CLASSLOADER",
"==",
"null",
")",
"{",
"EFapsClassLoader",
".",
"CLASSLOADER",
"=",
"new",
"EFapsClass... | Get the current EFapsClassLoader.
This static method is used to provide a way to use the same classloader
in different threads, due to the reason that using different classloader
instances might bring the problem of "instanceof" return unexpected results.
@param _parent parent classloader
@return the current EFapsClassLoader | [
"Get",
"the",
"current",
"EFapsClassLoader",
".",
"This",
"static",
"method",
"is",
"used",
"to",
"provide",
"a",
"way",
"to",
"use",
"the",
"same",
"classloader",
"in",
"different",
"threads",
"due",
"to",
"the",
"reason",
"that",
"using",
"different",
"cla... | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/program/esjp/EFapsClassLoader.java#L246-L252 |
app55/app55-java | src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java | BeanContextServicesSupport.revokeService | public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow)
{
if (serviceClass == null || serviceProvider == null)
{
throw new NullPointerException();
}
synchronized (globalHierarchyLock)
{
synchronized (services)
{
BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services.get(serviceClass);
if (bcssProvider == null)
{ // non-exist service
return;
}
if (bcssProvider.getServiceProvider() != serviceProvider)
{
throw new IllegalArgumentException(Messages.getString("beans.66"));
}
services.remove(serviceClass);
if (serviceProvider instanceof Serializable)
{
serializable--;
}
}
}
// notify listeners
fireServiceRevoked(serviceClass, revokeCurrentServicesNow);
// notify service users
notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow);
} | java | public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow)
{
if (serviceClass == null || serviceProvider == null)
{
throw new NullPointerException();
}
synchronized (globalHierarchyLock)
{
synchronized (services)
{
BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services.get(serviceClass);
if (bcssProvider == null)
{ // non-exist service
return;
}
if (bcssProvider.getServiceProvider() != serviceProvider)
{
throw new IllegalArgumentException(Messages.getString("beans.66"));
}
services.remove(serviceClass);
if (serviceProvider instanceof Serializable)
{
serializable--;
}
}
}
// notify listeners
fireServiceRevoked(serviceClass, revokeCurrentServicesNow);
// notify service users
notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow);
} | [
"public",
"void",
"revokeService",
"(",
"Class",
"serviceClass",
",",
"BeanContextServiceProvider",
"serviceProvider",
",",
"boolean",
"revokeCurrentServicesNow",
")",
"{",
"if",
"(",
"serviceClass",
"==",
"null",
"||",
"serviceProvider",
"==",
"null",
")",
"{",
"th... | Revokes a service in this bean context.
<p>
The given service provider is unregistered and a <code>BeanContextServiceRevokedEvent</code> is fired. All registered service listeners and current
service users get notified.
</p>
@param serviceClass
the service class
@param serviceProvider
the service provider
@param revokeCurrentServicesNow
true if service should be terminated immediantly
@see com.googlecode.openbeans.beancontext.BeanContextServices#revokeService(java.lang.Class,
com.googlecode.openbeans.beancontext.BeanContextServiceProvider, boolean) | [
"Revokes",
"a",
"service",
"in",
"this",
"bean",
"context",
".",
"<p",
">",
"The",
"given",
"service",
"provider",
"is",
"unregistered",
"and",
"a",
"<code",
">",
"BeanContextServiceRevokedEvent<",
"/",
"code",
">",
"is",
"fired",
".",
"All",
"registered",
"... | train | https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java#L916-L951 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.primitiveArrayGet | protected static List primitiveArrayGet(Object self, Range range) {
List answer = new ArrayList();
for (Object next : range) {
int idx = DefaultTypeTransformation.intUnbox(next);
answer.add(primitiveArrayGet(self, idx));
}
return answer;
} | java | protected static List primitiveArrayGet(Object self, Range range) {
List answer = new ArrayList();
for (Object next : range) {
int idx = DefaultTypeTransformation.intUnbox(next);
answer.add(primitiveArrayGet(self, idx));
}
return answer;
} | [
"protected",
"static",
"List",
"primitiveArrayGet",
"(",
"Object",
"self",
",",
"Range",
"range",
")",
"{",
"List",
"answer",
"=",
"new",
"ArrayList",
"(",
")",
";",
"for",
"(",
"Object",
"next",
":",
"range",
")",
"{",
"int",
"idx",
"=",
"DefaultTypeTra... | Implements the getAt(Range) method for primitive type arrays.
@param self an array object
@param range the range of indices of interest
@return the returned values from the array corresponding to the range
@since 1.5.0 | [
"Implements",
"the",
"getAt",
"(",
"Range",
")",
"method",
"for",
"primitive",
"type",
"arrays",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L14556-L14563 |
JodaOrg/joda-time | src/main/java/org/joda/time/chrono/BasicChronology.java | BasicChronology.getYearMonthDayMillis | long getYearMonthDayMillis(int year, int month, int dayOfMonth) {
long millis = getYearMillis(year);
millis += getTotalMillisByYearMonth(year, month);
return millis + (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY;
} | java | long getYearMonthDayMillis(int year, int month, int dayOfMonth) {
long millis = getYearMillis(year);
millis += getTotalMillisByYearMonth(year, month);
return millis + (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY;
} | [
"long",
"getYearMonthDayMillis",
"(",
"int",
"year",
",",
"int",
"month",
",",
"int",
"dayOfMonth",
")",
"{",
"long",
"millis",
"=",
"getYearMillis",
"(",
"year",
")",
";",
"millis",
"+=",
"getTotalMillisByYearMonth",
"(",
"year",
",",
"month",
")",
";",
"... | Get the milliseconds for a particular date.
@param year The year to use.
@param month The month to use
@param dayOfMonth The day of the month to use
@return millis from 1970-01-01T00:00:00Z | [
"Get",
"the",
"milliseconds",
"for",
"a",
"particular",
"date",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/chrono/BasicChronology.java#L411-L415 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.logException | protected void logException(CharSequence msg, Exception e) {
System.err.println(msg + ":" + e.getMessage());
e.printStackTrace();
} | java | protected void logException(CharSequence msg, Exception e) {
System.err.println(msg + ":" + e.getMessage());
e.printStackTrace();
} | [
"protected",
"void",
"logException",
"(",
"CharSequence",
"msg",
",",
"Exception",
"e",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"msg",
"+",
"\":\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
... | Logs an exception with an introductory message in addition to the
exception's getMessage().
@param msg message
@param e exception
@see Exception#getMessage | [
"Logs",
"an",
"exception",
"with",
"an",
"introductory",
"message",
"in",
"addition",
"to",
"the",
"exception",
"s",
"getMessage",
"()",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1124-L1127 |
segmentio/analytics-android | analytics/src/main/java/com/segment/analytics/ValueMap.java | ValueMap.getInt | public int getInt(String key, int defaultValue) {
Object value = get(key);
if (value instanceof Integer) {
return (int) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
try {
return Integer.valueOf((String) value);
} catch (NumberFormatException ignored) {
}
}
return defaultValue;
} | java | public int getInt(String key, int defaultValue) {
Object value = get(key);
if (value instanceof Integer) {
return (int) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
try {
return Integer.valueOf((String) value);
} catch (NumberFormatException ignored) {
}
}
return defaultValue;
} | [
"public",
"int",
"getInt",
"(",
"String",
"key",
",",
"int",
"defaultValue",
")",
"{",
"Object",
"value",
"=",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"instanceof",
"Integer",
")",
"{",
"return",
"(",
"int",
")",
"value",
";",
"}",
"if",
"... | Returns the value mapped by {@code key} if it exists and is a integer or can be coerced to a
integer. Returns {@code defaultValue} otherwise. | [
"Returns",
"the",
"value",
"mapped",
"by",
"{"
] | train | https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/ValueMap.java#L175-L189 |
junit-team/junit4 | src/main/java/org/junit/Assert.java | Assert.assertNull | public static void assertNull(String message, Object object) {
if (object == null) {
return;
}
failNotNull(message, object);
} | java | public static void assertNull(String message, Object object) {
if (object == null) {
return;
}
failNotNull(message, object);
} | [
"public",
"static",
"void",
"assertNull",
"(",
"String",
"message",
",",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
";",
"}",
"failNotNull",
"(",
"message",
",",
"object",
")",
";",
"}"
] | Asserts that an object is null. If it is not, an {@link AssertionError}
is thrown with the given message.
@param message the identifying message for the {@link AssertionError} (<code>null</code>
okay)
@param object Object to check or <code>null</code> | [
"Asserts",
"that",
"an",
"object",
"is",
"null",
".",
"If",
"it",
"is",
"not",
"an",
"{",
"@link",
"AssertionError",
"}",
"is",
"thrown",
"with",
"the",
"given",
"message",
"."
] | train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/Assert.java#L734-L739 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java | CmsContainerpageHandler.createMenuEntryForElementView | private CmsContextMenuEntry createMenuEntryForElementView(
final CmsElementViewInfo elementView,
boolean isActive,
I_CmsContextMenuHandler handler) {
CmsContextMenuEntry menuEntry = new CmsContextMenuEntry(handler, null, new I_CmsContextMenuCommand() {
public void execute(
CmsUUID innerStructureId,
I_CmsContextMenuHandler innerHandler,
CmsContextMenuEntryBean bean) {
setElementView(elementView, null);
}
public A_CmsContextMenuItem getItemWidget(
CmsUUID innerStructureId,
I_CmsContextMenuHandler innerHandler,
CmsContextMenuEntryBean bean) {
return null;
}
public boolean hasItemWidget() {
return false;
}
});
CmsContextMenuEntryBean bean = new CmsContextMenuEntryBean();
bean.setLabel(elementView.getTitle());
I_CmsInputCss inputCss = I_CmsInputLayoutBundle.INSTANCE.inputCss();
bean.setIconClass(isActive ? inputCss.checkBoxImageChecked() : "");
bean.setActive(!isActive);
bean.setVisible(true);
menuEntry.setBean(bean);
return menuEntry;
} | java | private CmsContextMenuEntry createMenuEntryForElementView(
final CmsElementViewInfo elementView,
boolean isActive,
I_CmsContextMenuHandler handler) {
CmsContextMenuEntry menuEntry = new CmsContextMenuEntry(handler, null, new I_CmsContextMenuCommand() {
public void execute(
CmsUUID innerStructureId,
I_CmsContextMenuHandler innerHandler,
CmsContextMenuEntryBean bean) {
setElementView(elementView, null);
}
public A_CmsContextMenuItem getItemWidget(
CmsUUID innerStructureId,
I_CmsContextMenuHandler innerHandler,
CmsContextMenuEntryBean bean) {
return null;
}
public boolean hasItemWidget() {
return false;
}
});
CmsContextMenuEntryBean bean = new CmsContextMenuEntryBean();
bean.setLabel(elementView.getTitle());
I_CmsInputCss inputCss = I_CmsInputLayoutBundle.INSTANCE.inputCss();
bean.setIconClass(isActive ? inputCss.checkBoxImageChecked() : "");
bean.setActive(!isActive);
bean.setVisible(true);
menuEntry.setBean(bean);
return menuEntry;
} | [
"private",
"CmsContextMenuEntry",
"createMenuEntryForElementView",
"(",
"final",
"CmsElementViewInfo",
"elementView",
",",
"boolean",
"isActive",
",",
"I_CmsContextMenuHandler",
"handler",
")",
"{",
"CmsContextMenuEntry",
"menuEntry",
"=",
"new",
"CmsContextMenuEntry",
"(",
... | Creates the menu entry for a single element view.<p>
@param elementView the element view
@param isActive if the group is the currently active group
@param handler the menu handler
@return the menu entry | [
"Creates",
"the",
"menu",
"entry",
"for",
"a",
"single",
"element",
"view",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L1598-L1636 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java | Director.getFeatureLicense | public Set<InstallLicense> getFeatureLicense(String esaLocation, Locale locale) throws InstallException {
Set<InstallLicense> licenses = new HashSet<InstallLicense>();
ArrayList<InstallAsset> installAssets = new ArrayList<InstallAsset>();
getResolveDirector().resolve(esaLocation, "", product.getInstalledFeatures(), installAssets, 10, 40);
if (installAssets.isEmpty()) {
return licenses;
}
Map<String, InstallLicenseImpl> licenseIds = new HashMap<String, InstallLicenseImpl>();
for (InstallAsset installAsset : installAssets) {
if (installAsset.isFeature()) {
ESAAsset esa = (ESAAsset) installAsset;
LicenseProvider lp = esa.getLicenseProvider(locale);
String licenseId = esa.getLicenseId();
if (licenseId != null && !licenseId.isEmpty()) {
InstallLicenseImpl ili = licenseIds.get(licenseId);
if (ili == null) {
ili = new InstallLicenseImpl(licenseId, null, lp);
licenseIds.put(licenseId, ili);
}
ili.addFeature(esa.getProvideFeature());
}
}
}
licenses.addAll(licenseIds.values());
return licenses;
} | java | public Set<InstallLicense> getFeatureLicense(String esaLocation, Locale locale) throws InstallException {
Set<InstallLicense> licenses = new HashSet<InstallLicense>();
ArrayList<InstallAsset> installAssets = new ArrayList<InstallAsset>();
getResolveDirector().resolve(esaLocation, "", product.getInstalledFeatures(), installAssets, 10, 40);
if (installAssets.isEmpty()) {
return licenses;
}
Map<String, InstallLicenseImpl> licenseIds = new HashMap<String, InstallLicenseImpl>();
for (InstallAsset installAsset : installAssets) {
if (installAsset.isFeature()) {
ESAAsset esa = (ESAAsset) installAsset;
LicenseProvider lp = esa.getLicenseProvider(locale);
String licenseId = esa.getLicenseId();
if (licenseId != null && !licenseId.isEmpty()) {
InstallLicenseImpl ili = licenseIds.get(licenseId);
if (ili == null) {
ili = new InstallLicenseImpl(licenseId, null, lp);
licenseIds.put(licenseId, ili);
}
ili.addFeature(esa.getProvideFeature());
}
}
}
licenses.addAll(licenseIds.values());
return licenses;
} | [
"public",
"Set",
"<",
"InstallLicense",
">",
"getFeatureLicense",
"(",
"String",
"esaLocation",
",",
"Locale",
"locale",
")",
"throws",
"InstallException",
"{",
"Set",
"<",
"InstallLicense",
">",
"licenses",
"=",
"new",
"HashSet",
"<",
"InstallLicense",
">",
"("... | Gets the licenses for the specified esa location.
@param esaLocation location of esa
@param locale Locale for the license
@return A set of InstallLicenses for the features at the esa location
@throws InstallException | [
"Gets",
"the",
"licenses",
"for",
"the",
"specified",
"esa",
"location",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java#L601-L627 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/GlobalAddressClient.java | GlobalAddressClient.insertGlobalAddress | @BetaApi
public final Operation insertGlobalAddress(String project, Address addressResource) {
InsertGlobalAddressHttpRequest request =
InsertGlobalAddressHttpRequest.newBuilder()
.setProject(project)
.setAddressResource(addressResource)
.build();
return insertGlobalAddress(request);
} | java | @BetaApi
public final Operation insertGlobalAddress(String project, Address addressResource) {
InsertGlobalAddressHttpRequest request =
InsertGlobalAddressHttpRequest.newBuilder()
.setProject(project)
.setAddressResource(addressResource)
.build();
return insertGlobalAddress(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertGlobalAddress",
"(",
"String",
"project",
",",
"Address",
"addressResource",
")",
"{",
"InsertGlobalAddressHttpRequest",
"request",
"=",
"InsertGlobalAddressHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setProjec... | Creates an address resource in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (GlobalAddressClient globalAddressClient = GlobalAddressClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
Address addressResource = Address.newBuilder().build();
Operation response = globalAddressClient.insertGlobalAddress(project.toString(), addressResource);
}
</code></pre>
@param project Project ID for this request.
@param addressResource A reserved address resource. (== resource_for beta.addresses ==) (==
resource_for v1.addresses ==) (== resource_for beta.globalAddresses ==) (== resource_for
v1.globalAddresses ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"an",
"address",
"resource",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/GlobalAddressClient.java#L406-L415 |
apache/incubator-druid | indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskQueue.java | TaskQueue.shutdown | public void shutdown(final String taskId, String reasonFormat, Object... args)
{
giant.lock();
try {
Preconditions.checkNotNull(taskId, "taskId");
for (final Task task : tasks) {
if (task.getId().equals(taskId)) {
notifyStatus(task, TaskStatus.failure(taskId), reasonFormat, args);
break;
}
}
}
finally {
giant.unlock();
}
} | java | public void shutdown(final String taskId, String reasonFormat, Object... args)
{
giant.lock();
try {
Preconditions.checkNotNull(taskId, "taskId");
for (final Task task : tasks) {
if (task.getId().equals(taskId)) {
notifyStatus(task, TaskStatus.failure(taskId), reasonFormat, args);
break;
}
}
}
finally {
giant.unlock();
}
} | [
"public",
"void",
"shutdown",
"(",
"final",
"String",
"taskId",
",",
"String",
"reasonFormat",
",",
"Object",
"...",
"args",
")",
"{",
"giant",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"taskId",
",",
"\"taskId\"",
... | Shuts down a task if it has not yet finished.
@param taskId task to kill | [
"Shuts",
"down",
"a",
"task",
"if",
"it",
"has",
"not",
"yet",
"finished",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskQueue.java#L383-L399 |
sarl/sarl | sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java | SpaceRepository.ensureLocalSpaceDefinition | @SuppressWarnings({ "unchecked", "rawtypes" })
protected void ensureLocalSpaceDefinition(SpaceID id, Object[] initializationParameters) {
synchronized (getSpaceRepositoryMutex()) {
if (!this.spaces.containsKey(id)) {
createSpaceInstance((Class) id.getSpaceSpecification(), id, false, initializationParameters);
}
}
} | java | @SuppressWarnings({ "unchecked", "rawtypes" })
protected void ensureLocalSpaceDefinition(SpaceID id, Object[] initializationParameters) {
synchronized (getSpaceRepositoryMutex()) {
if (!this.spaces.containsKey(id)) {
createSpaceInstance((Class) id.getSpaceSpecification(), id, false, initializationParameters);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"protected",
"void",
"ensureLocalSpaceDefinition",
"(",
"SpaceID",
"id",
",",
"Object",
"[",
"]",
"initializationParameters",
")",
"{",
"synchronized",
"(",
"getSpaceRepositoryMutex",
... | Add the existing, but not yet known, spaces into this repository.
@param id identifier of the space
@param initializationParameters parameters for initialization. | [
"Add",
"the",
"existing",
"but",
"not",
"yet",
"known",
"spaces",
"into",
"this",
"repository",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java#L209-L216 |
vdurmont/emoji-java | src/main/java/com/vdurmont/emoji/EmojiParser.java | EmojiParser.replaceAllEmojis | public static String replaceAllEmojis(String str, final String replacementString) {
EmojiParser.EmojiTransformer emojiTransformer = new EmojiParser.EmojiTransformer() {
public String transform(EmojiParser.UnicodeCandidate unicodeCandidate) {
return replacementString;
}
};
return parseFromUnicode(str, emojiTransformer);
} | java | public static String replaceAllEmojis(String str, final String replacementString) {
EmojiParser.EmojiTransformer emojiTransformer = new EmojiParser.EmojiTransformer() {
public String transform(EmojiParser.UnicodeCandidate unicodeCandidate) {
return replacementString;
}
};
return parseFromUnicode(str, emojiTransformer);
} | [
"public",
"static",
"String",
"replaceAllEmojis",
"(",
"String",
"str",
",",
"final",
"String",
"replacementString",
")",
"{",
"EmojiParser",
".",
"EmojiTransformer",
"emojiTransformer",
"=",
"new",
"EmojiParser",
".",
"EmojiTransformer",
"(",
")",
"{",
"public",
... | Replace all emojis with character
@param str the string to process
@param replacementString replacement the string that will replace all the emojis
@return the string with replaced character | [
"Replace",
"all",
"emojis",
"with",
"character"
] | train | https://github.com/vdurmont/emoji-java/blob/8cf5fbe0d7c1020b926791f2b342a263ed07bb0f/src/main/java/com/vdurmont/emoji/EmojiParser.java#L94-L102 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.serviceName_monitoringNotifications_POST | public OvhMonitoringNotification serviceName_monitoringNotifications_POST(String serviceName, Boolean allowIncident, Long downThreshold, String email, OvhFrequencyEnum frequency, String phone, String smsAccount, OvhTypeEnum type) throws IOException {
String qPath = "/xdsl/{serviceName}/monitoringNotifications";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "allowIncident", allowIncident);
addBody(o, "downThreshold", downThreshold);
addBody(o, "email", email);
addBody(o, "frequency", frequency);
addBody(o, "phone", phone);
addBody(o, "smsAccount", smsAccount);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMonitoringNotification.class);
} | java | public OvhMonitoringNotification serviceName_monitoringNotifications_POST(String serviceName, Boolean allowIncident, Long downThreshold, String email, OvhFrequencyEnum frequency, String phone, String smsAccount, OvhTypeEnum type) throws IOException {
String qPath = "/xdsl/{serviceName}/monitoringNotifications";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "allowIncident", allowIncident);
addBody(o, "downThreshold", downThreshold);
addBody(o, "email", email);
addBody(o, "frequency", frequency);
addBody(o, "phone", phone);
addBody(o, "smsAccount", smsAccount);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMonitoringNotification.class);
} | [
"public",
"OvhMonitoringNotification",
"serviceName_monitoringNotifications_POST",
"(",
"String",
"serviceName",
",",
"Boolean",
"allowIncident",
",",
"Long",
"downThreshold",
",",
"String",
"email",
",",
"OvhFrequencyEnum",
"frequency",
",",
"String",
"phone",
",",
"Stri... | Add a notification
REST: POST /xdsl/{serviceName}/monitoringNotifications
@param frequency [required]
@param downThreshold [required] [default=120] The number of seconds the access has to be down to trigger the alert
@param phone [required] The phone number, if type is sms
@param type [required]
@param smsAccount [required] The SMS account which will be debited for each sent SMS, if the type is sms
@param allowIncident [required] [default=true] Whether or not to allow notifications concerning generic incidents
@param email [required] The e-mail address, if type is mail
@param serviceName [required] The internal name of your XDSL offer | [
"Add",
"a",
"notification"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L1445-L1458 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java | RelativeDateTimeFormatter.getInstance | public static RelativeDateTimeFormatter getInstance(ULocale locale) {
return getInstance(locale, null, Style.LONG, DisplayContext.CAPITALIZATION_NONE);
} | java | public static RelativeDateTimeFormatter getInstance(ULocale locale) {
return getInstance(locale, null, Style.LONG, DisplayContext.CAPITALIZATION_NONE);
} | [
"public",
"static",
"RelativeDateTimeFormatter",
"getInstance",
"(",
"ULocale",
"locale",
")",
"{",
"return",
"getInstance",
"(",
"locale",
",",
"null",
",",
"Style",
".",
"LONG",
",",
"DisplayContext",
".",
"CAPITALIZATION_NONE",
")",
";",
"}"
] | Returns a RelativeDateTimeFormatter for a particular locale.
@param locale the locale.
@return An instance of RelativeDateTimeFormatter. | [
"Returns",
"a",
"RelativeDateTimeFormatter",
"for",
"a",
"particular",
"locale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java#L370-L372 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.userInGroup | public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
boolean result = false;
try {
result = m_driverManager.userInGroup(
dbc,
CmsOrganizationalUnit.removeLeadingSeparator(username),
CmsOrganizationalUnit.removeLeadingSeparator(groupname),
false);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_USER_IN_GROUP_2, username, groupname), e);
} finally {
dbc.clear();
}
return result;
} | java | public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
boolean result = false;
try {
result = m_driverManager.userInGroup(
dbc,
CmsOrganizationalUnit.removeLeadingSeparator(username),
CmsOrganizationalUnit.removeLeadingSeparator(groupname),
false);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_USER_IN_GROUP_2, username, groupname), e);
} finally {
dbc.clear();
}
return result;
} | [
"public",
"boolean",
"userInGroup",
"(",
"CmsRequestContext",
"context",
",",
"String",
"username",
",",
"String",
"groupname",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"bo... | Tests if a user is member of the given group.<p>
@param context the current request context
@param username the name of the user to check
@param groupname the name of the group to check
@return <code>true</code>, if the user is in the group; or <code>false</code> otherwise
@throws CmsException if operation was not successful | [
"Tests",
"if",
"a",
"user",
"is",
"member",
"of",
"the",
"given",
"group",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6517-L6533 |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/LevelDbOutputWriter.java | LevelDbOutputWriter.createRecord | private static Record createRecord(ByteBuffer data, int bytesToBlockEnd, Record lastRecord) {
int bytesToDataEnd = data.remaining();
RecordType type = RecordType.UNKNOWN;
int bytes = -1;
if ((lastRecord.getType() == RecordType.NONE)
&& ((bytesToDataEnd + LevelDbConstants.HEADER_LENGTH) <= bytesToBlockEnd)) {
// Can write entire record in current block
type = RecordType.FULL;
bytes = bytesToDataEnd;
} else if (lastRecord.getType() == RecordType.NONE) {
// On first write but can't fit in current block
type = RecordType.FIRST;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
} else if (bytesToDataEnd + LevelDbConstants.HEADER_LENGTH <= bytesToBlockEnd) {
// At end of record
type = RecordType.LAST;
bytes = bytesToDataEnd;
} else {
// In middle somewhere
type = RecordType.MIDDLE;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
}
return new Record(type, bytes);
} | java | private static Record createRecord(ByteBuffer data, int bytesToBlockEnd, Record lastRecord) {
int bytesToDataEnd = data.remaining();
RecordType type = RecordType.UNKNOWN;
int bytes = -1;
if ((lastRecord.getType() == RecordType.NONE)
&& ((bytesToDataEnd + LevelDbConstants.HEADER_LENGTH) <= bytesToBlockEnd)) {
// Can write entire record in current block
type = RecordType.FULL;
bytes = bytesToDataEnd;
} else if (lastRecord.getType() == RecordType.NONE) {
// On first write but can't fit in current block
type = RecordType.FIRST;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
} else if (bytesToDataEnd + LevelDbConstants.HEADER_LENGTH <= bytesToBlockEnd) {
// At end of record
type = RecordType.LAST;
bytes = bytesToDataEnd;
} else {
// In middle somewhere
type = RecordType.MIDDLE;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
}
return new Record(type, bytes);
} | [
"private",
"static",
"Record",
"createRecord",
"(",
"ByteBuffer",
"data",
",",
"int",
"bytesToBlockEnd",
",",
"Record",
"lastRecord",
")",
"{",
"int",
"bytesToDataEnd",
"=",
"data",
".",
"remaining",
"(",
")",
";",
"RecordType",
"type",
"=",
"RecordType",
".",... | Fills a {@link Record} object with data about the physical record to write.
@param data the users data.
@param bytesToBlockEnd remaining bytes in the current block.
@param lastRecord a {@link Record} representing the last physical record written.
@return the {@link Record} with new write data. | [
"Fills",
"a",
"{",
"@link",
"Record",
"}",
"object",
"with",
"data",
"about",
"the",
"physical",
"record",
"to",
"write",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/LevelDbOutputWriter.java#L150-L173 |
graphql-java/graphql-java | src/main/java/graphql/schema/diff/SchemaDiff.java | SchemaDiff.diffSchema | @SuppressWarnings("unchecked")
public int diffSchema(DiffSet diffSet, DifferenceReporter reporter) {
CountingReporter countingReporter = new CountingReporter(reporter);
diffSchemaImpl(diffSet, countingReporter);
return countingReporter.breakingCount;
} | java | @SuppressWarnings("unchecked")
public int diffSchema(DiffSet diffSet, DifferenceReporter reporter) {
CountingReporter countingReporter = new CountingReporter(reporter);
diffSchemaImpl(diffSet, countingReporter);
return countingReporter.breakingCount;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"int",
"diffSchema",
"(",
"DiffSet",
"diffSet",
",",
"DifferenceReporter",
"reporter",
")",
"{",
"CountingReporter",
"countingReporter",
"=",
"new",
"CountingReporter",
"(",
"reporter",
")",
";",
"diffSch... | This will perform a difference on the two schemas. The reporter callback
interface will be called when differences are encountered.
@param diffSet the two schemas to compare for difference
@param reporter the place to report difference events to
@return the number of API breaking changes | [
"This",
"will",
"perform",
"a",
"difference",
"on",
"the",
"two",
"schemas",
".",
"The",
"reporter",
"callback",
"interface",
"will",
"be",
"called",
"when",
"differences",
"are",
"encountered",
"."
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/diff/SchemaDiff.java#L120-L126 |
sarl/sarl | main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/AbstractExternalHighlightingFragment2.java | AbstractExternalHighlightingFragment2.generateReadme | protected void generateReadme(String basename) {
final Object content = getReadmeFileContent(basename);
if (content != null) {
final String textualContent = content.toString();
if (!Strings.isEmpty(textualContent)) {
final byte[] bytes = textualContent.getBytes();
for (final String output : getOutputs()) {
final File directory = new File(output).getAbsoluteFile();
try {
directory.mkdirs();
final File outputFile = new File(directory, README_BASENAME);
Files.write(Paths.get(outputFile.getAbsolutePath()), bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
} | java | protected void generateReadme(String basename) {
final Object content = getReadmeFileContent(basename);
if (content != null) {
final String textualContent = content.toString();
if (!Strings.isEmpty(textualContent)) {
final byte[] bytes = textualContent.getBytes();
for (final String output : getOutputs()) {
final File directory = new File(output).getAbsoluteFile();
try {
directory.mkdirs();
final File outputFile = new File(directory, README_BASENAME);
Files.write(Paths.get(outputFile.getAbsolutePath()), bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
} | [
"protected",
"void",
"generateReadme",
"(",
"String",
"basename",
")",
"{",
"final",
"Object",
"content",
"=",
"getReadmeFileContent",
"(",
"basename",
")",
";",
"if",
"(",
"content",
"!=",
"null",
")",
"{",
"final",
"String",
"textualContent",
"=",
"content",... | Generate the README file.
@param basename the basename of the generated file.
@since 0.6 | [
"Generate",
"the",
"README",
"file",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/AbstractExternalHighlightingFragment2.java#L584-L602 |
wcm-io/wcm-io-wcm | commons/src/main/java/io/wcm/wcm/commons/caching/CacheHeader.java | CacheHeader.setExpiresHours | public static void setExpiresHours(@NotNull HttpServletResponse response, int hours) {
Date expiresDate = DateUtils.addHours(new Date(), hours);
setExpires(response, expiresDate);
} | java | public static void setExpiresHours(@NotNull HttpServletResponse response, int hours) {
Date expiresDate = DateUtils.addHours(new Date(), hours);
setExpires(response, expiresDate);
} | [
"public",
"static",
"void",
"setExpiresHours",
"(",
"@",
"NotNull",
"HttpServletResponse",
"response",
",",
"int",
"hours",
")",
"{",
"Date",
"expiresDate",
"=",
"DateUtils",
".",
"addHours",
"(",
"new",
"Date",
"(",
")",
",",
"hours",
")",
";",
"setExpires"... | Set expires header to given amount of hours in the future.
@param response Response
@param hours Hours to expire | [
"Set",
"expires",
"header",
"to",
"given",
"amount",
"of",
"hours",
"in",
"the",
"future",
"."
] | train | https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/caching/CacheHeader.java#L242-L245 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getAllEmblemInfo | public void getAllEmblemInfo(Emblem.Type type, int[] ids, Callback<List<Emblem>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
if (ids.length > 200)
throw new GuildWars2Exception(ErrorCode.ID, "id list too long; this endpoint is limited to 200 ids at once");
gw2API.getAllEmblemInfo(type.name(), processIds(ids)).enqueue(callback);
} | java | public void getAllEmblemInfo(Emblem.Type type, int[] ids, Callback<List<Emblem>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
if (ids.length > 200)
throw new GuildWars2Exception(ErrorCode.ID, "id list too long; this endpoint is limited to 200 ids at once");
gw2API.getAllEmblemInfo(type.name(), processIds(ids)).enqueue(callback);
} | [
"public",
"void",
"getAllEmblemInfo",
"(",
"Emblem",
".",
"Type",
"type",
",",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"Emblem",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
... | For more info on emblem API go <a href="https://wiki.guildwars2.com/wiki/API:2/emblem">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param type foregrounds/backgrounds
@param ids list of emblem id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list | exceeds ID list limit (ie, ids.length>200)
@throws NullPointerException if given {@link Callback} is empty
@see Emblem Emblem info | [
"For",
"more",
"info",
"on",
"emblem",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"emblem",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"t... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1330-L1335 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/FileUtils.java | FileUtils.toXML | public static String toXML(final String aFilePath, final boolean aDeepConversion) throws FileNotFoundException,
TransformerException {
return toXML(aFilePath, WILDCARD, aDeepConversion);
} | java | public static String toXML(final String aFilePath, final boolean aDeepConversion) throws FileNotFoundException,
TransformerException {
return toXML(aFilePath, WILDCARD, aDeepConversion);
} | [
"public",
"static",
"String",
"toXML",
"(",
"final",
"String",
"aFilePath",
",",
"final",
"boolean",
"aDeepConversion",
")",
"throws",
"FileNotFoundException",
",",
"TransformerException",
"{",
"return",
"toXML",
"(",
"aFilePath",
",",
"WILDCARD",
",",
"aDeepConvers... | Creates a string of XML that describes the supplied file or directory (and, optionally, all its
subdirectories). Includes absolute path, last modified time, read/write permissions, etc.
@param aFilePath The file or directory to be returned as XML
@param aDeepConversion Whether the subdirectories are included
@return A string of XML describing the supplied file system path's structure
@throws FileNotFoundException If the supplied file or directory can not be found
@throws TransformerException If there is trouble with the XSL transformation | [
"Creates",
"a",
"string",
"of",
"XML",
"that",
"describes",
"the",
"supplied",
"file",
"or",
"directory",
"(",
"and",
"optionally",
"all",
"its",
"subdirectories",
")",
".",
"Includes",
"absolute",
"path",
"last",
"modified",
"time",
"read",
"/",
"write",
"p... | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L152-L155 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/SessionDriver.java | SessionDriver.initializeServer | private ServerSocket initializeServer(CoronaConf conf) throws IOException {
// Choose any free port.
ServerSocket sessionServerSocket =
new ServerSocket(0, 0, getLocalAddress());
TServerSocket tServerSocket = new TServerSocket(sessionServerSocket,
conf.getCMSoTimeout());
TFactoryBasedThreadPoolServer.Args args =
new TFactoryBasedThreadPoolServer.Args(tServerSocket);
args.processor(new SessionDriverServiceProcessor(incoming));
args.transportFactory(new TTransportFactory());
args.protocolFactory(new TBinaryProtocol.Factory(true, true));
args.stopTimeoutVal = 0;
server = new TFactoryBasedThreadPoolServer(
args, new TFactoryBasedThreadPoolServer.DaemonThreadFactory());
return sessionServerSocket;
} | java | private ServerSocket initializeServer(CoronaConf conf) throws IOException {
// Choose any free port.
ServerSocket sessionServerSocket =
new ServerSocket(0, 0, getLocalAddress());
TServerSocket tServerSocket = new TServerSocket(sessionServerSocket,
conf.getCMSoTimeout());
TFactoryBasedThreadPoolServer.Args args =
new TFactoryBasedThreadPoolServer.Args(tServerSocket);
args.processor(new SessionDriverServiceProcessor(incoming));
args.transportFactory(new TTransportFactory());
args.protocolFactory(new TBinaryProtocol.Factory(true, true));
args.stopTimeoutVal = 0;
server = new TFactoryBasedThreadPoolServer(
args, new TFactoryBasedThreadPoolServer.DaemonThreadFactory());
return sessionServerSocket;
} | [
"private",
"ServerSocket",
"initializeServer",
"(",
"CoronaConf",
"conf",
")",
"throws",
"IOException",
"{",
"// Choose any free port.",
"ServerSocket",
"sessionServerSocket",
"=",
"new",
"ServerSocket",
"(",
"0",
",",
"0",
",",
"getLocalAddress",
"(",
")",
")",
";"... | Start the SessionDriver callback server
@param conf the corona configuration for this session
@return the server socket of the callback server
@throws IOException | [
"Start",
"the",
"SessionDriver",
"callback",
"server"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/SessionDriver.java#L226-L242 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_catalog/FlowCatalog.java | FlowCatalog.put | public Map<String, AddSpecResponse> put(Spec spec, boolean triggerListener) {
Map<String, AddSpecResponse> responseMap = new HashMap<>();
try {
Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName()));
Preconditions.checkNotNull(spec);
long startTime = System.currentTimeMillis();
log.info(String.format("Adding FlowSpec with URI: %s and Config: %s", spec.getUri(),
((FlowSpec) spec).getConfigAsProperties()));
specStore.addSpec(spec);
metrics.updatePutSpecTime(startTime);
if (triggerListener) {
AddSpecResponse<CallbacksDispatcher.CallbackResults<SpecCatalogListener, AddSpecResponse>> response = this.listeners.onAddSpec(spec);
for (Map.Entry<SpecCatalogListener, CallbackResult<AddSpecResponse>> entry: response.getValue().getSuccesses().entrySet()) {
responseMap.put(entry.getKey().getName(), entry.getValue().getResult());
}
}
} catch (IOException e) {
throw new RuntimeException("Cannot add Spec to Spec store: " + spec, e);
}
return responseMap;
} | java | public Map<String, AddSpecResponse> put(Spec spec, boolean triggerListener) {
Map<String, AddSpecResponse> responseMap = new HashMap<>();
try {
Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName()));
Preconditions.checkNotNull(spec);
long startTime = System.currentTimeMillis();
log.info(String.format("Adding FlowSpec with URI: %s and Config: %s", spec.getUri(),
((FlowSpec) spec).getConfigAsProperties()));
specStore.addSpec(spec);
metrics.updatePutSpecTime(startTime);
if (triggerListener) {
AddSpecResponse<CallbacksDispatcher.CallbackResults<SpecCatalogListener, AddSpecResponse>> response = this.listeners.onAddSpec(spec);
for (Map.Entry<SpecCatalogListener, CallbackResult<AddSpecResponse>> entry: response.getValue().getSuccesses().entrySet()) {
responseMap.put(entry.getKey().getName(), entry.getValue().getResult());
}
}
} catch (IOException e) {
throw new RuntimeException("Cannot add Spec to Spec store: " + spec, e);
}
return responseMap;
} | [
"public",
"Map",
"<",
"String",
",",
"AddSpecResponse",
">",
"put",
"(",
"Spec",
"spec",
",",
"boolean",
"triggerListener",
")",
"{",
"Map",
"<",
"String",
",",
"AddSpecResponse",
">",
"responseMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"try",
"{"... | Persist {@link Spec} into {@link SpecStore} and notify {@link SpecCatalogListener} if triggerListener
is set to true.
@param spec The Spec to be added
@param triggerListener True if listeners should be notified.
@return | [
"Persist",
"{",
"@link",
"Spec",
"}",
"into",
"{",
"@link",
"SpecStore",
"}",
"and",
"notify",
"{",
"@link",
"SpecCatalogListener",
"}",
"if",
"triggerListener",
"is",
"set",
"to",
"true",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_catalog/FlowCatalog.java#L267-L288 |
cqframework/clinical_quality_language | Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/Cql2ElmVisitor.java | Cql2ElmVisitor.attemptDateRangeOptimization | private boolean attemptDateRangeOptimization(And and, Retrieve retrieve, String alias) {
if (retrieve.getDateProperty() != null || retrieve.getDateRange() != null) {
return false;
}
for (int i = 0; i < and.getOperand().size(); i++) {
Expression operand = and.getOperand().get(i);
if ((operand instanceof IncludedIn || operand instanceof In) && attemptDateRangeOptimization((BinaryExpression) operand, retrieve, alias)) {
// Replace optimized part in And with true -- to be optimized out later
and.getOperand().set(i, libraryBuilder.createLiteral(true));
return true;
} else if (operand instanceof And && attemptDateRangeOptimization((And) operand, retrieve, alias)) {
return true;
}
}
return false;
} | java | private boolean attemptDateRangeOptimization(And and, Retrieve retrieve, String alias) {
if (retrieve.getDateProperty() != null || retrieve.getDateRange() != null) {
return false;
}
for (int i = 0; i < and.getOperand().size(); i++) {
Expression operand = and.getOperand().get(i);
if ((operand instanceof IncludedIn || operand instanceof In) && attemptDateRangeOptimization((BinaryExpression) operand, retrieve, alias)) {
// Replace optimized part in And with true -- to be optimized out later
and.getOperand().set(i, libraryBuilder.createLiteral(true));
return true;
} else if (operand instanceof And && attemptDateRangeOptimization((And) operand, retrieve, alias)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"attemptDateRangeOptimization",
"(",
"And",
"and",
",",
"Retrieve",
"retrieve",
",",
"String",
"alias",
")",
"{",
"if",
"(",
"retrieve",
".",
"getDateProperty",
"(",
")",
"!=",
"null",
"||",
"retrieve",
".",
"getDateRange",
"(",
")",
"!... | Test an <code>And</code> expression and determine if it contains any operands (first-level or nested deeper)
than are <code>IncludedIn</code> expressions that can be refactored into a <code>Retrieve</code>. If so,
adjust the <code>Retrieve</code> accordingly and reset the corresponding operand to a literal
<code>true</code>. This <code>and</code> branch containing a <code>true</code> can be further consolidated
later.
@param and the <code>And</code> expression containing operands to potentially refactor into the
<code>Retrieve</code>
@param retrieve the <code>Retrieve</code> to add qualifying date ranges to (if applicable)
@param alias the alias of the <code>Retrieve</code> in the query.
@return <code>true</code> if the date range was set in the <code>Retrieve</code> and the <code>And</code>
operands (or sub-operands) were modified; <code>false</code> otherwise. | [
"Test",
"an",
"<code",
">",
"And<",
"/",
"code",
">",
"expression",
"and",
"determine",
"if",
"it",
"contains",
"any",
"operands",
"(",
"first",
"-",
"level",
"or",
"nested",
"deeper",
")",
"than",
"are",
"<code",
">",
"IncludedIn<",
"/",
"code",
">",
... | train | https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/Cql2ElmVisitor.java#L3089-L3106 |
scalecube/scalecube-services | services-api/src/main/java/io/scalecube/services/ServiceEndpoint.java | ServiceEndpoint.serviceReferences | public Collection<ServiceReference> serviceReferences() {
return serviceRegistrations.stream()
.flatMap(sr -> sr.methods().stream().map(sm -> new ServiceReference(sm, sr, this)))
.collect(Collectors.toList());
} | java | public Collection<ServiceReference> serviceReferences() {
return serviceRegistrations.stream()
.flatMap(sr -> sr.methods().stream().map(sm -> new ServiceReference(sm, sr, this)))
.collect(Collectors.toList());
} | [
"public",
"Collection",
"<",
"ServiceReference",
">",
"serviceReferences",
"(",
")",
"{",
"return",
"serviceRegistrations",
".",
"stream",
"(",
")",
".",
"flatMap",
"(",
"sr",
"->",
"sr",
".",
"methods",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"("... | Creates collection of service references from this service endpoint.
@return collection of {@link ServiceReference} | [
"Creates",
"collection",
"of",
"service",
"references",
"from",
"this",
"service",
"endpoint",
"."
] | train | https://github.com/scalecube/scalecube-services/blob/76c8de6019e5480a1436d12b37acf163f70eea47/services-api/src/main/java/io/scalecube/services/ServiceEndpoint.java#L75-L79 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java | BigDecimal.multiply | public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
if (mc.precision == 0)
return multiply(multiplicand);
int productScale = checkScale((long) scale + multiplicand.scale);
if (this.intCompact != INFLATED) {
if ((multiplicand.intCompact != INFLATED)) {
return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
} else {
return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
}
} else {
if ((multiplicand.intCompact != INFLATED)) {
return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
} else {
return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
}
}
} | java | public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
if (mc.precision == 0)
return multiply(multiplicand);
int productScale = checkScale((long) scale + multiplicand.scale);
if (this.intCompact != INFLATED) {
if ((multiplicand.intCompact != INFLATED)) {
return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
} else {
return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
}
} else {
if ((multiplicand.intCompact != INFLATED)) {
return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
} else {
return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
}
}
} | [
"public",
"BigDecimal",
"multiply",
"(",
"BigDecimal",
"multiplicand",
",",
"MathContext",
"mc",
")",
"{",
"if",
"(",
"mc",
".",
"precision",
"==",
"0",
")",
"return",
"multiply",
"(",
"multiplicand",
")",
";",
"int",
"productScale",
"=",
"checkScale",
"(",
... | Returns a {@code BigDecimal} whose value is <tt>(this ×
multiplicand)</tt>, with rounding according to the context settings.
@param multiplicand value to be multiplied by this {@code BigDecimal}.
@param mc the context to use.
@return {@code this * multiplicand}, rounded as necessary.
@throws ArithmeticException if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
@since 1.5 | [
"Returns",
"a",
"{",
"@code",
"BigDecimal",
"}",
"whose",
"value",
"is",
"<tt",
">",
"(",
"this",
"×",
";",
"multiplicand",
")",
"<",
"/",
"tt",
">",
"with",
"rounding",
"according",
"to",
"the",
"context",
"settings",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L1511-L1528 |
onelogin/onelogin-java-sdk | src/main/java/com/onelogin/sdk/conn/Client.java | Client.assignRoleToUser | public Boolean assignRoleToUser(long id, List<Long> roleIds) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
cleanError();
prepareToken();
OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(httpClient);
URIBuilder url = new URIBuilder(settings.getURL(Constants.ADD_ROLE_TO_USER_URL, Long.toString(id)));
OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString())
.buildHeaderMessage();
Map<String, String> headers = getAuthorizedHeader();
bearerRequest.setHeaders(headers);
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("role_id_array", roleIds);
String body = JSONUtils.buildJSON(params);
bearerRequest.setBody(body);
Boolean success = true;
OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.PUT, OneloginOAuthJSONResourceResponse.class);
if (oAuthResponse.getResponseCode() != 200) {
success = false;
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
errorAttribute = oAuthResponse.getErrorAttribute();
}
return success;
} | java | public Boolean assignRoleToUser(long id, List<Long> roleIds) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
cleanError();
prepareToken();
OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(httpClient);
URIBuilder url = new URIBuilder(settings.getURL(Constants.ADD_ROLE_TO_USER_URL, Long.toString(id)));
OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString())
.buildHeaderMessage();
Map<String, String> headers = getAuthorizedHeader();
bearerRequest.setHeaders(headers);
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("role_id_array", roleIds);
String body = JSONUtils.buildJSON(params);
bearerRequest.setBody(body);
Boolean success = true;
OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.PUT, OneloginOAuthJSONResourceResponse.class);
if (oAuthResponse.getResponseCode() != 200) {
success = false;
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
errorAttribute = oAuthResponse.getErrorAttribute();
}
return success;
} | [
"public",
"Boolean",
"assignRoleToUser",
"(",
"long",
"id",
",",
"List",
"<",
"Long",
">",
"roleIds",
")",
"throws",
"OAuthSystemException",
",",
"OAuthProblemException",
",",
"URISyntaxException",
"{",
"cleanError",
"(",
")",
";",
"prepareToken",
"(",
")",
";",... | Assigns Role to User
@param id
Id of the user to be modified
@param roleIds
Set to an array of one or more role IDs.
@return true if success
@throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection
@throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled
@throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/assign-role-to-user">Assign Role to User documentation</a> | [
"Assigns",
"Role",
"to",
"User"
] | train | https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L1075-L1105 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java | ContinuousDistributions.chisquareInverseCdf | public static double chisquareInverseCdf(double p, int df) {
final double CHI_EPSILON = 0.000001; /* Accuracy of critchi approximation */
final double CHI_MAX = 99999.0; /* Maximum chi-square value */
double minchisq = 0.0;
double maxchisq = CHI_MAX;
if (p <= 0.0) {
return CHI_MAX;
}
else if (p >= 1.0) {
return 0.0;
}
double chisqval = df/Math.sqrt(p); /* fair first value */
while ((maxchisq - minchisq) > CHI_EPSILON) {
if (1-chisquareCdf(chisqval, df) < p) {
maxchisq = chisqval;
}
else {
minchisq = chisqval;
}
chisqval = (maxchisq + minchisq) * 0.5;
}
return chisqval;
} | java | public static double chisquareInverseCdf(double p, int df) {
final double CHI_EPSILON = 0.000001; /* Accuracy of critchi approximation */
final double CHI_MAX = 99999.0; /* Maximum chi-square value */
double minchisq = 0.0;
double maxchisq = CHI_MAX;
if (p <= 0.0) {
return CHI_MAX;
}
else if (p >= 1.0) {
return 0.0;
}
double chisqval = df/Math.sqrt(p); /* fair first value */
while ((maxchisq - minchisq) > CHI_EPSILON) {
if (1-chisquareCdf(chisqval, df) < p) {
maxchisq = chisqval;
}
else {
minchisq = chisqval;
}
chisqval = (maxchisq + minchisq) * 0.5;
}
return chisqval;
} | [
"public",
"static",
"double",
"chisquareInverseCdf",
"(",
"double",
"p",
",",
"int",
"df",
")",
"{",
"final",
"double",
"CHI_EPSILON",
"=",
"0.000001",
";",
"/* Accuracy of critchi approximation */",
"final",
"double",
"CHI_MAX",
"=",
"99999.0",
";",
"/* Maximum chi... | Returns the x score of a specific pvalue and degrees of freedom for Chisquare. It We just do a bisectionsearch for a value within CHI_EPSILON, relying on the monotonicity of chisquareCdf().
Ported from Javascript code posted at http://www.fourmilab.ch/rpkp/experiments/analysis/chiCalc.js
@param p
@param df
@return | [
"Returns",
"the",
"x",
"score",
"of",
"a",
"specific",
"pvalue",
"and",
"degrees",
"of",
"freedom",
"for",
"Chisquare",
".",
"It",
"We",
"just",
"do",
"a",
"bisectionsearch",
"for",
"a",
"value",
"within",
"CHI_EPSILON",
"relying",
"on",
"the",
"monotonicity... | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java#L485-L510 |
xwiki/xwiki-commons | xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/AbstractVerifyMojo.java | AbstractVerifyMojo.guessDefaultLanguage | protected String guessDefaultLanguage(File file, Collection<File> xwikiXmlFiles)
{
String fileName = file.getName();
// Note that we need to check for content pages before technical pages because some pages are both content
// pages (Translation pages for example) and technical pages.
// Is it in the list of defined content pages?
String language = guessDefaultLanguageForPatterns(fileName, this.contentPagePatterns, this.defaultLanguage);
if (language != null) {
return language;
}
// Is it in the list of defined technical pages?
language = guessDefaultLanguageForPatterns(fileName, this.technicalPagePatterns, "");
if (language != null) {
return language;
}
language = "";
// Check if the doc is a translation
Matcher matcher = TRANSLATION_PATTERN.matcher(fileName);
if (matcher.matches()) {
// We're in a translation, use the default language
language = this.defaultLanguage;
} else {
// We're not in a translation, check if there are translations. First get the doc name before the extension
String prefix = StringUtils.substringBeforeLast(fileName, EXTENSION);
// Check for a translation now
Pattern translationPattern = Pattern.compile(String.format("%s\\..*\\.xml", Pattern.quote(prefix)));
for (File xwikiXmlFile : xwikiXmlFiles) {
Matcher translationMatcher = translationPattern.matcher(xwikiXmlFile.getName());
if (translationMatcher.matches()) {
// Found a translation, use the default language
language = this.defaultLanguage;
break;
}
}
}
return language;
} | java | protected String guessDefaultLanguage(File file, Collection<File> xwikiXmlFiles)
{
String fileName = file.getName();
// Note that we need to check for content pages before technical pages because some pages are both content
// pages (Translation pages for example) and technical pages.
// Is it in the list of defined content pages?
String language = guessDefaultLanguageForPatterns(fileName, this.contentPagePatterns, this.defaultLanguage);
if (language != null) {
return language;
}
// Is it in the list of defined technical pages?
language = guessDefaultLanguageForPatterns(fileName, this.technicalPagePatterns, "");
if (language != null) {
return language;
}
language = "";
// Check if the doc is a translation
Matcher matcher = TRANSLATION_PATTERN.matcher(fileName);
if (matcher.matches()) {
// We're in a translation, use the default language
language = this.defaultLanguage;
} else {
// We're not in a translation, check if there are translations. First get the doc name before the extension
String prefix = StringUtils.substringBeforeLast(fileName, EXTENSION);
// Check for a translation now
Pattern translationPattern = Pattern.compile(String.format("%s\\..*\\.xml", Pattern.quote(prefix)));
for (File xwikiXmlFile : xwikiXmlFiles) {
Matcher translationMatcher = translationPattern.matcher(xwikiXmlFile.getName());
if (translationMatcher.matches()) {
// Found a translation, use the default language
language = this.defaultLanguage;
break;
}
}
}
return language;
} | [
"protected",
"String",
"guessDefaultLanguage",
"(",
"File",
"file",
",",
"Collection",
"<",
"File",
">",
"xwikiXmlFiles",
")",
"{",
"String",
"fileName",
"=",
"file",
".",
"getName",
"(",
")",
";",
"// Note that we need to check for content pages before technical pages ... | Guess the {@code <defaultLanguage>} value to use for the passed file using the following algorithm:
<ul>
<li>If the page name matches one of the regexes defined by the user as content pages then check that the
default language is {@link #defaultLanguage}.</li>
<li>If the page name matches one of the regexes defined by the user as technial pages then check that the
default language is empty. Matching technical pages have precedence over matching content pages.</li>
<li>If there's no other translation of the file then consider default language to be empty to signify that
it's a technical document. </li>
<li>If there are other translations ("(prefix).(language).xml" format) then the default language should be
{@link #defaultLanguage}</li>
</ul>
@param file the XML file for which to guess the default language that it should have
@param xwikiXmlFiles the list of all XML files that is used to check for translations of the passed XML file
@return the default language as a string (e.g. "en" for English or "" for an empty default language)
@since 5.4.1 | [
"Guess",
"the",
"{"
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/AbstractVerifyMojo.java#L251-L292 |
Bernardo-MG/maven-site-fixer | src/main/java/com/bernardomg/velocity/tool/Html5UpdateTool.java | Html5UpdateTool.updateTableHeads | public final void updateTableHeads(final Element root) {
final Iterable<Element> tableHeadRows; // Heads to fix
Element table; // HTML table
Element thead; // Table's head for wrapping
checkNotNull(root, "Received a null pointer as root element");
// Table rows with <th> tags in a <tbody>
tableHeadRows = root.select("table > tbody > tr:has(th)");
for (final Element row : tableHeadRows) {
// Gets the row's table
// The selector ensured the row is inside a tbody
table = row.parent().parent();
// Removes the row from its original position
row.remove();
// Creates a table header element with the row
thead = new Element(Tag.valueOf("thead"), "");
thead.appendChild(row);
// Adds the head at the beginning of the table
table.prependChild(thead);
}
} | java | public final void updateTableHeads(final Element root) {
final Iterable<Element> tableHeadRows; // Heads to fix
Element table; // HTML table
Element thead; // Table's head for wrapping
checkNotNull(root, "Received a null pointer as root element");
// Table rows with <th> tags in a <tbody>
tableHeadRows = root.select("table > tbody > tr:has(th)");
for (final Element row : tableHeadRows) {
// Gets the row's table
// The selector ensured the row is inside a tbody
table = row.parent().parent();
// Removes the row from its original position
row.remove();
// Creates a table header element with the row
thead = new Element(Tag.valueOf("thead"), "");
thead.appendChild(row);
// Adds the head at the beginning of the table
table.prependChild(thead);
}
} | [
"public",
"final",
"void",
"updateTableHeads",
"(",
"final",
"Element",
"root",
")",
"{",
"final",
"Iterable",
"<",
"Element",
">",
"tableHeadRows",
";",
"// Heads to fix",
"Element",
"table",
";",
"// HTML table",
"Element",
"thead",
";",
"// Table's head for wrapp... | Corrects table headers by adding a {@code <thead>} section where missing.
<p>
This serves to fix an error with tables created by Doxia, which will add
the header rows into the {@code <tbody>} element, instead on a {@code
<thead>} element.
@param root
root element with tables to fix | [
"Corrects",
"table",
"headers",
"by",
"adding",
"a",
"{",
"@code",
"<thead",
">",
"}",
"section",
"where",
"missing",
".",
"<p",
">",
"This",
"serves",
"to",
"fix",
"an",
"error",
"with",
"tables",
"created",
"by",
"Doxia",
"which",
"will",
"add",
"the",... | train | https://github.com/Bernardo-MG/maven-site-fixer/blob/e064472faa7edb0fca11647a22d90ad72089baa3/src/main/java/com/bernardomg/velocity/tool/Html5UpdateTool.java#L125-L148 |
alkacon/opencms-core | src/org/opencms/ui/components/CmsUserDataFormLayout.java | CmsUserDataFormLayout.buildField | private TextField buildField(String label, CmsAccountInfo info) {
TextField field = (TextField)m_binder.buildAndBind(label, info);
field.setConverter(new CmsNullToEmptyConverter());
field.setWidth("100%");
boolean editable = (m_editLevel == EditLevel.all)
|| (info.isEditable() && (m_editLevel == EditLevel.configured));
field.setEnabled(editable);
if (editable) {
field.addValidator(new FieldValidator(info.getField()));
}
field.setImmediate(true);
return field;
} | java | private TextField buildField(String label, CmsAccountInfo info) {
TextField field = (TextField)m_binder.buildAndBind(label, info);
field.setConverter(new CmsNullToEmptyConverter());
field.setWidth("100%");
boolean editable = (m_editLevel == EditLevel.all)
|| (info.isEditable() && (m_editLevel == EditLevel.configured));
field.setEnabled(editable);
if (editable) {
field.addValidator(new FieldValidator(info.getField()));
}
field.setImmediate(true);
return field;
} | [
"private",
"TextField",
"buildField",
"(",
"String",
"label",
",",
"CmsAccountInfo",
"info",
")",
"{",
"TextField",
"field",
"=",
"(",
"TextField",
")",
"m_binder",
".",
"buildAndBind",
"(",
"label",
",",
"info",
")",
";",
"field",
".",
"setConverter",
"(",
... | Builds the text field for the given property.<p>
@param label the field label
@param info the property name
@return the field | [
"Builds",
"the",
"text",
"field",
"for",
"the",
"given",
"property",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsUserDataFormLayout.java#L254-L267 |
opentok/Opentok-Java-SDK | src/main/java/com/opentok/OpenTok.java | OpenTok.startArchive | public Archive startArchive(String sessionId, ArchiveProperties properties) throws OpenTokException {
if (sessionId == null || sessionId == "") {
throw new InvalidArgumentException("Session not valid");
}
Boolean hasResolution = properties != null && properties.resolution() != null && !properties.resolution().isEmpty();
if(properties != null && properties.outputMode().equals(Archive.OutputMode.INDIVIDUAL) && hasResolution) {
throw new InvalidArgumentException("The resolution cannot be specified for individual output mode.");
}
// TODO: do validation on sessionId and name
String archive = this.client.startArchive(sessionId, properties);
try {
return archiveReader.readValue(archive);
} catch (Exception e) {
throw new RequestException("Exception mapping json: " + e.getMessage());
}
} | java | public Archive startArchive(String sessionId, ArchiveProperties properties) throws OpenTokException {
if (sessionId == null || sessionId == "") {
throw new InvalidArgumentException("Session not valid");
}
Boolean hasResolution = properties != null && properties.resolution() != null && !properties.resolution().isEmpty();
if(properties != null && properties.outputMode().equals(Archive.OutputMode.INDIVIDUAL) && hasResolution) {
throw new InvalidArgumentException("The resolution cannot be specified for individual output mode.");
}
// TODO: do validation on sessionId and name
String archive = this.client.startArchive(sessionId, properties);
try {
return archiveReader.readValue(archive);
} catch (Exception e) {
throw new RequestException("Exception mapping json: " + e.getMessage());
}
} | [
"public",
"Archive",
"startArchive",
"(",
"String",
"sessionId",
",",
"ArchiveProperties",
"properties",
")",
"throws",
"OpenTokException",
"{",
"if",
"(",
"sessionId",
"==",
"null",
"||",
"sessionId",
"==",
"\"\"",
")",
"{",
"throw",
"new",
"InvalidArgumentExcept... | Starts archiving an OpenTok session. This version of the <code>startArchive()</code> method
lets you disable audio or video recording.
<p>
Clients must be actively connected to the OpenTok session for you to successfully start
recording an archive.
<p>
You can only record one archive at a time for a given session. You can only record archives
of sessions that use the OpenTok Media Router (sessions with the
<a href="https://tokbox.com/developer/guides/create-session/#media-mode">media mode</a>
set to routed); you cannot archive sessions with the media mode set to relayed.
<p>
For more information on archiving, see the
<a href="https://tokbox.com/developer/guides//archiving/">OpenTok archiving</a>
developer guide.
@param sessionId The session ID of the OpenTok session to archive.
@param properties This ArchiveProperties object defines options for the archive.
@return The Archive object. This object includes properties defining the archive, including the archive ID. | [
"Starts",
"archiving",
"an",
"OpenTok",
"session",
".",
"This",
"version",
"of",
"the",
"<code",
">",
"startArchive",
"()",
"<",
"/",
"code",
">",
"method",
"lets",
"you",
"disable",
"audio",
"or",
"video",
"recording",
".",
"<p",
">",
"Clients",
"must",
... | train | https://github.com/opentok/Opentok-Java-SDK/blob/d71b7999facc3131c415aebea874ea55776d477f/src/main/java/com/opentok/OpenTok.java#L436-L451 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.readResource | public CmsResource readResource(CmsUUID structureID, CmsResourceFilter filter) throws CmsException {
return m_securityManager.readResource(m_context, structureID, filter);
} | java | public CmsResource readResource(CmsUUID structureID, CmsResourceFilter filter) throws CmsException {
return m_securityManager.readResource(m_context, structureID, filter);
} | [
"public",
"CmsResource",
"readResource",
"(",
"CmsUUID",
"structureID",
",",
"CmsResourceFilter",
"filter",
")",
"throws",
"CmsException",
"{",
"return",
"m_securityManager",
".",
"readResource",
"(",
"m_context",
",",
"structureID",
",",
"filter",
")",
";",
"}"
] | Reads a resource from the VFS,
using the specified resource filter.<p>
A resource may be of type <code>{@link CmsFile}</code> or
<code>{@link CmsFolder}</code>. In case of
a file, the resource will not contain the binary file content. Since reading
the binary content is a cost-expensive database operation, it's recommended
to work with resources if possible, and only read the file content when absolutely
required. To "upgrade" a resource to a file,
use <code>{@link #readFile(CmsResource)}</code>.<p>
The specified filter controls what kind of resources should be "found"
during the read operation. This will depend on the application. For example,
using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently
"valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code>
will ignore the date release / date expired information of the resource.<p>
@param structureID the structure ID of the resource to read
@param filter the resource filter to use while reading
@return the resource that was read
@throws CmsException if the resource could not be read for any reason
@see #readFile(String, CmsResourceFilter)
@see #readFolder(String, CmsResourceFilter) | [
"Reads",
"a",
"resource",
"from",
"the",
"VFS",
"using",
"the",
"specified",
"resource",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L3113-L3116 |
apollographql/apollo-android | apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java | ResponseField.forObject | public static ResponseField forObject(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
return new ResponseField(Type.OBJECT, responseName, fieldName, arguments, optional, conditions);
} | java | public static ResponseField forObject(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
return new ResponseField(Type.OBJECT, responseName, fieldName, arguments, optional, conditions);
} | [
"public",
"static",
"ResponseField",
"forObject",
"(",
"String",
"responseName",
",",
"String",
"fieldName",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"arguments",
",",
"boolean",
"optional",
",",
"List",
"<",
"Condition",
">",
"conditions",
")",
"{",
"... | Factory method for creating a Field instance representing a custom {@link Type#OBJECT}.
@param responseName alias for the result of a field
@param fieldName name of the field in the GraphQL operation
@param arguments arguments to be passed along with the field
@param optional whether the arguments passed along are optional or required
@param conditions list of conditions for this field
@return Field instance representing custom {@link Type#OBJECT} | [
"Factory",
"method",
"for",
"creating",
"a",
"Field",
"instance",
"representing",
"a",
"custom",
"{",
"@link",
"Type#OBJECT",
"}",
"."
] | train | https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java#L130-L133 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.dedicated_server_serviceName_usbKey_duration_POST | public OvhOrder dedicated_server_serviceName_usbKey_duration_POST(String serviceName, String duration, OvhUsbKeyCapacityEnum capacity) throws IOException {
String qPath = "/order/dedicated/server/{serviceName}/usbKey/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "capacity", capacity);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder dedicated_server_serviceName_usbKey_duration_POST(String serviceName, String duration, OvhUsbKeyCapacityEnum capacity) throws IOException {
String qPath = "/order/dedicated/server/{serviceName}/usbKey/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "capacity", capacity);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"dedicated_server_serviceName_usbKey_duration_POST",
"(",
"String",
"serviceName",
",",
"String",
"duration",
",",
"OvhUsbKeyCapacityEnum",
"capacity",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/dedicated/server/{serviceName}/usbK... | Create order
REST: POST /order/dedicated/server/{serviceName}/usbKey/{duration}
@param capacity [required] Capacity in gigabytes
@param serviceName [required] The internal name of your dedicated server
@param duration [required] Duration | [
"Create",
"order"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L2687-L2694 |
apache/incubator-heron | storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java | ConfigUtils.translateComponentConfig | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateComponentConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
doStormTranslation(heronConfig);
return heronConfig;
} | java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateComponentConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
doStormTranslation(heronConfig);
return heronConfig;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"Config",
"translateComponentConfig",
"(",
"Map",
"stormConfig",
")",
"{",
"Config",
"heronConfig",
";",
"if",
"(",
"stormConfig",
"!=",
"null",
")",
"{",
"h... | Translate storm config to heron config for components
@param stormConfig the storm config
@return a heron config | [
"Translate",
"storm",
"config",
"to",
"heron",
"config",
"for",
"components"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java#L65-L77 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/strings/offsets/OffsetGroup.java | OffsetGroup.from | public static OffsetGroup from(final CharOffset charOffset, final EDTOffset edtOffset) {
return new Builder().charOffset(charOffset).edtOffset(edtOffset).build();
} | java | public static OffsetGroup from(final CharOffset charOffset, final EDTOffset edtOffset) {
return new Builder().charOffset(charOffset).edtOffset(edtOffset).build();
} | [
"public",
"static",
"OffsetGroup",
"from",
"(",
"final",
"CharOffset",
"charOffset",
",",
"final",
"EDTOffset",
"edtOffset",
")",
"{",
"return",
"new",
"Builder",
"(",
")",
".",
"charOffset",
"(",
"charOffset",
")",
".",
"edtOffset",
"(",
"edtOffset",
")",
"... | Creates a {@code OffsetGroup} with the specified character and EDT offsets and no specified
byte or ASR offsets. | [
"Creates",
"a",
"{"
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/strings/offsets/OffsetGroup.java#L40-L42 |
sebastiangraf/perfidix | src/main/java/org/perfidix/socketadapter/SocketViewProgressUpdater.java | SocketViewProgressUpdater.initProgressView | public boolean initProgressView(final Map<BenchmarkMethod, Integer> mapping)
throws SocketViewException {
if (mapping != null) {
final Set<BenchmarkMethod> methodSet = mapping.keySet();
final Map<String, Integer> finalMap = new HashMap<String, Integer>();
for (BenchmarkMethod benchmarkMethod : methodSet) {
finalMap.put(benchmarkMethod.getMethodWithClassName(),
mapping.get(benchmarkMethod));
}
viewStub.initTotalBenchProgress(finalMap);
}
return true;
} | java | public boolean initProgressView(final Map<BenchmarkMethod, Integer> mapping)
throws SocketViewException {
if (mapping != null) {
final Set<BenchmarkMethod> methodSet = mapping.keySet();
final Map<String, Integer> finalMap = new HashMap<String, Integer>();
for (BenchmarkMethod benchmarkMethod : methodSet) {
finalMap.put(benchmarkMethod.getMethodWithClassName(),
mapping.get(benchmarkMethod));
}
viewStub.initTotalBenchProgress(finalMap);
}
return true;
} | [
"public",
"boolean",
"initProgressView",
"(",
"final",
"Map",
"<",
"BenchmarkMethod",
",",
"Integer",
">",
"mapping",
")",
"throws",
"SocketViewException",
"{",
"if",
"(",
"mapping",
"!=",
"null",
")",
"{",
"final",
"Set",
"<",
"BenchmarkMethod",
">",
"methodS... | This method initializes the values of the eclipse view and resets the
progress bar.
@param mapping
a mapping with all methods to benchmark and the related runs
@throws SocketViewException
if init fails | [
"This",
"method",
"initializes",
"the",
"values",
"of",
"the",
"eclipse",
"view",
"and",
"resets",
"the",
"progress",
"bar",
"."
] | train | https://github.com/sebastiangraf/perfidix/blob/f13aa793b6a3055215ed4edbb946c1bb5d564886/src/main/java/org/perfidix/socketadapter/SocketViewProgressUpdater.java#L73-L88 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/FailoverGroupsInner.java | FailoverGroupsInner.beginCreateOrUpdate | public FailoverGroupInner beginCreateOrUpdate(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).toBlocking().single().body();
} | java | public FailoverGroupInner beginCreateOrUpdate(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).toBlocking().single().body();
} | [
"public",
"FailoverGroupInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"failoverGroupName",
",",
"FailoverGroupInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resour... | Creates or updates 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 serverName The name of the server containing the failover group.
@param failoverGroupName The name of the failover group.
@param parameters The failover group parameters.
@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 FailoverGroupInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"failover",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/FailoverGroupsInner.java#L310-L312 |
pravega/pravega | controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java | ZkOrderedStore.getEntitiesWithPosition | CompletableFuture<Map<Long, String>> getEntitiesWithPosition(String scope, String stream) {
Map<Long, String> result = new ConcurrentHashMap<>();
return Futures.exceptionallyExpecting(storeHelper.getChildren(getCollectionsPath(scope, stream)), DATA_NOT_FOUND_PREDICATE, Collections.emptyList())
.thenCompose(children -> {
// start with smallest collection and collect records
List<Integer> iterable = children.stream().map(Integer::parseInt).collect(Collectors.toList());
return Futures.loop(iterable, collectionNumber -> {
return Futures.exceptionallyExpecting(storeHelper.getChildren(getEntitiesPath(scope, stream, collectionNumber)),
DATA_NOT_FOUND_PREDICATE, Collections.emptyList())
.thenCompose(entities -> Futures.allOf(
entities.stream().map(x -> {
int pos = getPositionFromPath(x);
return storeHelper.getData(getEntityPath(scope, stream, collectionNumber, pos),
m -> new String(m, Charsets.UTF_8))
.thenAccept(r -> {
result.put(Position.toLong(collectionNumber, pos),
r.getObject());
});
}).collect(Collectors.toList()))
).thenApply(v -> true);
}, executor);
}).thenApply(v -> result)
.whenComplete((r, e) -> {
if (e != null) {
log.error("error encountered while trying to retrieve entities for stream {}/{}", scope, stream, e);
} else {
log.debug("entities at positions {} retrieved for stream {}/{}", r, scope, stream);
}
});
} | java | CompletableFuture<Map<Long, String>> getEntitiesWithPosition(String scope, String stream) {
Map<Long, String> result = new ConcurrentHashMap<>();
return Futures.exceptionallyExpecting(storeHelper.getChildren(getCollectionsPath(scope, stream)), DATA_NOT_FOUND_PREDICATE, Collections.emptyList())
.thenCompose(children -> {
// start with smallest collection and collect records
List<Integer> iterable = children.stream().map(Integer::parseInt).collect(Collectors.toList());
return Futures.loop(iterable, collectionNumber -> {
return Futures.exceptionallyExpecting(storeHelper.getChildren(getEntitiesPath(scope, stream, collectionNumber)),
DATA_NOT_FOUND_PREDICATE, Collections.emptyList())
.thenCompose(entities -> Futures.allOf(
entities.stream().map(x -> {
int pos = getPositionFromPath(x);
return storeHelper.getData(getEntityPath(scope, stream, collectionNumber, pos),
m -> new String(m, Charsets.UTF_8))
.thenAccept(r -> {
result.put(Position.toLong(collectionNumber, pos),
r.getObject());
});
}).collect(Collectors.toList()))
).thenApply(v -> true);
}, executor);
}).thenApply(v -> result)
.whenComplete((r, e) -> {
if (e != null) {
log.error("error encountered while trying to retrieve entities for stream {}/{}", scope, stream, e);
} else {
log.debug("entities at positions {} retrieved for stream {}/{}", r, scope, stream);
}
});
} | [
"CompletableFuture",
"<",
"Map",
"<",
"Long",
",",
"String",
">",
">",
"getEntitiesWithPosition",
"(",
"String",
"scope",
",",
"String",
"stream",
")",
"{",
"Map",
"<",
"Long",
",",
"String",
">",
"result",
"=",
"new",
"ConcurrentHashMap",
"<>",
"(",
")",
... | Returns a map of position to entity that was added to the set.
Note: Entities are ordered by position in the set but the map responded from this api is not ordered by default.
Users can filter and order elements based on the position and entity id.
@param scope scope scope
@param stream stream stream
@return CompletableFuture which when completed will contain all positions to entities in the set. | [
"Returns",
"a",
"map",
"of",
"position",
"to",
"entity",
"that",
"was",
"added",
"to",
"the",
"set",
".",
"Note",
":",
"Entities",
"are",
"ordered",
"by",
"position",
"in",
"the",
"set",
"but",
"the",
"map",
"responded",
"from",
"this",
"api",
"is",
"n... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java#L168-L199 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java | FeatureIO.writeText | public static void writeText(String featuresFileName, double[][] features) throws Exception {
BufferedWriter out = new BufferedWriter(new FileWriter(featuresFileName));
for (double[] feature : features) {
for (int j = 0; j < feature.length - 1; j++) {
out.write(feature[j] + ",");
}
out.write(feature[feature.length - 1] + "\n");
}
out.close();
} | java | public static void writeText(String featuresFileName, double[][] features) throws Exception {
BufferedWriter out = new BufferedWriter(new FileWriter(featuresFileName));
for (double[] feature : features) {
for (int j = 0; j < feature.length - 1; j++) {
out.write(feature[j] + ",");
}
out.write(feature[feature.length - 1] + "\n");
}
out.close();
} | [
"public",
"static",
"void",
"writeText",
"(",
"String",
"featuresFileName",
",",
"double",
"[",
"]",
"[",
"]",
"features",
")",
"throws",
"Exception",
"{",
"BufferedWriter",
"out",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"featuresFileName",
... | Takes a two-dimensional double array with features and writes them in a comma separated text file.
@param featuresFileName
The text file's name.
@param features
The features.
@throws Exception | [
"Takes",
"a",
"two",
"-",
"dimensional",
"double",
"array",
"with",
"features",
"and",
"writes",
"them",
"in",
"a",
"comma",
"separated",
"text",
"file",
"."
] | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L121-L130 |
geomajas/geomajas-project-client-gwt | common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java | HtmlBuilder.trClassHtmlContent | public static String trClassHtmlContent(String clazz, String... content) {
return tagClassHtmlContent(Html.Tag.TR, clazz, content);
} | java | public static String trClassHtmlContent(String clazz, String... content) {
return tagClassHtmlContent(Html.Tag.TR, clazz, content);
} | [
"public",
"static",
"String",
"trClassHtmlContent",
"(",
"String",
"clazz",
",",
"String",
"...",
"content",
")",
"{",
"return",
"tagClassHtmlContent",
"(",
"Html",
".",
"Tag",
".",
"TR",
",",
"clazz",
",",
"content",
")",
";",
"}"
] | Build a HTML TableRow with given CSS class for a string.
Use this method if given content contains HTML snippets, prepared with {@link HtmlBuilder#htmlEncode(String)}.
@param clazz class for tr element
@param content content string
@return HTML tr element as string | [
"Build",
"a",
"HTML",
"TableRow",
"with",
"given",
"CSS",
"class",
"for",
"a",
"string",
".",
"Use",
"this",
"method",
"if",
"given",
"content",
"contains",
"HTML",
"snippets",
"prepared",
"with",
"{",
"@link",
"HtmlBuilder#htmlEncode",
"(",
"String",
")",
"... | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L115-L117 |
lucmoreau/ProvToolbox | prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java | ProvFactory.newWasEndedBy | public WasEndedBy newWasEndedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger) {
WasEndedBy res = of.createWasEndedBy();
res.setId(id);
res.setActivity(activity);
res.setTrigger(trigger);
return res;
} | java | public WasEndedBy newWasEndedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger) {
WasEndedBy res = of.createWasEndedBy();
res.setId(id);
res.setActivity(activity);
res.setTrigger(trigger);
return res;
} | [
"public",
"WasEndedBy",
"newWasEndedBy",
"(",
"QualifiedName",
"id",
",",
"QualifiedName",
"activity",
",",
"QualifiedName",
"trigger",
")",
"{",
"WasEndedBy",
"res",
"=",
"of",
".",
"createWasEndedBy",
"(",
")",
";",
"res",
".",
"setId",
"(",
"id",
")",
";"... | A factory method to create an instance of an end {@link WasEndedBy}
@param id
@param activity an identifier for the ended <a href="http://www.w3.org/TR/prov-dm/#end.activity">activity</a>
@param trigger an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#end.trigger">entity triggering</a> the activity ending
@return an instance of {@link WasEndedBy} | [
"A",
"factory",
"method",
"to",
"create",
"an",
"instance",
"of",
"an",
"end",
"{"
] | train | https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java#L1245-L1251 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/redis/Cache.java | Cache.expireAt | public Long expireAt(Object key, long unixTime) {
Jedis jedis = getJedis();
try {
return jedis.expireAt(keyToBytes(key), unixTime);
}
finally {close(jedis);}
} | java | public Long expireAt(Object key, long unixTime) {
Jedis jedis = getJedis();
try {
return jedis.expireAt(keyToBytes(key), unixTime);
}
finally {close(jedis);}
} | [
"public",
"Long",
"expireAt",
"(",
"Object",
"key",
",",
"long",
"unixTime",
")",
"{",
"Jedis",
"jedis",
"=",
"getJedis",
"(",
")",
";",
"try",
"{",
"return",
"jedis",
".",
"expireAt",
"(",
"keyToBytes",
"(",
"key",
")",
",",
"unixTime",
")",
";",
"}... | EXPIREAT 的作用和 EXPIRE 类似,都用于为 key 设置生存时间。不同在于 EXPIREAT 命令接受的时间参数是 UNIX 时间戳(unix timestamp)。 | [
"EXPIREAT",
"的作用和",
"EXPIRE",
"类似,都用于为",
"key",
"设置生存时间。不同在于",
"EXPIREAT",
"命令接受的时间参数是",
"UNIX",
"时间戳",
"(",
"unix",
"timestamp",
")",
"。"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/redis/Cache.java#L329-L335 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java | DisasterRecoveryConfigurationsInner.beginFailoverAsync | public Observable<Void> beginFailoverAsync(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) {
return beginFailoverWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> beginFailoverAsync(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) {
return beginFailoverWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"beginFailoverAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"disasterRecoveryConfigurationName",
")",
"{",
"return",
"beginFailoverWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
... | Fails over from the current primary server to this server.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param disasterRecoveryConfigurationName The name of the disaster recovery configuration to failover.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Fails",
"over",
"from",
"the",
"current",
"primary",
"server",
"to",
"this",
"server",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java#L736-L743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.