repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfStream.java | PdfStream.writeLength | public void writeLength() throws IOException {
"""
Writes the stream length to the <CODE>PdfWriter</CODE>.
<p>
This method must be called and can only be called if the constructor {@link #PdfStream(InputStream,PdfWriter)}
is used to create the stream.
@throws IOException on error
@see #PdfStream(InputStream,PdfWriter)
"""
if (inputStream == null)
throw new UnsupportedOperationException("writeLength() can only be called in a contructed PdfStream(InputStream,PdfWriter).");
if (inputStreamLength == -1)
throw new IOException("writeLength() can only be called after output of the stream body.");
writer.addToBody(new PdfNumber(inputStreamLength), ref, false);
} | java | public void writeLength() throws IOException {
if (inputStream == null)
throw new UnsupportedOperationException("writeLength() can only be called in a contructed PdfStream(InputStream,PdfWriter).");
if (inputStreamLength == -1)
throw new IOException("writeLength() can only be called after output of the stream body.");
writer.addToBody(new PdfNumber(inputStreamLength), ref, false);
} | [
"public",
"void",
"writeLength",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"inputStream",
"==",
"null",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"writeLength() can only be called in a contructed PdfStream(InputStream,PdfWriter).\"",
")",
";",
"if",
"(",
"inputStreamLength",
"==",
"-",
"1",
")",
"throw",
"new",
"IOException",
"(",
"\"writeLength() can only be called after output of the stream body.\"",
")",
";",
"writer",
".",
"addToBody",
"(",
"new",
"PdfNumber",
"(",
"inputStreamLength",
")",
",",
"ref",
",",
"false",
")",
";",
"}"
] | Writes the stream length to the <CODE>PdfWriter</CODE>.
<p>
This method must be called and can only be called if the constructor {@link #PdfStream(InputStream,PdfWriter)}
is used to create the stream.
@throws IOException on error
@see #PdfStream(InputStream,PdfWriter) | [
"Writes",
"the",
"stream",
"length",
"to",
"the",
"<CODE",
">",
"PdfWriter<",
"/",
"CODE",
">",
".",
"<p",
">",
"This",
"method",
"must",
"be",
"called",
"and",
"can",
"only",
"be",
"called",
"if",
"the",
"constructor",
"{"
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStream.java#L186-L192 |
apereo/cas | support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java | DelegatedClientAuthenticationAction.handleException | protected Event handleException(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client, final Exception e) {
"""
Handle the thrown exception.
@param webContext the web context
@param client the authentication client
@param e the thrown exception
@return the event to trigger
"""
if (e instanceof RequestSloException) {
try {
webContext.getResponse().sendRedirect("logout");
} catch (final IOException ioe) {
throw new IllegalArgumentException("Unable to call logout", ioe);
}
return stopWebflow();
}
val msg = String.format("Delegated authentication has failed with client %s", client.getName());
LOGGER.error(msg, e);
throw new IllegalArgumentException(msg);
} | java | protected Event handleException(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client, final Exception e) {
if (e instanceof RequestSloException) {
try {
webContext.getResponse().sendRedirect("logout");
} catch (final IOException ioe) {
throw new IllegalArgumentException("Unable to call logout", ioe);
}
return stopWebflow();
}
val msg = String.format("Delegated authentication has failed with client %s", client.getName());
LOGGER.error(msg, e);
throw new IllegalArgumentException(msg);
} | [
"protected",
"Event",
"handleException",
"(",
"final",
"J2EContext",
"webContext",
",",
"final",
"BaseClient",
"<",
"Credentials",
",",
"CommonProfile",
">",
"client",
",",
"final",
"Exception",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"RequestSloException",
")",
"{",
"try",
"{",
"webContext",
".",
"getResponse",
"(",
")",
".",
"sendRedirect",
"(",
"\"logout\"",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unable to call logout\"",
",",
"ioe",
")",
";",
"}",
"return",
"stopWebflow",
"(",
")",
";",
"}",
"val",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Delegated authentication has failed with client %s\"",
",",
"client",
".",
"getName",
"(",
")",
")",
";",
"LOGGER",
".",
"error",
"(",
"msg",
",",
"e",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"msg",
")",
";",
"}"
] | Handle the thrown exception.
@param webContext the web context
@param client the authentication client
@param e the thrown exception
@return the event to trigger | [
"Handle",
"the",
"thrown",
"exception",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java#L208-L220 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/annotation/AnnotationUtil.java | AnnotationUtil.getAnnotationValue | public static <T> T getAnnotationValue(AnnotatedElement annotationEle, Class<? extends Annotation> annotationType, String propertyName) throws UtilException {
"""
获取指定注解属性的值<br>
如果无指定的属性方法返回null
@param <T> 注解值类型
@param annotationEle {@link AccessibleObject},可以是Class、Method、Field、Constructor、ReflectPermission
@param annotationType 注解类型
@param propertyName 属性名,例如注解中定义了name()方法,则 此处传入name
@return 注解对象
@throws UtilException 调用注解中的方法时执行异常
"""
final Annotation annotation = getAnnotation(annotationEle, annotationType);
if (null == annotation) {
return null;
}
final Method method = ReflectUtil.getMethodOfObj(annotation, propertyName);
if (null == method) {
return null;
}
return ReflectUtil.invoke(annotation, method);
} | java | public static <T> T getAnnotationValue(AnnotatedElement annotationEle, Class<? extends Annotation> annotationType, String propertyName) throws UtilException {
final Annotation annotation = getAnnotation(annotationEle, annotationType);
if (null == annotation) {
return null;
}
final Method method = ReflectUtil.getMethodOfObj(annotation, propertyName);
if (null == method) {
return null;
}
return ReflectUtil.invoke(annotation, method);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getAnnotationValue",
"(",
"AnnotatedElement",
"annotationEle",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
",",
"String",
"propertyName",
")",
"throws",
"UtilException",
"{",
"final",
"Annotation",
"annotation",
"=",
"getAnnotation",
"(",
"annotationEle",
",",
"annotationType",
")",
";",
"if",
"(",
"null",
"==",
"annotation",
")",
"{",
"return",
"null",
";",
"}",
"final",
"Method",
"method",
"=",
"ReflectUtil",
".",
"getMethodOfObj",
"(",
"annotation",
",",
"propertyName",
")",
";",
"if",
"(",
"null",
"==",
"method",
")",
"{",
"return",
"null",
";",
"}",
"return",
"ReflectUtil",
".",
"invoke",
"(",
"annotation",
",",
"method",
")",
";",
"}"
] | 获取指定注解属性的值<br>
如果无指定的属性方法返回null
@param <T> 注解值类型
@param annotationEle {@link AccessibleObject},可以是Class、Method、Field、Constructor、ReflectPermission
@param annotationType 注解类型
@param propertyName 属性名,例如注解中定义了name()方法,则 此处传入name
@return 注解对象
@throws UtilException 调用注解中的方法时执行异常 | [
"获取指定注解属性的值<br",
">",
"如果无指定的属性方法返回null"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/annotation/AnnotationUtil.java#L90-L101 |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/ModuleFactory.java | ModuleFactory.createModule | public AbstractPipelineModule createModule(final Class<? extends AbstractPipelineModule> moduleClass)
throws DITAOTException {
"""
Create the ModuleElem class instance according to moduleName.
@param moduleClass module class
@return AbstractPipelineModule
@throws DITAOTException DITAOTException
@since 1.6
"""
try {
return moduleClass.newInstance();
} catch (final Exception e) {
final MessageBean msgBean = MessageUtils.getMessage("DOTJ005F", moduleClass.getName());
final String msg = msgBean.toString();
throw new DITAOTException(msgBean, e,msg);
}
} | java | public AbstractPipelineModule createModule(final Class<? extends AbstractPipelineModule> moduleClass)
throws DITAOTException {
try {
return moduleClass.newInstance();
} catch (final Exception e) {
final MessageBean msgBean = MessageUtils.getMessage("DOTJ005F", moduleClass.getName());
final String msg = msgBean.toString();
throw new DITAOTException(msgBean, e,msg);
}
} | [
"public",
"AbstractPipelineModule",
"createModule",
"(",
"final",
"Class",
"<",
"?",
"extends",
"AbstractPipelineModule",
">",
"moduleClass",
")",
"throws",
"DITAOTException",
"{",
"try",
"{",
"return",
"moduleClass",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"final",
"MessageBean",
"msgBean",
"=",
"MessageUtils",
".",
"getMessage",
"(",
"\"DOTJ005F\"",
",",
"moduleClass",
".",
"getName",
"(",
")",
")",
";",
"final",
"String",
"msg",
"=",
"msgBean",
".",
"toString",
"(",
")",
";",
"throw",
"new",
"DITAOTException",
"(",
"msgBean",
",",
"e",
",",
"msg",
")",
";",
"}",
"}"
] | Create the ModuleElem class instance according to moduleName.
@param moduleClass module class
@return AbstractPipelineModule
@throws DITAOTException DITAOTException
@since 1.6 | [
"Create",
"the",
"ModuleElem",
"class",
"instance",
"according",
"to",
"moduleName",
"."
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/ModuleFactory.java#L52-L62 |
rzwitserloot/lombok | src/core/lombok/javac/handlers/JavacHandlerUtil.java | JavacHandlerUtil.deleteAnnotationIfNeccessary | public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType1, Class<? extends Annotation> annotationType2) {
"""
Removes the annotation from javac's AST (it remains in lombok's AST),
then removes any import statement that imports this exact annotation (not star imports).
Only does this if the DeleteLombokAnnotations class is in the context.
"""
deleteAnnotationIfNeccessary0(annotation, annotationType1.getName(), annotationType2.getName());
} | java | public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType1, Class<? extends Annotation> annotationType2) {
deleteAnnotationIfNeccessary0(annotation, annotationType1.getName(), annotationType2.getName());
} | [
"public",
"static",
"void",
"deleteAnnotationIfNeccessary",
"(",
"JavacNode",
"annotation",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType1",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType2",
")",
"{",
"deleteAnnotationIfNeccessary0",
"(",
"annotation",
",",
"annotationType1",
".",
"getName",
"(",
")",
",",
"annotationType2",
".",
"getName",
"(",
")",
")",
";",
"}"
] | Removes the annotation from javac's AST (it remains in lombok's AST),
then removes any import statement that imports this exact annotation (not star imports).
Only does this if the DeleteLombokAnnotations class is in the context. | [
"Removes",
"the",
"annotation",
"from",
"javac",
"s",
"AST",
"(",
"it",
"remains",
"in",
"lombok",
"s",
"AST",
")",
"then",
"removes",
"any",
"import",
"statement",
"that",
"imports",
"this",
"exact",
"annotation",
"(",
"not",
"star",
"imports",
")",
".",
"Only",
"does",
"this",
"if",
"the",
"DeleteLombokAnnotations",
"class",
"is",
"in",
"the",
"context",
"."
] | train | https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L474-L476 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/conversions/implicit/ConversionAnalyzer.java | ConversionAnalyzer.getConversionType | public static ConversionType getConversionType(final Field destination, final Field source) {
"""
Analyzes Fields given as input and returns the type of conversion that has to be done.
@param destination Field to analyze
@param source Field to analyze
@return type of Conversion
"""
return getConversionType(destination.getType(),source.getType());
} | java | public static ConversionType getConversionType(final Field destination, final Field source){
return getConversionType(destination.getType(),source.getType());
} | [
"public",
"static",
"ConversionType",
"getConversionType",
"(",
"final",
"Field",
"destination",
",",
"final",
"Field",
"source",
")",
"{",
"return",
"getConversionType",
"(",
"destination",
".",
"getType",
"(",
")",
",",
"source",
".",
"getType",
"(",
")",
")",
";",
"}"
] | Analyzes Fields given as input and returns the type of conversion that has to be done.
@param destination Field to analyze
@param source Field to analyze
@return type of Conversion | [
"Analyzes",
"Fields",
"given",
"as",
"input",
"and",
"returns",
"the",
"type",
"of",
"conversion",
"that",
"has",
"to",
"be",
"done",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/conversions/implicit/ConversionAnalyzer.java#L39-L41 |
victims/victims-lib-java | src/main/java/com/redhat/victims/fingerprint/ClassFile.java | ClassFile.constantValue | public static String constantValue(int index, ConstantPool cp) {
"""
Resolves a constants value from the constant pool to the lowest form it
can be represented by. E.g. String, Integer, Float, etc.
@author gcmurphy
@param index
@param cp
@return
"""
Constant type = cp.getConstant(index);
if (type != null) {
switch (type.getTag()) {
case Constants.CONSTANT_Class:
ConstantClass cls = (ConstantClass) type;
return constantValue(cls.getNameIndex(), cp);
case Constants.CONSTANT_Double:
ConstantDouble dbl = (ConstantDouble) type;
return String.valueOf(dbl.getBytes());
case Constants.CONSTANT_Fieldref:
ConstantFieldref fieldRef = (ConstantFieldref) type;
return constantValue(fieldRef.getClassIndex(), cp) + " "
+ constantValue(fieldRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_Float:
ConstantFloat flt = (ConstantFloat) type;
return String.valueOf(flt.getBytes());
case Constants.CONSTANT_Integer:
ConstantInteger integer = (ConstantInteger) type;
return String.valueOf(integer.getBytes());
case Constants.CONSTANT_InterfaceMethodref:
ConstantInterfaceMethodref intRef = (ConstantInterfaceMethodref) type;
return constantValue(intRef.getClassIndex(), cp) + " "
+ constantValue(intRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_Long:
ConstantLong lng = (ConstantLong) type;
return String.valueOf(lng.getBytes());
case Constants.CONSTANT_Methodref:
ConstantMethodref methRef = (ConstantMethodref) type;
return constantValue(methRef.getClassIndex(), cp) + " "
+ constantValue(methRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_NameAndType:
ConstantNameAndType nameType = (ConstantNameAndType) type;
return nameType.getName(cp) + " " + nameType.getSignature(cp);
case Constants.CONSTANT_String:
ConstantString str = (ConstantString) type;
return str.getBytes(cp);
case Constants.CONSTANT_Utf8:
ConstantUtf8 utf8 = (ConstantUtf8) type;
return utf8.getBytes();
}
}
return "";
} | java | public static String constantValue(int index, ConstantPool cp) {
Constant type = cp.getConstant(index);
if (type != null) {
switch (type.getTag()) {
case Constants.CONSTANT_Class:
ConstantClass cls = (ConstantClass) type;
return constantValue(cls.getNameIndex(), cp);
case Constants.CONSTANT_Double:
ConstantDouble dbl = (ConstantDouble) type;
return String.valueOf(dbl.getBytes());
case Constants.CONSTANT_Fieldref:
ConstantFieldref fieldRef = (ConstantFieldref) type;
return constantValue(fieldRef.getClassIndex(), cp) + " "
+ constantValue(fieldRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_Float:
ConstantFloat flt = (ConstantFloat) type;
return String.valueOf(flt.getBytes());
case Constants.CONSTANT_Integer:
ConstantInteger integer = (ConstantInteger) type;
return String.valueOf(integer.getBytes());
case Constants.CONSTANT_InterfaceMethodref:
ConstantInterfaceMethodref intRef = (ConstantInterfaceMethodref) type;
return constantValue(intRef.getClassIndex(), cp) + " "
+ constantValue(intRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_Long:
ConstantLong lng = (ConstantLong) type;
return String.valueOf(lng.getBytes());
case Constants.CONSTANT_Methodref:
ConstantMethodref methRef = (ConstantMethodref) type;
return constantValue(methRef.getClassIndex(), cp) + " "
+ constantValue(methRef.getNameAndTypeIndex(), cp);
case Constants.CONSTANT_NameAndType:
ConstantNameAndType nameType = (ConstantNameAndType) type;
return nameType.getName(cp) + " " + nameType.getSignature(cp);
case Constants.CONSTANT_String:
ConstantString str = (ConstantString) type;
return str.getBytes(cp);
case Constants.CONSTANT_Utf8:
ConstantUtf8 utf8 = (ConstantUtf8) type;
return utf8.getBytes();
}
}
return "";
} | [
"public",
"static",
"String",
"constantValue",
"(",
"int",
"index",
",",
"ConstantPool",
"cp",
")",
"{",
"Constant",
"type",
"=",
"cp",
".",
"getConstant",
"(",
"index",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"switch",
"(",
"type",
".",
"getTag",
"(",
")",
")",
"{",
"case",
"Constants",
".",
"CONSTANT_Class",
":",
"ConstantClass",
"cls",
"=",
"(",
"ConstantClass",
")",
"type",
";",
"return",
"constantValue",
"(",
"cls",
".",
"getNameIndex",
"(",
")",
",",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Double",
":",
"ConstantDouble",
"dbl",
"=",
"(",
"ConstantDouble",
")",
"type",
";",
"return",
"String",
".",
"valueOf",
"(",
"dbl",
".",
"getBytes",
"(",
")",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Fieldref",
":",
"ConstantFieldref",
"fieldRef",
"=",
"(",
"ConstantFieldref",
")",
"type",
";",
"return",
"constantValue",
"(",
"fieldRef",
".",
"getClassIndex",
"(",
")",
",",
"cp",
")",
"+",
"\" \"",
"+",
"constantValue",
"(",
"fieldRef",
".",
"getNameAndTypeIndex",
"(",
")",
",",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Float",
":",
"ConstantFloat",
"flt",
"=",
"(",
"ConstantFloat",
")",
"type",
";",
"return",
"String",
".",
"valueOf",
"(",
"flt",
".",
"getBytes",
"(",
")",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Integer",
":",
"ConstantInteger",
"integer",
"=",
"(",
"ConstantInteger",
")",
"type",
";",
"return",
"String",
".",
"valueOf",
"(",
"integer",
".",
"getBytes",
"(",
")",
")",
";",
"case",
"Constants",
".",
"CONSTANT_InterfaceMethodref",
":",
"ConstantInterfaceMethodref",
"intRef",
"=",
"(",
"ConstantInterfaceMethodref",
")",
"type",
";",
"return",
"constantValue",
"(",
"intRef",
".",
"getClassIndex",
"(",
")",
",",
"cp",
")",
"+",
"\" \"",
"+",
"constantValue",
"(",
"intRef",
".",
"getNameAndTypeIndex",
"(",
")",
",",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Long",
":",
"ConstantLong",
"lng",
"=",
"(",
"ConstantLong",
")",
"type",
";",
"return",
"String",
".",
"valueOf",
"(",
"lng",
".",
"getBytes",
"(",
")",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Methodref",
":",
"ConstantMethodref",
"methRef",
"=",
"(",
"ConstantMethodref",
")",
"type",
";",
"return",
"constantValue",
"(",
"methRef",
".",
"getClassIndex",
"(",
")",
",",
"cp",
")",
"+",
"\" \"",
"+",
"constantValue",
"(",
"methRef",
".",
"getNameAndTypeIndex",
"(",
")",
",",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_NameAndType",
":",
"ConstantNameAndType",
"nameType",
"=",
"(",
"ConstantNameAndType",
")",
"type",
";",
"return",
"nameType",
".",
"getName",
"(",
"cp",
")",
"+",
"\" \"",
"+",
"nameType",
".",
"getSignature",
"(",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_String",
":",
"ConstantString",
"str",
"=",
"(",
"ConstantString",
")",
"type",
";",
"return",
"str",
".",
"getBytes",
"(",
"cp",
")",
";",
"case",
"Constants",
".",
"CONSTANT_Utf8",
":",
"ConstantUtf8",
"utf8",
"=",
"(",
"ConstantUtf8",
")",
"type",
";",
"return",
"utf8",
".",
"getBytes",
"(",
")",
";",
"}",
"}",
"return",
"\"\"",
";",
"}"
] | Resolves a constants value from the constant pool to the lowest form it
can be represented by. E.g. String, Integer, Float, etc.
@author gcmurphy
@param index
@param cp
@return | [
"Resolves",
"a",
"constants",
"value",
"from",
"the",
"constant",
"pool",
"to",
"the",
"lowest",
"form",
"it",
"can",
"be",
"represented",
"by",
".",
"E",
".",
"g",
".",
"String",
"Integer",
"Float",
"etc",
"."
] | train | https://github.com/victims/victims-lib-java/blob/ccd0e2fcc409bb6cdfc5de411c3bb202c9095f8b/src/main/java/com/redhat/victims/fingerprint/ClassFile.java#L76-L129 |
netshoes/spring-cloud-sleuth-amqp | src/main/java/com/netshoes/springframework/cloud/sleuth/instrument/amqp/support/AmqpMessageHeaderAccessor.java | AmqpMessageHeaderAccessor.getHeader | public <T> T getHeader(String name, Class<T> type) {
"""
Get a header value casting to expected type.
@param name Name of header
@param type Expected type of header's value
@param <T> Expected type of header's value
@return Value of header
"""
return (T) headers.get(name);
} | java | public <T> T getHeader(String name, Class<T> type) {
return (T) headers.get(name);
} | [
"public",
"<",
"T",
">",
"T",
"getHeader",
"(",
"String",
"name",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"(",
"T",
")",
"headers",
".",
"get",
"(",
"name",
")",
";",
"}"
] | Get a header value casting to expected type.
@param name Name of header
@param type Expected type of header's value
@param <T> Expected type of header's value
@return Value of header | [
"Get",
"a",
"header",
"value",
"casting",
"to",
"expected",
"type",
"."
] | train | https://github.com/netshoes/spring-cloud-sleuth-amqp/blob/e4616ba6a075286d553548a1e2a500cf0ff85557/src/main/java/com/netshoes/springframework/cloud/sleuth/instrument/amqp/support/AmqpMessageHeaderAccessor.java#L79-L81 |
Impetus/Kundera | src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java | SparkDataHandler.populateEntityFromDataFrame | private Object populateEntityFromDataFrame(EntityMetadata m, Map<String, Integer> columnIndexMap, Row row) {
"""
Populate entity from data frame.
@param m
the m
@param columnIndexMap
the column index map
@param row
the row
@return the object
"""
try
{
// create entity instance
Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
// handle relations
Map<String, Object> relations = new HashMap<String, Object>();
if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
{
relations = ((EnhanceEntity) entity).getRelations();
entity = ((EnhanceEntity) entity).getEntity();
}
// get a Set of attributes
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();
// iterate over attributes and find its value
for (Attribute attribute : attributes)
{
String columnName = getColumnName(attribute);
Object columnValue = row.get(columnIndexMap.get(columnName));
if (columnValue != null)
{
Object value = PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),
columnValue.getClass(), columnValue);
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
}
}
// find the value of @Id field for EnhanceEntity
SingularAttribute attrib = m.getIdAttribute();
Object rowKey = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, rowKey, relations);
}
return entity;
}
catch (PropertyAccessException e1)
{
throw new RuntimeException(e1);
}
} | java | private Object populateEntityFromDataFrame(EntityMetadata m, Map<String, Integer> columnIndexMap, Row row)
{
try
{
// create entity instance
Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
// handle relations
Map<String, Object> relations = new HashMap<String, Object>();
if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
{
relations = ((EnhanceEntity) entity).getRelations();
entity = ((EnhanceEntity) entity).getEntity();
}
// get a Set of attributes
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();
// iterate over attributes and find its value
for (Attribute attribute : attributes)
{
String columnName = getColumnName(attribute);
Object columnValue = row.get(columnIndexMap.get(columnName));
if (columnValue != null)
{
Object value = PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),
columnValue.getClass(), columnValue);
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
}
}
// find the value of @Id field for EnhanceEntity
SingularAttribute attrib = m.getIdAttribute();
Object rowKey = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, rowKey, relations);
}
return entity;
}
catch (PropertyAccessException e1)
{
throw new RuntimeException(e1);
}
} | [
"private",
"Object",
"populateEntityFromDataFrame",
"(",
"EntityMetadata",
"m",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"columnIndexMap",
",",
"Row",
"row",
")",
"{",
"try",
"{",
"// create entity instance",
"Object",
"entity",
"=",
"KunderaCoreUtils",
".",
"createNewInstance",
"(",
"m",
".",
"getEntityClazz",
"(",
")",
")",
";",
"// handle relations",
"Map",
"<",
"String",
",",
"Object",
">",
"relations",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"if",
"(",
"entity",
".",
"getClass",
"(",
")",
".",
"isAssignableFrom",
"(",
"EnhanceEntity",
".",
"class",
")",
")",
"{",
"relations",
"=",
"(",
"(",
"EnhanceEntity",
")",
"entity",
")",
".",
"getRelations",
"(",
")",
";",
"entity",
"=",
"(",
"(",
"EnhanceEntity",
")",
"entity",
")",
".",
"getEntity",
"(",
")",
";",
"}",
"// get a Set of attributes",
"MetamodelImpl",
"metaModel",
"=",
"(",
"MetamodelImpl",
")",
"kunderaMetadata",
".",
"getApplicationMetadata",
"(",
")",
".",
"getMetamodel",
"(",
"m",
".",
"getPersistenceUnit",
"(",
")",
")",
";",
"EntityType",
"entityType",
"=",
"metaModel",
".",
"entity",
"(",
"m",
".",
"getEntityClazz",
"(",
")",
")",
";",
"Set",
"<",
"Attribute",
">",
"attributes",
"=",
"(",
"(",
"AbstractManagedType",
")",
"entityType",
")",
".",
"getAttributes",
"(",
")",
";",
"// iterate over attributes and find its value",
"for",
"(",
"Attribute",
"attribute",
":",
"attributes",
")",
"{",
"String",
"columnName",
"=",
"getColumnName",
"(",
"attribute",
")",
";",
"Object",
"columnValue",
"=",
"row",
".",
"get",
"(",
"columnIndexMap",
".",
"get",
"(",
"columnName",
")",
")",
";",
"if",
"(",
"columnValue",
"!=",
"null",
")",
"{",
"Object",
"value",
"=",
"PropertyAccessorHelper",
".",
"fromSourceToTargetClass",
"(",
"attribute",
".",
"getJavaType",
"(",
")",
",",
"columnValue",
".",
"getClass",
"(",
")",
",",
"columnValue",
")",
";",
"PropertyAccessorHelper",
".",
"set",
"(",
"entity",
",",
"(",
"Field",
")",
"attribute",
".",
"getJavaMember",
"(",
")",
",",
"value",
")",
";",
"}",
"}",
"// find the value of @Id field for EnhanceEntity",
"SingularAttribute",
"attrib",
"=",
"m",
".",
"getIdAttribute",
"(",
")",
";",
"Object",
"rowKey",
"=",
"PropertyAccessorHelper",
".",
"getObject",
"(",
"entity",
",",
"(",
"Field",
")",
"attrib",
".",
"getJavaMember",
"(",
")",
")",
";",
"if",
"(",
"!",
"relations",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"new",
"EnhanceEntity",
"(",
"entity",
",",
"rowKey",
",",
"relations",
")",
";",
"}",
"return",
"entity",
";",
"}",
"catch",
"(",
"PropertyAccessException",
"e1",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e1",
")",
";",
"}",
"}"
] | Populate entity from data frame.
@param m
the m
@param columnIndexMap
the column index map
@param row
the row
@return the object | [
"Populate",
"entity",
"from",
"data",
"frame",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java#L121-L165 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWvWMatchScore | public void getWvWMatchScore(int worldID, Callback<WvWMatchScore> callback) throws NullPointerException {
"""
For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param worldID {@link World#id}
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@see WvWMatchScore WvW match score info
"""
gw2API.getWvWMatchScoreUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | java | public void getWvWMatchScore(int worldID, Callback<WvWMatchScore> callback) throws NullPointerException {
gw2API.getWvWMatchScoreUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | [
"public",
"void",
"getWvWMatchScore",
"(",
"int",
"worldID",
",",
"Callback",
"<",
"WvWMatchScore",
">",
"callback",
")",
"throws",
"NullPointerException",
"{",
"gw2API",
".",
"getWvWMatchScoreUsingWorld",
"(",
"Integer",
".",
"toString",
"(",
"worldID",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param worldID {@link World#id}
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@see WvWMatchScore WvW match score info | [
"For",
"more",
"info",
"on",
"WvW",
"matches",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"wvw",
"/",
"matches",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2666-L2668 |
strator-dev/greenpepper | samples-application/src/main/java/com/greenpepper/samples/application/phonebook/Country.java | Country.addState | public void addState(String name, String code) {
"""
<p>addState.</p>
@param name a {@link java.lang.String} object.
@param code a {@link java.lang.String} object.
"""
states.add(new State(this, name, code));
} | java | public void addState(String name, String code)
{
states.add(new State(this, name, code));
} | [
"public",
"void",
"addState",
"(",
"String",
"name",
",",
"String",
"code",
")",
"{",
"states",
".",
"add",
"(",
"new",
"State",
"(",
"this",
",",
"name",
",",
"code",
")",
")",
";",
"}"
] | <p>addState.</p>
@param name a {@link java.lang.String} object.
@param code a {@link java.lang.String} object. | [
"<p",
">",
"addState",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/samples-application/src/main/java/com/greenpepper/samples/application/phonebook/Country.java#L107-L110 |
federkasten/appbundle-maven-plugin | src/main/java/sh/tak/appbundler/CreateApplicationBundleMojo.java | CreateApplicationBundleMojo.copyResources | private List<String> copyResources(File targetDirectory, List<FileSet> fileSets) throws MojoExecutionException {
"""
Copies given resources to the build directory.
@param fileSets A list of FileSet objects that represent additional
resources to copy.
@throws MojoExecutionException In case of a resource copying error.
"""
ArrayList<String> addedFiles = new ArrayList<String>();
for (FileSet fileSet : fileSets) {
// Get the absolute base directory for the FileSet
File sourceDirectory = new File(fileSet.getDirectory());
if (!sourceDirectory.isAbsolute()) {
sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
}
if (!sourceDirectory.exists()) {
// If the requested directory does not exist, log it and carry on
getLog().warn("Specified source directory " + sourceDirectory.getPath() + " does not exist.");
continue;
}
List<String> includedFiles = scanFileSet(sourceDirectory, fileSet);
addedFiles.addAll(includedFiles);
getLog().info("Copying " + includedFiles.size() + " additional resource" + (includedFiles.size() > 1 ? "s" : ""));
for (String destination : includedFiles) {
File source = new File(sourceDirectory, destination);
File destinationFile = new File(targetDirectory, destination);
// Make sure that the directory we are copying into exists
destinationFile.getParentFile().mkdirs();
try {
FileUtils.copyFile(source, destinationFile);
destinationFile.setExecutable(fileSet.isExecutable(),false);
} catch (IOException e) {
throw new MojoExecutionException("Error copying additional resource " + source, e);
}
}
}
return addedFiles;
} | java | private List<String> copyResources(File targetDirectory, List<FileSet> fileSets) throws MojoExecutionException {
ArrayList<String> addedFiles = new ArrayList<String>();
for (FileSet fileSet : fileSets) {
// Get the absolute base directory for the FileSet
File sourceDirectory = new File(fileSet.getDirectory());
if (!sourceDirectory.isAbsolute()) {
sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
}
if (!sourceDirectory.exists()) {
// If the requested directory does not exist, log it and carry on
getLog().warn("Specified source directory " + sourceDirectory.getPath() + " does not exist.");
continue;
}
List<String> includedFiles = scanFileSet(sourceDirectory, fileSet);
addedFiles.addAll(includedFiles);
getLog().info("Copying " + includedFiles.size() + " additional resource" + (includedFiles.size() > 1 ? "s" : ""));
for (String destination : includedFiles) {
File source = new File(sourceDirectory, destination);
File destinationFile = new File(targetDirectory, destination);
// Make sure that the directory we are copying into exists
destinationFile.getParentFile().mkdirs();
try {
FileUtils.copyFile(source, destinationFile);
destinationFile.setExecutable(fileSet.isExecutable(),false);
} catch (IOException e) {
throw new MojoExecutionException("Error copying additional resource " + source, e);
}
}
}
return addedFiles;
} | [
"private",
"List",
"<",
"String",
">",
"copyResources",
"(",
"File",
"targetDirectory",
",",
"List",
"<",
"FileSet",
">",
"fileSets",
")",
"throws",
"MojoExecutionException",
"{",
"ArrayList",
"<",
"String",
">",
"addedFiles",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"FileSet",
"fileSet",
":",
"fileSets",
")",
"{",
"// Get the absolute base directory for the FileSet",
"File",
"sourceDirectory",
"=",
"new",
"File",
"(",
"fileSet",
".",
"getDirectory",
"(",
")",
")",
";",
"if",
"(",
"!",
"sourceDirectory",
".",
"isAbsolute",
"(",
")",
")",
"{",
"sourceDirectory",
"=",
"new",
"File",
"(",
"project",
".",
"getBasedir",
"(",
")",
",",
"sourceDirectory",
".",
"getPath",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"sourceDirectory",
".",
"exists",
"(",
")",
")",
"{",
"// If the requested directory does not exist, log it and carry on",
"getLog",
"(",
")",
".",
"warn",
"(",
"\"Specified source directory \"",
"+",
"sourceDirectory",
".",
"getPath",
"(",
")",
"+",
"\" does not exist.\"",
")",
";",
"continue",
";",
"}",
"List",
"<",
"String",
">",
"includedFiles",
"=",
"scanFileSet",
"(",
"sourceDirectory",
",",
"fileSet",
")",
";",
"addedFiles",
".",
"addAll",
"(",
"includedFiles",
")",
";",
"getLog",
"(",
")",
".",
"info",
"(",
"\"Copying \"",
"+",
"includedFiles",
".",
"size",
"(",
")",
"+",
"\" additional resource\"",
"+",
"(",
"includedFiles",
".",
"size",
"(",
")",
">",
"1",
"?",
"\"s\"",
":",
"\"\"",
")",
")",
";",
"for",
"(",
"String",
"destination",
":",
"includedFiles",
")",
"{",
"File",
"source",
"=",
"new",
"File",
"(",
"sourceDirectory",
",",
"destination",
")",
";",
"File",
"destinationFile",
"=",
"new",
"File",
"(",
"targetDirectory",
",",
"destination",
")",
";",
"// Make sure that the directory we are copying into exists",
"destinationFile",
".",
"getParentFile",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"try",
"{",
"FileUtils",
".",
"copyFile",
"(",
"source",
",",
"destinationFile",
")",
";",
"destinationFile",
".",
"setExecutable",
"(",
"fileSet",
".",
"isExecutable",
"(",
")",
",",
"false",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Error copying additional resource \"",
"+",
"source",
",",
"e",
")",
";",
"}",
"}",
"}",
"return",
"addedFiles",
";",
"}"
] | Copies given resources to the build directory.
@param fileSets A list of FileSet objects that represent additional
resources to copy.
@throws MojoExecutionException In case of a resource copying error. | [
"Copies",
"given",
"resources",
"to",
"the",
"build",
"directory",
"."
] | train | https://github.com/federkasten/appbundle-maven-plugin/blob/4cdaf7e0da95c83bc8a045ba40cb3eef45d25a5f/src/main/java/sh/tak/appbundler/CreateApplicationBundleMojo.java#L741-L779 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java | AccountsInner.listByResourceGroupAsync | public Observable<Page<DataLakeAnalyticsAccountBasicInner>> listByResourceGroupAsync(final String resourceGroupName, final String filter, final Integer top, final Integer skip, final String select, final String orderby, final Boolean count) {
"""
Gets the first page of Data Lake Analytics accounts, if any, within a specific resource group. This includes a link to the next page, if any.
@param resourceGroupName The name of the Azure resource group.
@param filter OData filter. Optional.
@param top The number of items to return. Optional.
@param skip The number of items to skip over before returning elements. Optional.
@param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional.
@param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional.
@param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<DataLakeAnalyticsAccountBasicInner> object
"""
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, filter, top, skip, select, orderby, count)
.map(new Func1<ServiceResponse<Page<DataLakeAnalyticsAccountBasicInner>>, Page<DataLakeAnalyticsAccountBasicInner>>() {
@Override
public Page<DataLakeAnalyticsAccountBasicInner> call(ServiceResponse<Page<DataLakeAnalyticsAccountBasicInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<DataLakeAnalyticsAccountBasicInner>> listByResourceGroupAsync(final String resourceGroupName, final String filter, final Integer top, final Integer skip, final String select, final String orderby, final Boolean count) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, filter, top, skip, select, orderby, count)
.map(new Func1<ServiceResponse<Page<DataLakeAnalyticsAccountBasicInner>>, Page<DataLakeAnalyticsAccountBasicInner>>() {
@Override
public Page<DataLakeAnalyticsAccountBasicInner> call(ServiceResponse<Page<DataLakeAnalyticsAccountBasicInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"DataLakeAnalyticsAccountBasicInner",
">",
">",
"listByResourceGroupAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"filter",
",",
"final",
"Integer",
"top",
",",
"final",
"Integer",
"skip",
",",
"final",
"String",
"select",
",",
"final",
"String",
"orderby",
",",
"final",
"Boolean",
"count",
")",
"{",
"return",
"listByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"filter",
",",
"top",
",",
"skip",
",",
"select",
",",
"orderby",
",",
"count",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"DataLakeAnalyticsAccountBasicInner",
">",
">",
",",
"Page",
"<",
"DataLakeAnalyticsAccountBasicInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"DataLakeAnalyticsAccountBasicInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"DataLakeAnalyticsAccountBasicInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the first page of Data Lake Analytics accounts, if any, within a specific resource group. This includes a link to the next page, if any.
@param resourceGroupName The name of the Azure resource group.
@param filter OData filter. Optional.
@param top The number of items to return. Optional.
@param skip The number of items to skip over before returning elements. Optional.
@param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional.
@param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional.
@param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<DataLakeAnalyticsAccountBasicInner> object | [
"Gets",
"the",
"first",
"page",
"of",
"Data",
"Lake",
"Analytics",
"accounts",
"if",
"any",
"within",
"a",
"specific",
"resource",
"group",
".",
"This",
"includes",
"a",
"link",
"to",
"the",
"next",
"page",
"if",
"any",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java#L543-L551 |
elki-project/elki | elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/timeseries/DTWDistanceFunction.java | DTWDistanceFunction.firstRow | protected void firstRow(double[] buf, int band, NumberVector v1, NumberVector v2, int dim2) {
"""
Fill the first row.
@param buf Buffer
@param band Bandwidth
@param v1 First vector
@param v2 Second vector
@param dim2 Dimensionality of second
"""
// First cell:
final double val1 = v1.doubleValue(0);
buf[0] = delta(val1, v2.doubleValue(0));
// Width of valid area:
final int w = (band >= dim2) ? dim2 - 1 : band;
// Fill remaining part of buffer:
for(int j = 1; j <= w; j++) {
buf[j] = buf[j - 1] + delta(val1, v2.doubleValue(j));
}
} | java | protected void firstRow(double[] buf, int band, NumberVector v1, NumberVector v2, int dim2) {
// First cell:
final double val1 = v1.doubleValue(0);
buf[0] = delta(val1, v2.doubleValue(0));
// Width of valid area:
final int w = (band >= dim2) ? dim2 - 1 : band;
// Fill remaining part of buffer:
for(int j = 1; j <= w; j++) {
buf[j] = buf[j - 1] + delta(val1, v2.doubleValue(j));
}
} | [
"protected",
"void",
"firstRow",
"(",
"double",
"[",
"]",
"buf",
",",
"int",
"band",
",",
"NumberVector",
"v1",
",",
"NumberVector",
"v2",
",",
"int",
"dim2",
")",
"{",
"// First cell:",
"final",
"double",
"val1",
"=",
"v1",
".",
"doubleValue",
"(",
"0",
")",
";",
"buf",
"[",
"0",
"]",
"=",
"delta",
"(",
"val1",
",",
"v2",
".",
"doubleValue",
"(",
"0",
")",
")",
";",
"// Width of valid area:",
"final",
"int",
"w",
"=",
"(",
"band",
">=",
"dim2",
")",
"?",
"dim2",
"-",
"1",
":",
"band",
";",
"// Fill remaining part of buffer:",
"for",
"(",
"int",
"j",
"=",
"1",
";",
"j",
"<=",
"w",
";",
"j",
"++",
")",
"{",
"buf",
"[",
"j",
"]",
"=",
"buf",
"[",
"j",
"-",
"1",
"]",
"+",
"delta",
"(",
"val1",
",",
"v2",
".",
"doubleValue",
"(",
"j",
")",
")",
";",
"}",
"}"
] | Fill the first row.
@param buf Buffer
@param band Bandwidth
@param v1 First vector
@param v2 Second vector
@param dim2 Dimensionality of second | [
"Fill",
"the",
"first",
"row",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/timeseries/DTWDistanceFunction.java#L137-L148 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java | AdHocCommandManager.respondError | private static IQ respondError(AdHocCommandData response,
StanzaError.Condition condition) {
"""
Responds an error with an specific condition.
@param response the response to send.
@param condition the condition of the error.
@throws NotConnectedException
"""
return respondError(response, StanzaError.getBuilder(condition));
} | java | private static IQ respondError(AdHocCommandData response,
StanzaError.Condition condition) {
return respondError(response, StanzaError.getBuilder(condition));
} | [
"private",
"static",
"IQ",
"respondError",
"(",
"AdHocCommandData",
"response",
",",
"StanzaError",
".",
"Condition",
"condition",
")",
"{",
"return",
"respondError",
"(",
"response",
",",
"StanzaError",
".",
"getBuilder",
"(",
"condition",
")",
")",
";",
"}"
] | Responds an error with an specific condition.
@param response the response to send.
@param condition the condition of the error.
@throws NotConnectedException | [
"Responds",
"an",
"error",
"with",
"an",
"specific",
"condition",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java#L568-L571 |
netheosgithub/pcs_api | java/src/main/java/net/netheos/pcsapi/models/CDownloadRequest.java | CDownloadRequest.getHttpHeaders | public Headers getHttpHeaders() {
"""
Get the HTTP headers to be used for download request.
Default implementation only handles Range header.
@return The headers
"""
Headers headers = new Headers();
if ( byteRange != null ) {
StringBuilder rangeBuilder = new StringBuilder( "bytes=" );
long start;
if ( byteRange.offset >= 0 ) {
rangeBuilder.append( byteRange.offset );
start = byteRange.offset;
} else {
start = 1;
}
rangeBuilder.append( "-" );
if ( byteRange.length > 0 ) {
rangeBuilder.append( start + byteRange.length - 1 );
}
Header rangeHeader = new BasicHeader( "Range", rangeBuilder.toString() );
headers.addHeader( rangeHeader );
}
return headers;
} | java | public Headers getHttpHeaders()
{
Headers headers = new Headers();
if ( byteRange != null ) {
StringBuilder rangeBuilder = new StringBuilder( "bytes=" );
long start;
if ( byteRange.offset >= 0 ) {
rangeBuilder.append( byteRange.offset );
start = byteRange.offset;
} else {
start = 1;
}
rangeBuilder.append( "-" );
if ( byteRange.length > 0 ) {
rangeBuilder.append( start + byteRange.length - 1 );
}
Header rangeHeader = new BasicHeader( "Range", rangeBuilder.toString() );
headers.addHeader( rangeHeader );
}
return headers;
} | [
"public",
"Headers",
"getHttpHeaders",
"(",
")",
"{",
"Headers",
"headers",
"=",
"new",
"Headers",
"(",
")",
";",
"if",
"(",
"byteRange",
"!=",
"null",
")",
"{",
"StringBuilder",
"rangeBuilder",
"=",
"new",
"StringBuilder",
"(",
"\"bytes=\"",
")",
";",
"long",
"start",
";",
"if",
"(",
"byteRange",
".",
"offset",
">=",
"0",
")",
"{",
"rangeBuilder",
".",
"append",
"(",
"byteRange",
".",
"offset",
")",
";",
"start",
"=",
"byteRange",
".",
"offset",
";",
"}",
"else",
"{",
"start",
"=",
"1",
";",
"}",
"rangeBuilder",
".",
"append",
"(",
"\"-\"",
")",
";",
"if",
"(",
"byteRange",
".",
"length",
">",
"0",
")",
"{",
"rangeBuilder",
".",
"append",
"(",
"start",
"+",
"byteRange",
".",
"length",
"-",
"1",
")",
";",
"}",
"Header",
"rangeHeader",
"=",
"new",
"BasicHeader",
"(",
"\"Range\"",
",",
"rangeBuilder",
".",
"toString",
"(",
")",
")",
";",
"headers",
".",
"addHeader",
"(",
"rangeHeader",
")",
";",
"}",
"return",
"headers",
";",
"}"
] | Get the HTTP headers to be used for download request.
Default implementation only handles Range header.
@return The headers | [
"Get",
"the",
"HTTP",
"headers",
"to",
"be",
"used",
"for",
"download",
"request",
"."
] | train | https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/models/CDownloadRequest.java#L62-L85 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getCertificateIssuersWithServiceResponseAsync | public Observable<ServiceResponse<Page<CertificateIssuerItem>>> getCertificateIssuersWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) {
"""
List certificate issuers for a specified key vault.
The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. This operation requires the certificates/manageissuers/getissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CertificateIssuerItem> object
"""
return getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults)
.concatMap(new Func1<ServiceResponse<Page<CertificateIssuerItem>>, Observable<ServiceResponse<Page<CertificateIssuerItem>>>>() {
@Override
public Observable<ServiceResponse<Page<CertificateIssuerItem>>> call(ServiceResponse<Page<CertificateIssuerItem>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<CertificateIssuerItem>>> getCertificateIssuersWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) {
return getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults)
.concatMap(new Func1<ServiceResponse<Page<CertificateIssuerItem>>, Observable<ServiceResponse<Page<CertificateIssuerItem>>>>() {
@Override
public Observable<ServiceResponse<Page<CertificateIssuerItem>>> call(ServiceResponse<Page<CertificateIssuerItem>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getCertificateIssuersNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"CertificateIssuerItem",
">",
">",
">",
"getCertificateIssuersWithServiceResponseAsync",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"Integer",
"maxresults",
")",
"{",
"return",
"getCertificateIssuersSinglePageAsync",
"(",
"vaultBaseUrl",
",",
"maxresults",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"CertificateIssuerItem",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"CertificateIssuerItem",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"CertificateIssuerItem",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"CertificateIssuerItem",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"getCertificateIssuersNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | List certificate issuers for a specified key vault.
The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. This operation requires the certificates/manageissuers/getissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CertificateIssuerItem> object | [
"List",
"certificate",
"issuers",
"for",
"a",
"specified",
"key",
"vault",
".",
"The",
"GetCertificateIssuers",
"operation",
"returns",
"the",
"set",
"of",
"certificate",
"issuer",
"resources",
"in",
"the",
"specified",
"key",
"vault",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"manageissuers",
"/",
"getissuers",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5836-L5848 |
google/closure-compiler | src/com/google/javascript/jscomp/SideEffectsAnalysis.java | SideEffectsAnalysis.nodeHasAncestor | private static boolean nodeHasAncestor(Node node, Node possibleAncestor) {
"""
Returns true if {@code possibleAncestor} is an ancestor of{@code node}.
A node is not considered to be an ancestor of itself.
"""
// Note node is not in node.getAncestors()
for (Node ancestor : node.getAncestors()) {
if (ancestor == possibleAncestor) {
return true;
}
}
return false;
} | java | private static boolean nodeHasAncestor(Node node, Node possibleAncestor) {
// Note node is not in node.getAncestors()
for (Node ancestor : node.getAncestors()) {
if (ancestor == possibleAncestor) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"nodeHasAncestor",
"(",
"Node",
"node",
",",
"Node",
"possibleAncestor",
")",
"{",
"// Note node is not in node.getAncestors()",
"for",
"(",
"Node",
"ancestor",
":",
"node",
".",
"getAncestors",
"(",
")",
")",
"{",
"if",
"(",
"ancestor",
"==",
"possibleAncestor",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if {@code possibleAncestor} is an ancestor of{@code node}.
A node is not considered to be an ancestor of itself. | [
"Returns",
"true",
"if",
"{"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SideEffectsAnalysis.java#L379-L389 |
anotheria/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/producers/action/ShowProducerAction.java | ShowProducerAction.populateStats | private void populateStats(final StatDecoratorBean statDecoratorBean, final List<StatLineAO> allStatLines, final StatBeanSortType sortType) {
"""
Allows to set all stats to decorator except cumulated stat.
Stats will be sorted using given sort type.
@param statDecoratorBean {@link StatDecoratorBean}
@param allStatLines list of {@link StatLineAO}, all stats present in producer
@param sortType {@link StatBeanSortType}
"""
if (allStatLines == null || allStatLines.isEmpty()) {
LOGGER.warn("Producer's stats are empty");
return;
}
final int cumulatedIndex = getCumulatedIndex(allStatLines);
// stats
int allStatLinesSize = allStatLines.size();
final List<StatBean> statBeans = new ArrayList<>(allStatLinesSize);
for (int i = 0; i < allStatLinesSize; i++) {
if (i == cumulatedIndex)
continue;
final StatLineAO line = allStatLines.get(i);
final List<StatValueAO> statValues = line.getValues();
final StatBean statBean = new StatBean();
statBean.setName(line.getStatName());
statBean.setValues(statValues);
statBeans.add(statBean);
}
// sort stat beans
StaticQuickSorter.sort(statBeans, sortType);
// set stats
statDecoratorBean.setStats(statBeans);
} | java | private void populateStats(final StatDecoratorBean statDecoratorBean, final List<StatLineAO> allStatLines, final StatBeanSortType sortType) {
if (allStatLines == null || allStatLines.isEmpty()) {
LOGGER.warn("Producer's stats are empty");
return;
}
final int cumulatedIndex = getCumulatedIndex(allStatLines);
// stats
int allStatLinesSize = allStatLines.size();
final List<StatBean> statBeans = new ArrayList<>(allStatLinesSize);
for (int i = 0; i < allStatLinesSize; i++) {
if (i == cumulatedIndex)
continue;
final StatLineAO line = allStatLines.get(i);
final List<StatValueAO> statValues = line.getValues();
final StatBean statBean = new StatBean();
statBean.setName(line.getStatName());
statBean.setValues(statValues);
statBeans.add(statBean);
}
// sort stat beans
StaticQuickSorter.sort(statBeans, sortType);
// set stats
statDecoratorBean.setStats(statBeans);
} | [
"private",
"void",
"populateStats",
"(",
"final",
"StatDecoratorBean",
"statDecoratorBean",
",",
"final",
"List",
"<",
"StatLineAO",
">",
"allStatLines",
",",
"final",
"StatBeanSortType",
"sortType",
")",
"{",
"if",
"(",
"allStatLines",
"==",
"null",
"||",
"allStatLines",
".",
"isEmpty",
"(",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Producer's stats are empty\"",
")",
";",
"return",
";",
"}",
"final",
"int",
"cumulatedIndex",
"=",
"getCumulatedIndex",
"(",
"allStatLines",
")",
";",
"// stats",
"int",
"allStatLinesSize",
"=",
"allStatLines",
".",
"size",
"(",
")",
";",
"final",
"List",
"<",
"StatBean",
">",
"statBeans",
"=",
"new",
"ArrayList",
"<>",
"(",
"allStatLinesSize",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"allStatLinesSize",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"cumulatedIndex",
")",
"continue",
";",
"final",
"StatLineAO",
"line",
"=",
"allStatLines",
".",
"get",
"(",
"i",
")",
";",
"final",
"List",
"<",
"StatValueAO",
">",
"statValues",
"=",
"line",
".",
"getValues",
"(",
")",
";",
"final",
"StatBean",
"statBean",
"=",
"new",
"StatBean",
"(",
")",
";",
"statBean",
".",
"setName",
"(",
"line",
".",
"getStatName",
"(",
")",
")",
";",
"statBean",
".",
"setValues",
"(",
"statValues",
")",
";",
"statBeans",
".",
"add",
"(",
"statBean",
")",
";",
"}",
"// sort stat beans",
"StaticQuickSorter",
".",
"sort",
"(",
"statBeans",
",",
"sortType",
")",
";",
"// set stats",
"statDecoratorBean",
".",
"setStats",
"(",
"statBeans",
")",
";",
"}"
] | Allows to set all stats to decorator except cumulated stat.
Stats will be sorted using given sort type.
@param statDecoratorBean {@link StatDecoratorBean}
@param allStatLines list of {@link StatLineAO}, all stats present in producer
@param sortType {@link StatBeanSortType} | [
"Allows",
"to",
"set",
"all",
"stats",
"to",
"decorator",
"except",
"cumulated",
"stat",
".",
"Stats",
"will",
"be",
"sorted",
"using",
"given",
"sort",
"type",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-webui/src/main/java/net/anotheria/moskito/webui/producers/action/ShowProducerAction.java#L194-L223 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AoImplCodeGen.java | AoImplCodeGen.writeImport | @Override
public void writeImport(Definition def, Writer out) throws IOException {
"""
Output class import
@param def definition
@param out Writer
@throws IOException ioException
"""
out.write("package " + def.getRaPackage() + ";\n\n");
if (def.isAdminObjectImplRaAssociation())
{
out.write("import java.io.Serializable;\n\n");
out.write("import javax.naming.NamingException;\n");
out.write("import javax.naming.Reference;\n\n");
out.write("import javax.resource.Referenceable;\n");
}
if (def.isUseAnnotation())
{
out.write("import javax.resource.spi.AdministeredObject;\n");
out.write("import javax.resource.spi.ConfigProperty;\n");
}
if (def.isAdminObjectImplRaAssociation())
{
out.write("import javax.resource.spi.ResourceAdapter;\n");
out.write("import javax.resource.spi.ResourceAdapterAssociation;\n");
}
writeEol(out);
} | java | @Override
public void writeImport(Definition def, Writer out) throws IOException
{
out.write("package " + def.getRaPackage() + ";\n\n");
if (def.isAdminObjectImplRaAssociation())
{
out.write("import java.io.Serializable;\n\n");
out.write("import javax.naming.NamingException;\n");
out.write("import javax.naming.Reference;\n\n");
out.write("import javax.resource.Referenceable;\n");
}
if (def.isUseAnnotation())
{
out.write("import javax.resource.spi.AdministeredObject;\n");
out.write("import javax.resource.spi.ConfigProperty;\n");
}
if (def.isAdminObjectImplRaAssociation())
{
out.write("import javax.resource.spi.ResourceAdapter;\n");
out.write("import javax.resource.spi.ResourceAdapterAssociation;\n");
}
writeEol(out);
} | [
"@",
"Override",
"public",
"void",
"writeImport",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"\"package \"",
"+",
"def",
".",
"getRaPackage",
"(",
")",
"+",
"\";\\n\\n\"",
")",
";",
"if",
"(",
"def",
".",
"isAdminObjectImplRaAssociation",
"(",
")",
")",
"{",
"out",
".",
"write",
"(",
"\"import java.io.Serializable;\\n\\n\"",
")",
";",
"out",
".",
"write",
"(",
"\"import javax.naming.NamingException;\\n\"",
")",
";",
"out",
".",
"write",
"(",
"\"import javax.naming.Reference;\\n\\n\"",
")",
";",
"out",
".",
"write",
"(",
"\"import javax.resource.Referenceable;\\n\"",
")",
";",
"}",
"if",
"(",
"def",
".",
"isUseAnnotation",
"(",
")",
")",
"{",
"out",
".",
"write",
"(",
"\"import javax.resource.spi.AdministeredObject;\\n\"",
")",
";",
"out",
".",
"write",
"(",
"\"import javax.resource.spi.ConfigProperty;\\n\"",
")",
";",
"}",
"if",
"(",
"def",
".",
"isAdminObjectImplRaAssociation",
"(",
")",
")",
"{",
"out",
".",
"write",
"(",
"\"import javax.resource.spi.ResourceAdapter;\\n\"",
")",
";",
"out",
".",
"write",
"(",
"\"import javax.resource.spi.ResourceAdapterAssociation;\\n\"",
")",
";",
"}",
"writeEol",
"(",
"out",
")",
";",
"}"
] | Output class import
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"class",
"import"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AoImplCodeGen.java#L152-L174 |
lamydev/Android-Notification | core/src/zemin/notification/NotificationBoard.java | NotificationBoard.setBoardPadding | public void setBoardPadding(int l, int t, int r, int b) {
"""
Set the margin of the entire board.
@param l
@param t
@param r
@param b
"""
mContentView.setPadding(l, t, r, b);
} | java | public void setBoardPadding(int l, int t, int r, int b) {
mContentView.setPadding(l, t, r, b);
} | [
"public",
"void",
"setBoardPadding",
"(",
"int",
"l",
",",
"int",
"t",
",",
"int",
"r",
",",
"int",
"b",
")",
"{",
"mContentView",
".",
"setPadding",
"(",
"l",
",",
"t",
",",
"r",
",",
"b",
")",
";",
"}"
] | Set the margin of the entire board.
@param l
@param t
@param r
@param b | [
"Set",
"the",
"margin",
"of",
"the",
"entire",
"board",
"."
] | train | https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationBoard.java#L1087-L1089 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java | TypeUtility.endStringConversion | public static void endStringConversion(Builder methodBuilder, TypeName typeMirror) {
"""
generate end string to translate in code to used in content value or parameter need to be converted in string through String.valueOf
@param methodBuilder
the method builder
@param typeMirror
the type mirror
"""
SQLTransform transform = SQLTransformer.lookup(typeMirror);
switch (transform.getColumnType()) {
case TEXT:
return;
case BLOB:
methodBuilder.addCode(",$T.UTF_8)", StandardCharsets.class);
break;
case INTEGER:
case REAL:
methodBuilder.addCode(")");
break;
default:
break;
}
} | java | public static void endStringConversion(Builder methodBuilder, TypeName typeMirror) {
SQLTransform transform = SQLTransformer.lookup(typeMirror);
switch (transform.getColumnType()) {
case TEXT:
return;
case BLOB:
methodBuilder.addCode(",$T.UTF_8)", StandardCharsets.class);
break;
case INTEGER:
case REAL:
methodBuilder.addCode(")");
break;
default:
break;
}
} | [
"public",
"static",
"void",
"endStringConversion",
"(",
"Builder",
"methodBuilder",
",",
"TypeName",
"typeMirror",
")",
"{",
"SQLTransform",
"transform",
"=",
"SQLTransformer",
".",
"lookup",
"(",
"typeMirror",
")",
";",
"switch",
"(",
"transform",
".",
"getColumnType",
"(",
")",
")",
"{",
"case",
"TEXT",
":",
"return",
";",
"case",
"BLOB",
":",
"methodBuilder",
".",
"addCode",
"(",
"\",$T.UTF_8)\"",
",",
"StandardCharsets",
".",
"class",
")",
";",
"break",
";",
"case",
"INTEGER",
":",
"case",
"REAL",
":",
"methodBuilder",
".",
"addCode",
"(",
"\")\"",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}"
] | generate end string to translate in code to used in content value or parameter need to be converted in string through String.valueOf
@param methodBuilder
the method builder
@param typeMirror
the type mirror | [
"generate",
"end",
"string",
"to",
"translate",
"in",
"code",
"to",
"used",
"in",
"content",
"value",
"or",
"parameter",
"need",
"to",
"be",
"converted",
"in",
"string",
"through",
"String",
".",
"valueOf"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java#L431-L447 |
kiswanij/jk-util | src/main/java/com/jk/util/JKDateTimeUtil.java | JKDateTimeUtil.getDayDifference | public static long getDayDifference(Date startDate, Date endDate) {
"""
Gets the day difference.
@param startDate the start date
@param endDate the end date
@return the day difference
"""
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = TimeUnit.MILLISECONDS.toDays(diffTime);
return diffDays;
} | java | public static long getDayDifference(Date startDate, Date endDate) {
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = TimeUnit.MILLISECONDS.toDays(diffTime);
return diffDays;
} | [
"public",
"static",
"long",
"getDayDifference",
"(",
"Date",
"startDate",
",",
"Date",
"endDate",
")",
"{",
"long",
"startTime",
"=",
"startDate",
".",
"getTime",
"(",
")",
";",
"long",
"endTime",
"=",
"endDate",
".",
"getTime",
"(",
")",
";",
"long",
"diffTime",
"=",
"endTime",
"-",
"startTime",
";",
"long",
"diffDays",
"=",
"TimeUnit",
".",
"MILLISECONDS",
".",
"toDays",
"(",
"diffTime",
")",
";",
"return",
"diffDays",
";",
"}"
] | Gets the day difference.
@param startDate the start date
@param endDate the end date
@return the day difference | [
"Gets",
"the",
"day",
"difference",
"."
] | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L427-L433 |
deeplearning4j/deeplearning4j | datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/RandomCropTransform.java | RandomCropTransform.doTransform | @Override
protected ImageWritable doTransform(ImageWritable image, Random random) {
"""
Takes an image and returns a randomly cropped image.
@param image to transform, null == end of stream
@param random object to use (or null for deterministic)
@return transformed image
"""
if (image == null) {
return null;
}
// ensure that transform is valid
if (image.getFrame().imageHeight < outputHeight || image.getFrame().imageWidth < outputWidth)
throw new UnsupportedOperationException(
"Output height/width cannot be more than the input image. Requested: " + outputHeight + "+x"
+ outputWidth + ", got " + image.getFrame().imageHeight + "+x"
+ image.getFrame().imageWidth);
// determine boundary to place random offset
int cropTop = image.getFrame().imageHeight - outputHeight;
int cropLeft = image.getFrame().imageWidth - outputWidth;
Mat mat = converter.convert(image.getFrame());
int top = rng.nextInt(cropTop + 1);
int left = rng.nextInt(cropLeft + 1);
y = Math.min(top, mat.rows() - 1);
x = Math.min(left, mat.cols() - 1);
Mat result = mat.apply(new Rect(x, y, outputWidth, outputHeight));
return new ImageWritable(converter.convert(result));
} | java | @Override
protected ImageWritable doTransform(ImageWritable image, Random random) {
if (image == null) {
return null;
}
// ensure that transform is valid
if (image.getFrame().imageHeight < outputHeight || image.getFrame().imageWidth < outputWidth)
throw new UnsupportedOperationException(
"Output height/width cannot be more than the input image. Requested: " + outputHeight + "+x"
+ outputWidth + ", got " + image.getFrame().imageHeight + "+x"
+ image.getFrame().imageWidth);
// determine boundary to place random offset
int cropTop = image.getFrame().imageHeight - outputHeight;
int cropLeft = image.getFrame().imageWidth - outputWidth;
Mat mat = converter.convert(image.getFrame());
int top = rng.nextInt(cropTop + 1);
int left = rng.nextInt(cropLeft + 1);
y = Math.min(top, mat.rows() - 1);
x = Math.min(left, mat.cols() - 1);
Mat result = mat.apply(new Rect(x, y, outputWidth, outputHeight));
return new ImageWritable(converter.convert(result));
} | [
"@",
"Override",
"protected",
"ImageWritable",
"doTransform",
"(",
"ImageWritable",
"image",
",",
"Random",
"random",
")",
"{",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// ensure that transform is valid",
"if",
"(",
"image",
".",
"getFrame",
"(",
")",
".",
"imageHeight",
"<",
"outputHeight",
"||",
"image",
".",
"getFrame",
"(",
")",
".",
"imageWidth",
"<",
"outputWidth",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Output height/width cannot be more than the input image. Requested: \"",
"+",
"outputHeight",
"+",
"\"+x\"",
"+",
"outputWidth",
"+",
"\", got \"",
"+",
"image",
".",
"getFrame",
"(",
")",
".",
"imageHeight",
"+",
"\"+x\"",
"+",
"image",
".",
"getFrame",
"(",
")",
".",
"imageWidth",
")",
";",
"// determine boundary to place random offset",
"int",
"cropTop",
"=",
"image",
".",
"getFrame",
"(",
")",
".",
"imageHeight",
"-",
"outputHeight",
";",
"int",
"cropLeft",
"=",
"image",
".",
"getFrame",
"(",
")",
".",
"imageWidth",
"-",
"outputWidth",
";",
"Mat",
"mat",
"=",
"converter",
".",
"convert",
"(",
"image",
".",
"getFrame",
"(",
")",
")",
";",
"int",
"top",
"=",
"rng",
".",
"nextInt",
"(",
"cropTop",
"+",
"1",
")",
";",
"int",
"left",
"=",
"rng",
".",
"nextInt",
"(",
"cropLeft",
"+",
"1",
")",
";",
"y",
"=",
"Math",
".",
"min",
"(",
"top",
",",
"mat",
".",
"rows",
"(",
")",
"-",
"1",
")",
";",
"x",
"=",
"Math",
".",
"min",
"(",
"left",
",",
"mat",
".",
"cols",
"(",
")",
"-",
"1",
")",
";",
"Mat",
"result",
"=",
"mat",
".",
"apply",
"(",
"new",
"Rect",
"(",
"x",
",",
"y",
",",
"outputWidth",
",",
"outputHeight",
")",
")",
";",
"return",
"new",
"ImageWritable",
"(",
"converter",
".",
"convert",
"(",
"result",
")",
")",
";",
"}"
] | Takes an image and returns a randomly cropped image.
@param image to transform, null == end of stream
@param random object to use (or null for deterministic)
@return transformed image | [
"Takes",
"an",
"image",
"and",
"returns",
"a",
"randomly",
"cropped",
"image",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/RandomCropTransform.java#L74-L100 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/profiler/ProfilerFactory.java | ProfilerFactory.newInstance | public static Object newInstance(Object obj) {
"""
Function wraps Object into Profiling Java Proxy.
Used to wrap QueryRunner instance with Java Proxy
@param obj Object which would be wrapped into Profiling Proxy
@return Java Proxy with wrapped input object
"""
if (MjdbcLogger.isSLF4jAvailable() == true && MjdbcLogger.isSLF4jImplementationAvailable() == false) {
// Logging depends on slf4j. If it haven't found any logging system
// connected - it is turned off.
// In such case there is no need to output profiling information as
// it won't be printed out.
return obj;
} else {
if (MjdbcConfig.isProfilerEnabled() == true) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new BaseInvocationHandler(obj, MjdbcConfig.getProfilerOutputFormat()));
} else {
return obj;
}
}
} | java | public static Object newInstance(Object obj) {
if (MjdbcLogger.isSLF4jAvailable() == true && MjdbcLogger.isSLF4jImplementationAvailable() == false) {
// Logging depends on slf4j. If it haven't found any logging system
// connected - it is turned off.
// In such case there is no need to output profiling information as
// it won't be printed out.
return obj;
} else {
if (MjdbcConfig.isProfilerEnabled() == true) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new BaseInvocationHandler(obj, MjdbcConfig.getProfilerOutputFormat()));
} else {
return obj;
}
}
} | [
"public",
"static",
"Object",
"newInstance",
"(",
"Object",
"obj",
")",
"{",
"if",
"(",
"MjdbcLogger",
".",
"isSLF4jAvailable",
"(",
")",
"==",
"true",
"&&",
"MjdbcLogger",
".",
"isSLF4jImplementationAvailable",
"(",
")",
"==",
"false",
")",
"{",
"// Logging depends on slf4j. If it haven't found any logging system",
"// connected - it is turned off.",
"// In such case there is no need to output profiling information as",
"// it won't be printed out.",
"return",
"obj",
";",
"}",
"else",
"{",
"if",
"(",
"MjdbcConfig",
".",
"isProfilerEnabled",
"(",
")",
"==",
"true",
")",
"{",
"return",
"java",
".",
"lang",
".",
"reflect",
".",
"Proxy",
".",
"newProxyInstance",
"(",
"obj",
".",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
",",
"obj",
".",
"getClass",
"(",
")",
".",
"getInterfaces",
"(",
")",
",",
"new",
"BaseInvocationHandler",
"(",
"obj",
",",
"MjdbcConfig",
".",
"getProfilerOutputFormat",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"return",
"obj",
";",
"}",
"}",
"}"
] | Function wraps Object into Profiling Java Proxy.
Used to wrap QueryRunner instance with Java Proxy
@param obj Object which would be wrapped into Profiling Proxy
@return Java Proxy with wrapped input object | [
"Function",
"wraps",
"Object",
"into",
"Profiling",
"Java",
"Proxy",
".",
"Used",
"to",
"wrap",
"QueryRunner",
"instance",
"with",
"Java",
"Proxy"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/profiler/ProfilerFactory.java#L36-L52 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/render/Responsive.java | Responsive.getSize | private static String getSize(IResponsiveLabel r, Sizes size) {
"""
Decode col sizes between two way of definition
@param col
@param size
@return
"""
String colSize = "-1";
switch(size) {
case xs:
colSize = r.getLabelColXs();
if(colSize.equals("-1")) colSize = r.getLabelTinyScreen();
break;
case sm:
colSize = r.getLabelColSm();
if(colSize.equals("-1")) colSize = r.getLabelSmallScreen();
break;
case md:
colSize = r.getLabelColMd();
if(colSize.equals("-1")) colSize = r.getLabelMediumScreen();
break;
case lg:
colSize = r.getLabelColLg();
if(colSize.equals("-1")) colSize = r.getLabelLargeScreen();
break;
}
return colSize;
} | java | private static String getSize(IResponsiveLabel r, Sizes size) {
String colSize = "-1";
switch(size) {
case xs:
colSize = r.getLabelColXs();
if(colSize.equals("-1")) colSize = r.getLabelTinyScreen();
break;
case sm:
colSize = r.getLabelColSm();
if(colSize.equals("-1")) colSize = r.getLabelSmallScreen();
break;
case md:
colSize = r.getLabelColMd();
if(colSize.equals("-1")) colSize = r.getLabelMediumScreen();
break;
case lg:
colSize = r.getLabelColLg();
if(colSize.equals("-1")) colSize = r.getLabelLargeScreen();
break;
}
return colSize;
} | [
"private",
"static",
"String",
"getSize",
"(",
"IResponsiveLabel",
"r",
",",
"Sizes",
"size",
")",
"{",
"String",
"colSize",
"=",
"\"-1\"",
";",
"switch",
"(",
"size",
")",
"{",
"case",
"xs",
":",
"colSize",
"=",
"r",
".",
"getLabelColXs",
"(",
")",
";",
"if",
"(",
"colSize",
".",
"equals",
"(",
"\"-1\"",
")",
")",
"colSize",
"=",
"r",
".",
"getLabelTinyScreen",
"(",
")",
";",
"break",
";",
"case",
"sm",
":",
"colSize",
"=",
"r",
".",
"getLabelColSm",
"(",
")",
";",
"if",
"(",
"colSize",
".",
"equals",
"(",
"\"-1\"",
")",
")",
"colSize",
"=",
"r",
".",
"getLabelSmallScreen",
"(",
")",
";",
"break",
";",
"case",
"md",
":",
"colSize",
"=",
"r",
".",
"getLabelColMd",
"(",
")",
";",
"if",
"(",
"colSize",
".",
"equals",
"(",
"\"-1\"",
")",
")",
"colSize",
"=",
"r",
".",
"getLabelMediumScreen",
"(",
")",
";",
"break",
";",
"case",
"lg",
":",
"colSize",
"=",
"r",
".",
"getLabelColLg",
"(",
")",
";",
"if",
"(",
"colSize",
".",
"equals",
"(",
"\"-1\"",
")",
")",
"colSize",
"=",
"r",
".",
"getLabelLargeScreen",
"(",
")",
";",
"break",
";",
"}",
"return",
"colSize",
";",
"}"
] | Decode col sizes between two way of definition
@param col
@param size
@return | [
"Decode",
"col",
"sizes",
"between",
"two",
"way",
"of",
"definition"
] | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/render/Responsive.java#L131-L152 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForView | public boolean waitForView(int id, int minimumNumberOfMatches, int timeout) {
"""
Waits for a View matching the specified resource id.
@param id the R.id of the {@link View} to wait for
@param minimumNumberOfMatches the minimum number of matches that are expected to be found. {@code 0} means any number of matches
@param timeout the amount of time in milliseconds to wait
@return {@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+id+", "+minimumNumberOfMatches+", "+timeout+")");
}
return waitForView(id, minimumNumberOfMatches, timeout, true);
} | java | public boolean waitForView(int id, int minimumNumberOfMatches, int timeout){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForView("+id+", "+minimumNumberOfMatches+", "+timeout+")");
}
return waitForView(id, minimumNumberOfMatches, timeout, true);
} | [
"public",
"boolean",
"waitForView",
"(",
"int",
"id",
",",
"int",
"minimumNumberOfMatches",
",",
"int",
"timeout",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"waitForView(\"",
"+",
"id",
"+",
"\", \"",
"+",
"minimumNumberOfMatches",
"+",
"\", \"",
"+",
"timeout",
"+",
"\")\"",
")",
";",
"}",
"return",
"waitForView",
"(",
"id",
",",
"minimumNumberOfMatches",
",",
"timeout",
",",
"true",
")",
";",
"}"
] | Waits for a View matching the specified resource id.
@param id the R.id of the {@link View} to wait for
@param minimumNumberOfMatches the minimum number of matches that are expected to be found. {@code 0} means any number of matches
@param timeout the amount of time in milliseconds to wait
@return {@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout | [
"Waits",
"for",
"a",
"View",
"matching",
"the",
"specified",
"resource",
"id",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L468-L474 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java | ASMUtil.getAncestorTag | public static Tag getAncestorTag(Statement stat, String fullName) {
"""
Gibt ein uebergeordnetes Tag mit dem uebergebenen Full-Name (Namespace und Name) zurueck, falls
ein solches existiert, andernfalls wird null zurueckgegeben.
@param el Startelement, von wo aus gesucht werden soll.
@param fullName Name des gesuchten Tags.
@return uebergeornetes Element oder null.
"""
Statement parent = stat;
Tag tag;
while (true) {
parent = parent.getParent();
if (parent == null) return null;
if (parent instanceof Tag) {
tag = (Tag) parent;
if (tag.getFullname().equalsIgnoreCase(fullName)) return tag;
}
}
} | java | public static Tag getAncestorTag(Statement stat, String fullName) {
Statement parent = stat;
Tag tag;
while (true) {
parent = parent.getParent();
if (parent == null) return null;
if (parent instanceof Tag) {
tag = (Tag) parent;
if (tag.getFullname().equalsIgnoreCase(fullName)) return tag;
}
}
} | [
"public",
"static",
"Tag",
"getAncestorTag",
"(",
"Statement",
"stat",
",",
"String",
"fullName",
")",
"{",
"Statement",
"parent",
"=",
"stat",
";",
"Tag",
"tag",
";",
"while",
"(",
"true",
")",
"{",
"parent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"parent",
"instanceof",
"Tag",
")",
"{",
"tag",
"=",
"(",
"Tag",
")",
"parent",
";",
"if",
"(",
"tag",
".",
"getFullname",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"fullName",
")",
")",
"return",
"tag",
";",
"}",
"}",
"}"
] | Gibt ein uebergeordnetes Tag mit dem uebergebenen Full-Name (Namespace und Name) zurueck, falls
ein solches existiert, andernfalls wird null zurueckgegeben.
@param el Startelement, von wo aus gesucht werden soll.
@param fullName Name des gesuchten Tags.
@return uebergeornetes Element oder null. | [
"Gibt",
"ein",
"uebergeordnetes",
"Tag",
"mit",
"dem",
"uebergebenen",
"Full",
"-",
"Name",
"(",
"Namespace",
"und",
"Name",
")",
"zurueck",
"falls",
"ein",
"solches",
"existiert",
"andernfalls",
"wird",
"null",
"zurueckgegeben",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java#L296-L307 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/lss/LssClient.java | LssClient.updateStreamPullUrl | public void updateStreamPullUrl(String domain, String app, String stream, String pullUrl) {
"""
Update stream's destination push url
@param domain The requested domain which the specific stream belongs to
@param app The requested app which the specific stream belongs to
@param stream The requested stream which need to update pull url
@param pullUrl The new pull url is setting to this specific stream
"""
UpdateStreamPullUrlRequest request = new UpdateStreamPullUrlRequest()
.withDomain(domain)
.withApp(app)
.withStream(stream)
.withPullUrl(pullUrl);
updateStreamPullUrl(request);
} | java | public void updateStreamPullUrl(String domain, String app, String stream, String pullUrl) {
UpdateStreamPullUrlRequest request = new UpdateStreamPullUrlRequest()
.withDomain(domain)
.withApp(app)
.withStream(stream)
.withPullUrl(pullUrl);
updateStreamPullUrl(request);
} | [
"public",
"void",
"updateStreamPullUrl",
"(",
"String",
"domain",
",",
"String",
"app",
",",
"String",
"stream",
",",
"String",
"pullUrl",
")",
"{",
"UpdateStreamPullUrlRequest",
"request",
"=",
"new",
"UpdateStreamPullUrlRequest",
"(",
")",
".",
"withDomain",
"(",
"domain",
")",
".",
"withApp",
"(",
"app",
")",
".",
"withStream",
"(",
"stream",
")",
".",
"withPullUrl",
"(",
"pullUrl",
")",
";",
"updateStreamPullUrl",
"(",
"request",
")",
";",
"}"
] | Update stream's destination push url
@param domain The requested domain which the specific stream belongs to
@param app The requested app which the specific stream belongs to
@param stream The requested stream which need to update pull url
@param pullUrl The new pull url is setting to this specific stream | [
"Update",
"stream",
"s",
"destination",
"push",
"url"
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1735-L1742 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/gm/inf/Beliefs.java | Beliefs.setValue | public double setValue(int idx, double val) {
"""
Sets a particular value by treating this object as a vector.
NOTE: This implementation is O(n).
@param idx The index of the value to set.
@param val The value to set.
@return The previous value at that index.
"""
int vSize = MVecArray.count(varBeliefs);
if (idx < vSize) {
return MVecArray.setValue(idx, val, varBeliefs);
} else {
return MVecArray.setValue(idx - vSize, val, facBeliefs);
}
} | java | public double setValue(int idx, double val) {
int vSize = MVecArray.count(varBeliefs);
if (idx < vSize) {
return MVecArray.setValue(idx, val, varBeliefs);
} else {
return MVecArray.setValue(idx - vSize, val, facBeliefs);
}
} | [
"public",
"double",
"setValue",
"(",
"int",
"idx",
",",
"double",
"val",
")",
"{",
"int",
"vSize",
"=",
"MVecArray",
".",
"count",
"(",
"varBeliefs",
")",
";",
"if",
"(",
"idx",
"<",
"vSize",
")",
"{",
"return",
"MVecArray",
".",
"setValue",
"(",
"idx",
",",
"val",
",",
"varBeliefs",
")",
";",
"}",
"else",
"{",
"return",
"MVecArray",
".",
"setValue",
"(",
"idx",
"-",
"vSize",
",",
"val",
",",
"facBeliefs",
")",
";",
"}",
"}"
] | Sets a particular value by treating this object as a vector.
NOTE: This implementation is O(n).
@param idx The index of the value to set.
@param val The value to set.
@return The previous value at that index. | [
"Sets",
"a",
"particular",
"value",
"by",
"treating",
"this",
"object",
"as",
"a",
"vector",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/inf/Beliefs.java#L81-L88 |
anotheria/moskito | moskito-integration/moskito-cdi/src/main/java/net/anotheria/moskito/integration/cdi/AbstractInterceptor.java | AbstractInterceptor.getProducer | protected final OnDemandStatsProducer getProducer(Class producerClass, String producerId, String category, String subsystem, boolean tracingSupported) {
"""
Returns {@link OnDemandStatsProducer}.
@param producerClass producer class
@param producerId producer id
@param category category
@param subsystem subsystem
@param tracingSupported is tracing supported
@return {@link OnDemandStatsProducer}
"""
OnDemandStatsProducer<T> producer = (OnDemandStatsProducer<T>) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
if (producer == null) {
producer = new OnDemandStatsProducer<T>(producerId, category, subsystem, getStatsFactory());
producer.setTracingSupported(tracingSupported);
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer);
//check for annotations
createClassLevelAccumulators(producer, producerClass);
for (Method method : producerClass.getMethods()){
createMethodLevelAccumulators(producer, method);
}
}
try {
return (OnDemandStatsProducer) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
} catch (ClassCastException e) {
LOGGER.error("getProducer(): Unexpected producer type", e);
return null;
}
} | java | protected final OnDemandStatsProducer getProducer(Class producerClass, String producerId, String category, String subsystem, boolean tracingSupported){
OnDemandStatsProducer<T> producer = (OnDemandStatsProducer<T>) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
if (producer == null) {
producer = new OnDemandStatsProducer<T>(producerId, category, subsystem, getStatsFactory());
producer.setTracingSupported(tracingSupported);
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer);
//check for annotations
createClassLevelAccumulators(producer, producerClass);
for (Method method : producerClass.getMethods()){
createMethodLevelAccumulators(producer, method);
}
}
try {
return (OnDemandStatsProducer) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
} catch (ClassCastException e) {
LOGGER.error("getProducer(): Unexpected producer type", e);
return null;
}
} | [
"protected",
"final",
"OnDemandStatsProducer",
"getProducer",
"(",
"Class",
"producerClass",
",",
"String",
"producerId",
",",
"String",
"category",
",",
"String",
"subsystem",
",",
"boolean",
"tracingSupported",
")",
"{",
"OnDemandStatsProducer",
"<",
"T",
">",
"producer",
"=",
"(",
"OnDemandStatsProducer",
"<",
"T",
">",
")",
"ProducerRegistryFactory",
".",
"getProducerRegistryInstance",
"(",
")",
".",
"getProducer",
"(",
"producerId",
")",
";",
"if",
"(",
"producer",
"==",
"null",
")",
"{",
"producer",
"=",
"new",
"OnDemandStatsProducer",
"<",
"T",
">",
"(",
"producerId",
",",
"category",
",",
"subsystem",
",",
"getStatsFactory",
"(",
")",
")",
";",
"producer",
".",
"setTracingSupported",
"(",
"tracingSupported",
")",
";",
"ProducerRegistryFactory",
".",
"getProducerRegistryInstance",
"(",
")",
".",
"registerProducer",
"(",
"producer",
")",
";",
"//check for annotations",
"createClassLevelAccumulators",
"(",
"producer",
",",
"producerClass",
")",
";",
"for",
"(",
"Method",
"method",
":",
"producerClass",
".",
"getMethods",
"(",
")",
")",
"{",
"createMethodLevelAccumulators",
"(",
"producer",
",",
"method",
")",
";",
"}",
"}",
"try",
"{",
"return",
"(",
"OnDemandStatsProducer",
")",
"ProducerRegistryFactory",
".",
"getProducerRegistryInstance",
"(",
")",
".",
"getProducer",
"(",
"producerId",
")",
";",
"}",
"catch",
"(",
"ClassCastException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"getProducer(): Unexpected producer type\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Returns {@link OnDemandStatsProducer}.
@param producerClass producer class
@param producerId producer id
@param category category
@param subsystem subsystem
@param tracingSupported is tracing supported
@return {@link OnDemandStatsProducer} | [
"Returns",
"{",
"@link",
"OnDemandStatsProducer",
"}",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-integration/moskito-cdi/src/main/java/net/anotheria/moskito/integration/cdi/AbstractInterceptor.java#L58-L80 |
JodaOrg/joda-beans | src/main/java/org/joda/beans/ser/bin/MsgPackOutput.java | MsgPackOutput.writeExtensionByte | void writeExtensionByte(int extensionType, int value) throws IOException {
"""
Writes an extension string using FIX_EXT_1.
@param extensionType the type
@param value the value to write as the data
@throws IOException if an error occurs
"""
output.write(FIX_EXT_1);
output.write(extensionType);
output.write(value);
} | java | void writeExtensionByte(int extensionType, int value) throws IOException {
output.write(FIX_EXT_1);
output.write(extensionType);
output.write(value);
} | [
"void",
"writeExtensionByte",
"(",
"int",
"extensionType",
",",
"int",
"value",
")",
"throws",
"IOException",
"{",
"output",
".",
"write",
"(",
"FIX_EXT_1",
")",
";",
"output",
".",
"write",
"(",
"extensionType",
")",
";",
"output",
".",
"write",
"(",
"value",
")",
";",
"}"
] | Writes an extension string using FIX_EXT_1.
@param extensionType the type
@param value the value to write as the data
@throws IOException if an error occurs | [
"Writes",
"an",
"extension",
"string",
"using",
"FIX_EXT_1",
"."
] | train | https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/bin/MsgPackOutput.java#L279-L283 |
seancfoley/IPAddress | IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6Address.java | IPv6Address.toNormalizedString | public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {
"""
Constructs a string representing this address according to the given parameters
@param keepMixed if this address was constructed from a string with mixed representation (a:b:c:d:e:f:1.2.3.4), whether to keep it that way (ignored if makeMixed is true in the params argument)
@param params the parameters for the address string
"""
if(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {
params = new IPv6StringOptions(
params.base,
params.expandSegments,
params.wildcardOption,
params.wildcards,
params.segmentStrPrefix,
true,
params.ipv4Opts,
params.compressOptions,
params.separator,
params.zoneSeparator,
params.addrLabel,
params.addrSuffix,
params.reverse,
params.splitDigits,
params.uppercase);
}
return toNormalizedString(params);
} | java | public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {
if(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {
params = new IPv6StringOptions(
params.base,
params.expandSegments,
params.wildcardOption,
params.wildcards,
params.segmentStrPrefix,
true,
params.ipv4Opts,
params.compressOptions,
params.separator,
params.zoneSeparator,
params.addrLabel,
params.addrSuffix,
params.reverse,
params.splitDigits,
params.uppercase);
}
return toNormalizedString(params);
} | [
"public",
"String",
"toNormalizedString",
"(",
"boolean",
"keepMixed",
",",
"IPv6StringOptions",
"params",
")",
"{",
"if",
"(",
"keepMixed",
"&&",
"fromString",
"!=",
"null",
"&&",
"getAddressfromString",
"(",
")",
".",
"isMixedIPv6",
"(",
")",
"&&",
"!",
"params",
".",
"makeMixed",
"(",
")",
")",
"{",
"params",
"=",
"new",
"IPv6StringOptions",
"(",
"params",
".",
"base",
",",
"params",
".",
"expandSegments",
",",
"params",
".",
"wildcardOption",
",",
"params",
".",
"wildcards",
",",
"params",
".",
"segmentStrPrefix",
",",
"true",
",",
"params",
".",
"ipv4Opts",
",",
"params",
".",
"compressOptions",
",",
"params",
".",
"separator",
",",
"params",
".",
"zoneSeparator",
",",
"params",
".",
"addrLabel",
",",
"params",
".",
"addrSuffix",
",",
"params",
".",
"reverse",
",",
"params",
".",
"splitDigits",
",",
"params",
".",
"uppercase",
")",
";",
"}",
"return",
"toNormalizedString",
"(",
"params",
")",
";",
"}"
] | Constructs a string representing this address according to the given parameters
@param keepMixed if this address was constructed from a string with mixed representation (a:b:c:d:e:f:1.2.3.4), whether to keep it that way (ignored if makeMixed is true in the params argument)
@param params the parameters for the address string | [
"Constructs",
"a",
"string",
"representing",
"this",
"address",
"according",
"to",
"the",
"given",
"parameters"
] | train | https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6Address.java#L1968-L1988 |
aws/aws-sdk-java | aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ConnectionInput.java | ConnectionInput.withConnectionProperties | public ConnectionInput withConnectionProperties(java.util.Map<String, String> connectionProperties) {
"""
<p>
These key-value pairs define parameters for the connection.
</p>
@param connectionProperties
These key-value pairs define parameters for the connection.
@return Returns a reference to this object so that method calls can be chained together.
"""
setConnectionProperties(connectionProperties);
return this;
} | java | public ConnectionInput withConnectionProperties(java.util.Map<String, String> connectionProperties) {
setConnectionProperties(connectionProperties);
return this;
} | [
"public",
"ConnectionInput",
"withConnectionProperties",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"connectionProperties",
")",
"{",
"setConnectionProperties",
"(",
"connectionProperties",
")",
";",
"return",
"this",
";",
"}"
] | <p>
These key-value pairs define parameters for the connection.
</p>
@param connectionProperties
These key-value pairs define parameters for the connection.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"These",
"key",
"-",
"value",
"pairs",
"define",
"parameters",
"for",
"the",
"connection",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ConnectionInput.java#L313-L316 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/io/async/AsyncSocketChannel.java | AsyncSocketChannel.prepareSocket | public synchronized void prepareSocket() throws IOException {
"""
Perform initialization steps for this new connection.
@throws IOException
"""
if (!prepared) {
final long fd = getFileDescriptor();
if (fd == INVALID_SOCKET) {
throw new AsyncException(AsyncProperties.aio_handle_unavailable);
}
channelIdentifier = provider.prepare2(fd, asyncChannelGroup.getCompletionPort());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "prepareSocket - socket prepared, fd = " + fd
+ " channel id: " + channelIdentifier + " "
+ ", local: " + channel.socket().getLocalSocketAddress()
+ ", remote: " + channel.socket().getRemoteSocketAddress());
}
long callid = 0; // init to zero, reset when IO requested
readIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
if (readIOCB != null) {
// initialize the IOCB from the pool
readIOCB.initializePoolEntry(channelIdentifier, callid);
writeIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
if (writeIOCB != null) {
// initialize the IOCB from the pool
writeIOCB.initializePoolEntry(channelIdentifier, callid);
} else {
writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
}
} else {
readIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
}
provider.initializeIOCB(readIOCB);
provider.initializeIOCB(writeIOCB);
prepared = true;
}
} | java | public synchronized void prepareSocket() throws IOException {
if (!prepared) {
final long fd = getFileDescriptor();
if (fd == INVALID_SOCKET) {
throw new AsyncException(AsyncProperties.aio_handle_unavailable);
}
channelIdentifier = provider.prepare2(fd, asyncChannelGroup.getCompletionPort());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "prepareSocket - socket prepared, fd = " + fd
+ " channel id: " + channelIdentifier + " "
+ ", local: " + channel.socket().getLocalSocketAddress()
+ ", remote: " + channel.socket().getRemoteSocketAddress());
}
long callid = 0; // init to zero, reset when IO requested
readIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
if (readIOCB != null) {
// initialize the IOCB from the pool
readIOCB.initializePoolEntry(channelIdentifier, callid);
writeIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
if (writeIOCB != null) {
// initialize the IOCB from the pool
writeIOCB.initializePoolEntry(channelIdentifier, callid);
} else {
writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
}
} else {
readIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
}
provider.initializeIOCB(readIOCB);
provider.initializeIOCB(writeIOCB);
prepared = true;
}
} | [
"public",
"synchronized",
"void",
"prepareSocket",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"prepared",
")",
"{",
"final",
"long",
"fd",
"=",
"getFileDescriptor",
"(",
")",
";",
"if",
"(",
"fd",
"==",
"INVALID_SOCKET",
")",
"{",
"throw",
"new",
"AsyncException",
"(",
"AsyncProperties",
".",
"aio_handle_unavailable",
")",
";",
"}",
"channelIdentifier",
"=",
"provider",
".",
"prepare2",
"(",
"fd",
",",
"asyncChannelGroup",
".",
"getCompletionPort",
"(",
")",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"prepareSocket - socket prepared, fd = \"",
"+",
"fd",
"+",
"\" channel id: \"",
"+",
"channelIdentifier",
"+",
"\" \"",
"+",
"\", local: \"",
"+",
"channel",
".",
"socket",
"(",
")",
".",
"getLocalSocketAddress",
"(",
")",
"+",
"\", remote: \"",
"+",
"channel",
".",
"socket",
"(",
")",
".",
"getRemoteSocketAddress",
"(",
")",
")",
";",
"}",
"long",
"callid",
"=",
"0",
";",
"// init to zero, reset when IO requested",
"readIOCB",
"=",
"(",
"CompletionKey",
")",
"AsyncLibrary",
".",
"completionKeyPool",
".",
"get",
"(",
")",
";",
"if",
"(",
"readIOCB",
"!=",
"null",
")",
"{",
"// initialize the IOCB from the pool",
"readIOCB",
".",
"initializePoolEntry",
"(",
"channelIdentifier",
",",
"callid",
")",
";",
"writeIOCB",
"=",
"(",
"CompletionKey",
")",
"AsyncLibrary",
".",
"completionKeyPool",
".",
"get",
"(",
")",
";",
"if",
"(",
"writeIOCB",
"!=",
"null",
")",
"{",
"// initialize the IOCB from the pool",
"writeIOCB",
".",
"initializePoolEntry",
"(",
"channelIdentifier",
",",
"callid",
")",
";",
"}",
"else",
"{",
"writeIOCB",
"=",
"new",
"CompletionKey",
"(",
"channelIdentifier",
",",
"callid",
",",
"defaultBufferCount",
")",
";",
"}",
"}",
"else",
"{",
"readIOCB",
"=",
"new",
"CompletionKey",
"(",
"channelIdentifier",
",",
"callid",
",",
"defaultBufferCount",
")",
";",
"writeIOCB",
"=",
"new",
"CompletionKey",
"(",
"channelIdentifier",
",",
"callid",
",",
"defaultBufferCount",
")",
";",
"}",
"provider",
".",
"initializeIOCB",
"(",
"readIOCB",
")",
";",
"provider",
".",
"initializeIOCB",
"(",
"writeIOCB",
")",
";",
"prepared",
"=",
"true",
";",
"}",
"}"
] | Perform initialization steps for this new connection.
@throws IOException | [
"Perform",
"initialization",
"steps",
"for",
"this",
"new",
"connection",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/io/async/AsyncSocketChannel.java#L349-L387 |
bwkimmel/java-util | src/main/java/ca/eandb/util/sql/DbUtil.java | DbUtil.getTypeName | public static String getTypeName(int type, int length, DataSource ds) throws SQLException {
"""
Gets the <code>String</code> denoting the specified SQL data type.
@param type The data type to get the name of. Valid type values
consist of the static fields of {@link java.sql.Types}.
@param length The length to assign to data types for those types
that require a length (e.g., <code>VARCHAR(n)</code>), or zero
to indicate that no length is required.
@param ds The <code>DataSource</code> for which to get the type name.
@return The name of the type, or <code>null</code> if no such type
exists.
@throws SQLException If an error occurs while communicating with the
database.
@see java.sql.Types
"""
Connection con = null;
try {
con = ds.getConnection();
return getTypeName(type, length, con);
} finally {
close(con);
}
} | java | public static String getTypeName(int type, int length, DataSource ds) throws SQLException {
Connection con = null;
try {
con = ds.getConnection();
return getTypeName(type, length, con);
} finally {
close(con);
}
} | [
"public",
"static",
"String",
"getTypeName",
"(",
"int",
"type",
",",
"int",
"length",
",",
"DataSource",
"ds",
")",
"throws",
"SQLException",
"{",
"Connection",
"con",
"=",
"null",
";",
"try",
"{",
"con",
"=",
"ds",
".",
"getConnection",
"(",
")",
";",
"return",
"getTypeName",
"(",
"type",
",",
"length",
",",
"con",
")",
";",
"}",
"finally",
"{",
"close",
"(",
"con",
")",
";",
"}",
"}"
] | Gets the <code>String</code> denoting the specified SQL data type.
@param type The data type to get the name of. Valid type values
consist of the static fields of {@link java.sql.Types}.
@param length The length to assign to data types for those types
that require a length (e.g., <code>VARCHAR(n)</code>), or zero
to indicate that no length is required.
@param ds The <code>DataSource</code> for which to get the type name.
@return The name of the type, or <code>null</code> if no such type
exists.
@throws SQLException If an error occurs while communicating with the
database.
@see java.sql.Types | [
"Gets",
"the",
"<code",
">",
"String<",
"/",
"code",
">",
"denoting",
"the",
"specified",
"SQL",
"data",
"type",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/sql/DbUtil.java#L420-L428 |
ginere/ginere-base | src/main/java/eu/ginere/base/util/file/FileUtils.java | FileUtils.copyFromFileToFile | public static void copyFromFileToFile(File source, File dest) throws IOException {
"""
Copia el contenido de un fichero a otro en caso de error lanza una excepcion.
@param source
@param dest
@throws IOException
"""
try {
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(dest);
try {
FileChannel canalFuente = in.getChannel();
FileChannel canalDestino = out.getChannel();
canalFuente.transferTo(0, canalFuente.size(), canalDestino);
} catch (IOException e) {
throw new IOException("copiando ficheros orig:'" + source.getAbsolutePath()
+ "' destino:'" + dest.getAbsolutePath() + "'", e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
// try {
// in.close();
// } catch (IOException e) {
// }
// try {
// out.close();
// } catch (IOException e) {
// }
}
} catch (FileNotFoundException e) {
throw new IOException("copiando ficheros orig:'" + source.getAbsolutePath()
+ "' destino:'" + dest.getAbsolutePath() + "'", e);
}
} | java | public static void copyFromFileToFile(File source, File dest) throws IOException{
try {
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(dest);
try {
FileChannel canalFuente = in.getChannel();
FileChannel canalDestino = out.getChannel();
canalFuente.transferTo(0, canalFuente.size(), canalDestino);
} catch (IOException e) {
throw new IOException("copiando ficheros orig:'" + source.getAbsolutePath()
+ "' destino:'" + dest.getAbsolutePath() + "'", e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
// try {
// in.close();
// } catch (IOException e) {
// }
// try {
// out.close();
// } catch (IOException e) {
// }
}
} catch (FileNotFoundException e) {
throw new IOException("copiando ficheros orig:'" + source.getAbsolutePath()
+ "' destino:'" + dest.getAbsolutePath() + "'", e);
}
} | [
"public",
"static",
"void",
"copyFromFileToFile",
"(",
"File",
"source",
",",
"File",
"dest",
")",
"throws",
"IOException",
"{",
"try",
"{",
"FileInputStream",
"in",
"=",
"new",
"FileInputStream",
"(",
"source",
")",
";",
"FileOutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"dest",
")",
";",
"try",
"{",
"FileChannel",
"canalFuente",
"=",
"in",
".",
"getChannel",
"(",
")",
";",
"FileChannel",
"canalDestino",
"=",
"out",
".",
"getChannel",
"(",
")",
";",
"canalFuente",
".",
"transferTo",
"(",
"0",
",",
"canalFuente",
".",
"size",
"(",
")",
",",
"canalDestino",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"copiando ficheros orig:'\"",
"+",
"source",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"' destino:'\"",
"+",
"dest",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"'\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"in",
")",
";",
"IOUtils",
".",
"closeQuietly",
"(",
"out",
")",
";",
"//\t\t\t\ttry { \r",
"//\t\t\t\t\tin.close();\r",
"//\t\t\t\t} catch (IOException e) {\r",
"//\t\t\t\t}\r",
"//\t\t\t\ttry {\r",
"//\t\t\t\t\tout.close();\r",
"//\t\t\t\t} catch (IOException e) {\r",
"//\t\t\t\t}\r",
"}",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"copiando ficheros orig:'\"",
"+",
"source",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"' destino:'\"",
"+",
"dest",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"'\"",
",",
"e",
")",
";",
"}",
"}"
] | Copia el contenido de un fichero a otro en caso de error lanza una excepcion.
@param source
@param dest
@throws IOException | [
"Copia",
"el",
"contenido",
"de",
"un",
"fichero",
"a",
"otro",
"en",
"caso",
"de",
"error",
"lanza",
"una",
"excepcion",
"."
] | train | https://github.com/ginere/ginere-base/blob/b1cc1c5834bd8a31df475c6f3fc0ee51273c5a24/src/main/java/eu/ginere/base/util/file/FileUtils.java#L522-L549 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/spatial/snapping/NearestAlgorithm.java | NearestAlgorithm.getSnappingPoint | Coordinate getSnappingPoint(Coordinate original, double threshold) {
"""
Calculates a snapping point from the given coordinate.
@param original
The original and unsnapped coordinate.
@param threshold
A threshold value that needs to be beaten in order to snap. Only if the distance between the original
and the candidate coordinate is smaller then this threshold, can the candidate coordinate be a snapped
coordinate.
@return Returns the eventual snapped coordinate, or null if no snapping occurred.
"""
minimumDistance = Double.MAX_VALUE;
Coordinate snappingPoint = null;
double currThreshold = threshold;
for (Coordinate[] coordinateArray : coordinates) {
for (int j = 1; j < coordinateArray.length; j++) {
LineSegment line = new LineSegment(coordinateArray[j], coordinateArray[j - 1]);
double distance = line.distance(original);
if (distance < currThreshold && distance < ruleDistance) {
currThreshold = distance;
minimumDistance = distance;
snappingPoint = line.nearest(original);
}
}
}
return snappingPoint;
} | java | Coordinate getSnappingPoint(Coordinate original, double threshold) {
minimumDistance = Double.MAX_VALUE;
Coordinate snappingPoint = null;
double currThreshold = threshold;
for (Coordinate[] coordinateArray : coordinates) {
for (int j = 1; j < coordinateArray.length; j++) {
LineSegment line = new LineSegment(coordinateArray[j], coordinateArray[j - 1]);
double distance = line.distance(original);
if (distance < currThreshold && distance < ruleDistance) {
currThreshold = distance;
minimumDistance = distance;
snappingPoint = line.nearest(original);
}
}
}
return snappingPoint;
} | [
"Coordinate",
"getSnappingPoint",
"(",
"Coordinate",
"original",
",",
"double",
"threshold",
")",
"{",
"minimumDistance",
"=",
"Double",
".",
"MAX_VALUE",
";",
"Coordinate",
"snappingPoint",
"=",
"null",
";",
"double",
"currThreshold",
"=",
"threshold",
";",
"for",
"(",
"Coordinate",
"[",
"]",
"coordinateArray",
":",
"coordinates",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"1",
";",
"j",
"<",
"coordinateArray",
".",
"length",
";",
"j",
"++",
")",
"{",
"LineSegment",
"line",
"=",
"new",
"LineSegment",
"(",
"coordinateArray",
"[",
"j",
"]",
",",
"coordinateArray",
"[",
"j",
"-",
"1",
"]",
")",
";",
"double",
"distance",
"=",
"line",
".",
"distance",
"(",
"original",
")",
";",
"if",
"(",
"distance",
"<",
"currThreshold",
"&&",
"distance",
"<",
"ruleDistance",
")",
"{",
"currThreshold",
"=",
"distance",
";",
"minimumDistance",
"=",
"distance",
";",
"snappingPoint",
"=",
"line",
".",
"nearest",
"(",
"original",
")",
";",
"}",
"}",
"}",
"return",
"snappingPoint",
";",
"}"
] | Calculates a snapping point from the given coordinate.
@param original
The original and unsnapped coordinate.
@param threshold
A threshold value that needs to be beaten in order to snap. Only if the distance between the original
and the candidate coordinate is smaller then this threshold, can the candidate coordinate be a snapped
coordinate.
@return Returns the eventual snapped coordinate, or null if no snapping occurred. | [
"Calculates",
"a",
"snapping",
"point",
"from",
"the",
"given",
"coordinate",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/spatial/snapping/NearestAlgorithm.java#L68-L86 |
baratine/baratine | kraken/src/main/java/com/caucho/v5/kraken/table/WatchTable.java | WatchTable.onPut | private void onPut(ArrayList<WatchEntry> list, byte []key) {
"""
Notify all watches with the updated row for the given key.
@param list watch list
@param key the updated row's key
"""
if (list != null) {
int size = list.size();
for (int i = 0; i < size; i++) {
WatchEntry entry = list.get(i);
RowCursor rowCursor = _table.cursor();
rowCursor.setKey(key, 0);
EnvKelp envKelp = null;
CursorKraken cursor = new CursorKraken(table(), envKelp, rowCursor, _results);
entry.onPut(cursor);
}
}
} | java | private void onPut(ArrayList<WatchEntry> list, byte []key)
{
if (list != null) {
int size = list.size();
for (int i = 0; i < size; i++) {
WatchEntry entry = list.get(i);
RowCursor rowCursor = _table.cursor();
rowCursor.setKey(key, 0);
EnvKelp envKelp = null;
CursorKraken cursor = new CursorKraken(table(), envKelp, rowCursor, _results);
entry.onPut(cursor);
}
}
} | [
"private",
"void",
"onPut",
"(",
"ArrayList",
"<",
"WatchEntry",
">",
"list",
",",
"byte",
"[",
"]",
"key",
")",
"{",
"if",
"(",
"list",
"!=",
"null",
")",
"{",
"int",
"size",
"=",
"list",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"WatchEntry",
"entry",
"=",
"list",
".",
"get",
"(",
"i",
")",
";",
"RowCursor",
"rowCursor",
"=",
"_table",
".",
"cursor",
"(",
")",
";",
"rowCursor",
".",
"setKey",
"(",
"key",
",",
"0",
")",
";",
"EnvKelp",
"envKelp",
"=",
"null",
";",
"CursorKraken",
"cursor",
"=",
"new",
"CursorKraken",
"(",
"table",
"(",
")",
",",
"envKelp",
",",
"rowCursor",
",",
"_results",
")",
";",
"entry",
".",
"onPut",
"(",
"cursor",
")",
";",
"}",
"}",
"}"
] | Notify all watches with the updated row for the given key.
@param list watch list
@param key the updated row's key | [
"Notify",
"all",
"watches",
"with",
"the",
"updated",
"row",
"for",
"the",
"given",
"key",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kraken/table/WatchTable.java#L196-L214 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java | SourceToHTMLConverter.writeToFile | private void writeToFile(Content body, DocPath path) throws DocFileIOException {
"""
Write the output to the file.
@param body the documentation content to be written to the file.
@param path the path for the file.
"""
Content htmlDocType = configuration.isOutputHtml5()
? DocType.HTML5
: DocType.TRANSITIONAL;
Content head = new HtmlTree(HtmlTag.HEAD);
head.addContent(HtmlTree.TITLE(new StringContent(
configuration.getText("doclet.Window_Source_title"))));
head.addContent(getStyleSheetProperties());
Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
head, body);
Content htmlDocument = new HtmlDocument(htmlDocType, htmlTree);
messages.notice("doclet.Generating_0", path.getPath());
DocFile df = DocFile.createFileForOutput(configuration, path);
try (Writer w = df.openWriter()) {
htmlDocument.write(w, true);
} catch (IOException e) {
throw new DocFileIOException(df, DocFileIOException.Mode.WRITE, e);
}
} | java | private void writeToFile(Content body, DocPath path) throws DocFileIOException {
Content htmlDocType = configuration.isOutputHtml5()
? DocType.HTML5
: DocType.TRANSITIONAL;
Content head = new HtmlTree(HtmlTag.HEAD);
head.addContent(HtmlTree.TITLE(new StringContent(
configuration.getText("doclet.Window_Source_title"))));
head.addContent(getStyleSheetProperties());
Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
head, body);
Content htmlDocument = new HtmlDocument(htmlDocType, htmlTree);
messages.notice("doclet.Generating_0", path.getPath());
DocFile df = DocFile.createFileForOutput(configuration, path);
try (Writer w = df.openWriter()) {
htmlDocument.write(w, true);
} catch (IOException e) {
throw new DocFileIOException(df, DocFileIOException.Mode.WRITE, e);
}
} | [
"private",
"void",
"writeToFile",
"(",
"Content",
"body",
",",
"DocPath",
"path",
")",
"throws",
"DocFileIOException",
"{",
"Content",
"htmlDocType",
"=",
"configuration",
".",
"isOutputHtml5",
"(",
")",
"?",
"DocType",
".",
"HTML5",
":",
"DocType",
".",
"TRANSITIONAL",
";",
"Content",
"head",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"HEAD",
")",
";",
"head",
".",
"addContent",
"(",
"HtmlTree",
".",
"TITLE",
"(",
"new",
"StringContent",
"(",
"configuration",
".",
"getText",
"(",
"\"doclet.Window_Source_title\"",
")",
")",
")",
")",
";",
"head",
".",
"addContent",
"(",
"getStyleSheetProperties",
"(",
")",
")",
";",
"Content",
"htmlTree",
"=",
"HtmlTree",
".",
"HTML",
"(",
"configuration",
".",
"getLocale",
"(",
")",
".",
"getLanguage",
"(",
")",
",",
"head",
",",
"body",
")",
";",
"Content",
"htmlDocument",
"=",
"new",
"HtmlDocument",
"(",
"htmlDocType",
",",
"htmlTree",
")",
";",
"messages",
".",
"notice",
"(",
"\"doclet.Generating_0\"",
",",
"path",
".",
"getPath",
"(",
")",
")",
";",
"DocFile",
"df",
"=",
"DocFile",
".",
"createFileForOutput",
"(",
"configuration",
",",
"path",
")",
";",
"try",
"(",
"Writer",
"w",
"=",
"df",
".",
"openWriter",
"(",
")",
")",
"{",
"htmlDocument",
".",
"write",
"(",
"w",
",",
"true",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"DocFileIOException",
"(",
"df",
",",
"DocFileIOException",
".",
"Mode",
".",
"WRITE",
",",
"e",
")",
";",
"}",
"}"
] | Write the output to the file.
@param body the documentation content to be written to the file.
@param path the path for the file. | [
"Write",
"the",
"output",
"to",
"the",
"file",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java#L206-L225 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java | ApiOvhIpLoadbalancing.serviceName_tcp_farm_farmId_PUT | public void serviceName_tcp_farm_farmId_PUT(String serviceName, Long farmId, OvhBackendTcp body) throws IOException {
"""
Alter this object properties
REST: PUT /ipLoadbalancing/{serviceName}/tcp/farm/{farmId}
@param body [required] New object properties
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm
"""
String qPath = "/ipLoadbalancing/{serviceName}/tcp/farm/{farmId}";
StringBuilder sb = path(qPath, serviceName, farmId);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void serviceName_tcp_farm_farmId_PUT(String serviceName, Long farmId, OvhBackendTcp body) throws IOException {
String qPath = "/ipLoadbalancing/{serviceName}/tcp/farm/{farmId}";
StringBuilder sb = path(qPath, serviceName, farmId);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"serviceName_tcp_farm_farmId_PUT",
"(",
"String",
"serviceName",
",",
"Long",
"farmId",
",",
"OvhBackendTcp",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/ipLoadbalancing/{serviceName}/tcp/farm/{farmId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"farmId",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
] | Alter this object properties
REST: PUT /ipLoadbalancing/{serviceName}/tcp/farm/{farmId}
@param body [required] New object properties
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1584-L1588 |
jboss/jboss-servlet-api_spec | src/main/java/javax/servlet/http/HttpServletResponseWrapper.java | HttpServletResponseWrapper.addHeader | @Override
public void addHeader(String name, String value) {
"""
The default behavior of this method is to return addHeader(String name, String value)
on the wrapped response object.
"""
this._getHttpServletResponse().addHeader(name, value);
} | java | @Override
public void addHeader(String name, String value) {
this._getHttpServletResponse().addHeader(name, value);
} | [
"@",
"Override",
"public",
"void",
"addHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"this",
".",
"_getHttpServletResponse",
"(",
")",
".",
"addHeader",
"(",
"name",
",",
"value",
")",
";",
"}"
] | The default behavior of this method is to return addHeader(String name, String value)
on the wrapped response object. | [
"The",
"default",
"behavior",
"of",
"this",
"method",
"is",
"to",
"return",
"addHeader",
"(",
"String",
"name",
"String",
"value",
")",
"on",
"the",
"wrapped",
"response",
"object",
"."
] | train | https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletResponseWrapper.java#L216-L219 |
eclipse/xtext-core | org.eclipse.xtext/src/org/eclipse/xtext/formatting2/AbstractFormatter2.java | AbstractFormatter2._format | protected void _format(EObject obj, IFormattableDocument document) {
"""
Fall-back for types that are not handled by a subclasse's dispatch method.
"""
for (EObject child : obj.eContents())
document.format(child);
} | java | protected void _format(EObject obj, IFormattableDocument document) {
for (EObject child : obj.eContents())
document.format(child);
} | [
"protected",
"void",
"_format",
"(",
"EObject",
"obj",
",",
"IFormattableDocument",
"document",
")",
"{",
"for",
"(",
"EObject",
"child",
":",
"obj",
".",
"eContents",
"(",
")",
")",
"document",
".",
"format",
"(",
"child",
")",
";",
"}"
] | Fall-back for types that are not handled by a subclasse's dispatch method. | [
"Fall",
"-",
"back",
"for",
"types",
"that",
"are",
"not",
"handled",
"by",
"a",
"subclasse",
"s",
"dispatch",
"method",
"."
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/formatting2/AbstractFormatter2.java#L189-L192 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAuthenticatorProxy.java | WebAuthenticatorProxy.getAuthenticatorForFailOver | private WebAuthenticator getAuthenticatorForFailOver(String authType, WebRequest webRequest) {
"""
Get the appropriate Authenticator based on the authType
@param authType the auth type, either FORM or BASIC
@param the WebRequest
@return The WebAuthenticator or {@code null} if the authType is unknown
"""
WebAuthenticator authenticator = null;
if (LoginConfiguration.FORM.equals(authType)) {
authenticator = createFormLoginAuthenticator(webRequest);
} else if (LoginConfiguration.BASIC.equals(authType)) {
authenticator = getBasicAuthAuthenticator();
}
return authenticator;
} | java | private WebAuthenticator getAuthenticatorForFailOver(String authType, WebRequest webRequest) {
WebAuthenticator authenticator = null;
if (LoginConfiguration.FORM.equals(authType)) {
authenticator = createFormLoginAuthenticator(webRequest);
} else if (LoginConfiguration.BASIC.equals(authType)) {
authenticator = getBasicAuthAuthenticator();
}
return authenticator;
} | [
"private",
"WebAuthenticator",
"getAuthenticatorForFailOver",
"(",
"String",
"authType",
",",
"WebRequest",
"webRequest",
")",
"{",
"WebAuthenticator",
"authenticator",
"=",
"null",
";",
"if",
"(",
"LoginConfiguration",
".",
"FORM",
".",
"equals",
"(",
"authType",
")",
")",
"{",
"authenticator",
"=",
"createFormLoginAuthenticator",
"(",
"webRequest",
")",
";",
"}",
"else",
"if",
"(",
"LoginConfiguration",
".",
"BASIC",
".",
"equals",
"(",
"authType",
")",
")",
"{",
"authenticator",
"=",
"getBasicAuthAuthenticator",
"(",
")",
";",
"}",
"return",
"authenticator",
";",
"}"
] | Get the appropriate Authenticator based on the authType
@param authType the auth type, either FORM or BASIC
@param the WebRequest
@return The WebAuthenticator or {@code null} if the authType is unknown | [
"Get",
"the",
"appropriate",
"Authenticator",
"based",
"on",
"the",
"authType"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAuthenticatorProxy.java#L115-L123 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypeReferenceBuilder.java | JvmTypeReferenceBuilder.typeRef | public JvmTypeReference typeRef(JvmType type, JvmTypeReference... typeArgs) {
"""
Creates a new {@link JvmTypeReference} pointing to the given class and containing the given type arguments.
@param type
the type the reference shall point to.
@param typeArgs
type arguments
@return the newly created {@link JvmTypeReference}
"""
int typeParams = 0;
if (type instanceof JvmGenericType) {
typeParams = ((JvmGenericType) type).getTypeParameters().size();
}
if (typeParams < typeArgs.length) {
throw new IllegalArgumentException("The type "+type.getIdentifier()+" only declares "+typeParams+" type parameters. You passed "+typeArgs.length+".");
}
LightweightTypeReference reference = typeReferenceOwner.toPlainTypeReference(type);
for (JvmTypeReference jvmTypeReference : typeArgs) {
((ParameterizedTypeReference)reference).addTypeArgument(typeReferenceOwner.toLightweightTypeReference(jvmTypeReference));
}
return reference.toJavaCompliantTypeReference();
} | java | public JvmTypeReference typeRef(JvmType type, JvmTypeReference... typeArgs) {
int typeParams = 0;
if (type instanceof JvmGenericType) {
typeParams = ((JvmGenericType) type).getTypeParameters().size();
}
if (typeParams < typeArgs.length) {
throw new IllegalArgumentException("The type "+type.getIdentifier()+" only declares "+typeParams+" type parameters. You passed "+typeArgs.length+".");
}
LightweightTypeReference reference = typeReferenceOwner.toPlainTypeReference(type);
for (JvmTypeReference jvmTypeReference : typeArgs) {
((ParameterizedTypeReference)reference).addTypeArgument(typeReferenceOwner.toLightweightTypeReference(jvmTypeReference));
}
return reference.toJavaCompliantTypeReference();
} | [
"public",
"JvmTypeReference",
"typeRef",
"(",
"JvmType",
"type",
",",
"JvmTypeReference",
"...",
"typeArgs",
")",
"{",
"int",
"typeParams",
"=",
"0",
";",
"if",
"(",
"type",
"instanceof",
"JvmGenericType",
")",
"{",
"typeParams",
"=",
"(",
"(",
"JvmGenericType",
")",
"type",
")",
".",
"getTypeParameters",
"(",
")",
".",
"size",
"(",
")",
";",
"}",
"if",
"(",
"typeParams",
"<",
"typeArgs",
".",
"length",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The type \"",
"+",
"type",
".",
"getIdentifier",
"(",
")",
"+",
"\" only declares \"",
"+",
"typeParams",
"+",
"\" type parameters. You passed \"",
"+",
"typeArgs",
".",
"length",
"+",
"\".\"",
")",
";",
"}",
"LightweightTypeReference",
"reference",
"=",
"typeReferenceOwner",
".",
"toPlainTypeReference",
"(",
"type",
")",
";",
"for",
"(",
"JvmTypeReference",
"jvmTypeReference",
":",
"typeArgs",
")",
"{",
"(",
"(",
"ParameterizedTypeReference",
")",
"reference",
")",
".",
"addTypeArgument",
"(",
"typeReferenceOwner",
".",
"toLightweightTypeReference",
"(",
"jvmTypeReference",
")",
")",
";",
"}",
"return",
"reference",
".",
"toJavaCompliantTypeReference",
"(",
")",
";",
"}"
] | Creates a new {@link JvmTypeReference} pointing to the given class and containing the given type arguments.
@param type
the type the reference shall point to.
@param typeArgs
type arguments
@return the newly created {@link JvmTypeReference} | [
"Creates",
"a",
"new",
"{",
"@link",
"JvmTypeReference",
"}",
"pointing",
"to",
"the",
"given",
"class",
"and",
"containing",
"the",
"given",
"type",
"arguments",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypeReferenceBuilder.java#L104-L117 |
dverstap/jsmiparser | jsmiparser-api/src/main/java/org/jsmiparser/phase/file/ModuleParser.java | ModuleParser.createIntegerType | public SmiType createIntegerType(IdToken idToken, IntKeywordToken intToken, Token applicationTagToken, List<SmiNamedNumber> namedNumbers, List<SmiRange> rangeConstraints) {
"""
and resolve references to INTEGER, BITS, ... during the XRef phase
"""
if (idToken == null && intToken.getPrimitiveType() == INTEGER && namedNumbers == null && rangeConstraints == null) {
return SmiConstants.INTEGER_TYPE;
} else if (idToken != null || namedNumbers != null || rangeConstraints != null) {
SmiType type = createPotentiallyTaggedType(idToken, applicationTagToken);
if (intToken.getPrimitiveType() == INTEGER) {
type.setBaseType(SmiConstants.INTEGER_TYPE);
} else {
type.setBaseType(new SmiReferencedType(intToken, m_module));
}
type.setEnumValues(namedNumbers);
type.setRangeConstraints(rangeConstraints);
return type;
}
return new SmiReferencedType(intToken, m_module);
} | java | public SmiType createIntegerType(IdToken idToken, IntKeywordToken intToken, Token applicationTagToken, List<SmiNamedNumber> namedNumbers, List<SmiRange> rangeConstraints) {
if (idToken == null && intToken.getPrimitiveType() == INTEGER && namedNumbers == null && rangeConstraints == null) {
return SmiConstants.INTEGER_TYPE;
} else if (idToken != null || namedNumbers != null || rangeConstraints != null) {
SmiType type = createPotentiallyTaggedType(idToken, applicationTagToken);
if (intToken.getPrimitiveType() == INTEGER) {
type.setBaseType(SmiConstants.INTEGER_TYPE);
} else {
type.setBaseType(new SmiReferencedType(intToken, m_module));
}
type.setEnumValues(namedNumbers);
type.setRangeConstraints(rangeConstraints);
return type;
}
return new SmiReferencedType(intToken, m_module);
} | [
"public",
"SmiType",
"createIntegerType",
"(",
"IdToken",
"idToken",
",",
"IntKeywordToken",
"intToken",
",",
"Token",
"applicationTagToken",
",",
"List",
"<",
"SmiNamedNumber",
">",
"namedNumbers",
",",
"List",
"<",
"SmiRange",
">",
"rangeConstraints",
")",
"{",
"if",
"(",
"idToken",
"==",
"null",
"&&",
"intToken",
".",
"getPrimitiveType",
"(",
")",
"==",
"INTEGER",
"&&",
"namedNumbers",
"==",
"null",
"&&",
"rangeConstraints",
"==",
"null",
")",
"{",
"return",
"SmiConstants",
".",
"INTEGER_TYPE",
";",
"}",
"else",
"if",
"(",
"idToken",
"!=",
"null",
"||",
"namedNumbers",
"!=",
"null",
"||",
"rangeConstraints",
"!=",
"null",
")",
"{",
"SmiType",
"type",
"=",
"createPotentiallyTaggedType",
"(",
"idToken",
",",
"applicationTagToken",
")",
";",
"if",
"(",
"intToken",
".",
"getPrimitiveType",
"(",
")",
"==",
"INTEGER",
")",
"{",
"type",
".",
"setBaseType",
"(",
"SmiConstants",
".",
"INTEGER_TYPE",
")",
";",
"}",
"else",
"{",
"type",
".",
"setBaseType",
"(",
"new",
"SmiReferencedType",
"(",
"intToken",
",",
"m_module",
")",
")",
";",
"}",
"type",
".",
"setEnumValues",
"(",
"namedNumbers",
")",
";",
"type",
".",
"setRangeConstraints",
"(",
"rangeConstraints",
")",
";",
"return",
"type",
";",
"}",
"return",
"new",
"SmiReferencedType",
"(",
"intToken",
",",
"m_module",
")",
";",
"}"
] | and resolve references to INTEGER, BITS, ... during the XRef phase | [
"and",
"resolve",
"references",
"to",
"INTEGER",
"BITS",
"...",
"during",
"the",
"XRef",
"phase"
] | train | https://github.com/dverstap/jsmiparser/blob/1ba26599e573682d17e34363a85cf3a42cc06383/jsmiparser-api/src/main/java/org/jsmiparser/phase/file/ModuleParser.java#L246-L261 |
kiswanij/jk-util | src/main/java/com/jk/util/time/JKTimeObject.java | JKTimeObject.toTimeObject | public JKTimeObject toTimeObject(Date date, Date time) {
"""
To time object.
@param date the date
@param time the time
@return the JK time object
"""
JKTimeObject fsTimeObject = new JKTimeObject();
Calendar timeInstance = Calendar.getInstance();
timeInstance.setTimeInMillis(time.getTime());
fsTimeObject.setHour(timeInstance.get(Calendar.HOUR_OF_DAY));
fsTimeObject.setMunite(timeInstance.get(Calendar.MINUTE));
Calendar dateInstance = Calendar.getInstance();
dateInstance.setTime(date);
fsTimeObject.setYear(dateInstance.get(Calendar.YEAR));
fsTimeObject.setMonth(dateInstance.get(Calendar.MONTH));
fsTimeObject.setDay(dateInstance.get(Calendar.DAY_OF_MONTH));
return fsTimeObject;
} | java | public JKTimeObject toTimeObject(Date date, Date time) {
JKTimeObject fsTimeObject = new JKTimeObject();
Calendar timeInstance = Calendar.getInstance();
timeInstance.setTimeInMillis(time.getTime());
fsTimeObject.setHour(timeInstance.get(Calendar.HOUR_OF_DAY));
fsTimeObject.setMunite(timeInstance.get(Calendar.MINUTE));
Calendar dateInstance = Calendar.getInstance();
dateInstance.setTime(date);
fsTimeObject.setYear(dateInstance.get(Calendar.YEAR));
fsTimeObject.setMonth(dateInstance.get(Calendar.MONTH));
fsTimeObject.setDay(dateInstance.get(Calendar.DAY_OF_MONTH));
return fsTimeObject;
} | [
"public",
"JKTimeObject",
"toTimeObject",
"(",
"Date",
"date",
",",
"Date",
"time",
")",
"{",
"JKTimeObject",
"fsTimeObject",
"=",
"new",
"JKTimeObject",
"(",
")",
";",
"Calendar",
"timeInstance",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"timeInstance",
".",
"setTimeInMillis",
"(",
"time",
".",
"getTime",
"(",
")",
")",
";",
"fsTimeObject",
".",
"setHour",
"(",
"timeInstance",
".",
"get",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
")",
")",
";",
"fsTimeObject",
".",
"setMunite",
"(",
"timeInstance",
".",
"get",
"(",
"Calendar",
".",
"MINUTE",
")",
")",
";",
"Calendar",
"dateInstance",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"dateInstance",
".",
"setTime",
"(",
"date",
")",
";",
"fsTimeObject",
".",
"setYear",
"(",
"dateInstance",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
")",
";",
"fsTimeObject",
".",
"setMonth",
"(",
"dateInstance",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
")",
";",
"fsTimeObject",
".",
"setDay",
"(",
"dateInstance",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_MONTH",
")",
")",
";",
"return",
"fsTimeObject",
";",
"}"
] | To time object.
@param date the date
@param time the time
@return the JK time object | [
"To",
"time",
"object",
"."
] | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/time/JKTimeObject.java#L95-L108 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.copy | public static long copy(ReadableByteChannel in, WritableByteChannel out) throws IORuntimeException {
"""
拷贝流,使用NIO,不会关闭流
@param in {@link ReadableByteChannel}
@param out {@link WritableByteChannel}
@return 拷贝的字节数
@throws IORuntimeException IO异常
@since 4.5.0
"""
return copy(in, out, DEFAULT_BUFFER_SIZE);
} | java | public static long copy(ReadableByteChannel in, WritableByteChannel out) throws IORuntimeException {
return copy(in, out, DEFAULT_BUFFER_SIZE);
} | [
"public",
"static",
"long",
"copy",
"(",
"ReadableByteChannel",
"in",
",",
"WritableByteChannel",
"out",
")",
"throws",
"IORuntimeException",
"{",
"return",
"copy",
"(",
"in",
",",
"out",
",",
"DEFAULT_BUFFER_SIZE",
")",
";",
"}"
] | 拷贝流,使用NIO,不会关闭流
@param in {@link ReadableByteChannel}
@param out {@link WritableByteChannel}
@return 拷贝的字节数
@throws IORuntimeException IO异常
@since 4.5.0 | [
"拷贝流,使用NIO,不会关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L236-L238 |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/MavenMessageHandler.java | MavenMessageHandler.handleMessage | public boolean handleMessage(final IMessage message) {
"""
Copies output from the supplied message onto the active Maven Log.
If the message type (i.e. {@code message.getKind()}) is listed in the showDetailsForMessageKindList List,
the message is prefixed with location details (Class, row/line number etc.) as well.
<p/>
{@inheritDoc}
"""
// Compose the message text
final StringBuilder builder = new StringBuilder(message.getMessage());
if (isMessageDetailDesired(message)) {
//
// The AJC details are typically delivered on the format [fileName]:[lineNumber]
// (i.e. /src/main/java/Clazz.java:16).
//
// Mimic this, and include the context of the message as well,
// including guarding against NPEs.
//
final ISourceLocation sourceLocation = message.getSourceLocation();
final String sourceFile = sourceLocation == null || sourceLocation.getSourceFile() == null
? "<unknown source file>"
: sourceLocation.getSourceFile().getAbsolutePath();
final String context = sourceLocation == null || sourceLocation.getContext() == null
? ""
: sourceLocation.getContext() + "\n";
final String line = sourceLocation == null
? "<no line information>"
: "" + sourceLocation.getLine();
builder.append("\n\t")
.append(sourceFile)
.append(":")
.append(line)
.append("\n")
.append(context);
}
final String messageText = builder.toString();
if (isNotIgnored(message, IMessage.DEBUG)
|| isNotIgnored(message, IMessage.INFO)
|| isNotIgnored(message, IMessage.TASKTAG)) {
// The DEBUG, INFO, and TASKTAG ajc message kinds are considered Maven Debug messages.
log.debug(messageText);
} else if (isNotIgnored(message, IMessage.WEAVEINFO)) {
// The WEAVEINFO ajc message kind is considered Maven Info messages.
log.info(messageText);
} else if (isNotIgnored(message, IMessage.WARNING)) {
// The WARNING ajc message kind is considered Maven Warn messages.
log.warn(messageText);
} else if(isNotIgnored(message, IMessage.ERROR)
|| isNotIgnored(message, IMessage.ABORT)
|| isNotIgnored(message, IMessage.FAIL)) {
// We map ERROR, ABORT, and FAIL ajc message kinds to Maven Error messages.
log.error(messageText);
}
// Delegate to normal handling.
return super.handleMessage(message);
} | java | public boolean handleMessage(final IMessage message) {
// Compose the message text
final StringBuilder builder = new StringBuilder(message.getMessage());
if (isMessageDetailDesired(message)) {
//
// The AJC details are typically delivered on the format [fileName]:[lineNumber]
// (i.e. /src/main/java/Clazz.java:16).
//
// Mimic this, and include the context of the message as well,
// including guarding against NPEs.
//
final ISourceLocation sourceLocation = message.getSourceLocation();
final String sourceFile = sourceLocation == null || sourceLocation.getSourceFile() == null
? "<unknown source file>"
: sourceLocation.getSourceFile().getAbsolutePath();
final String context = sourceLocation == null || sourceLocation.getContext() == null
? ""
: sourceLocation.getContext() + "\n";
final String line = sourceLocation == null
? "<no line information>"
: "" + sourceLocation.getLine();
builder.append("\n\t")
.append(sourceFile)
.append(":")
.append(line)
.append("\n")
.append(context);
}
final String messageText = builder.toString();
if (isNotIgnored(message, IMessage.DEBUG)
|| isNotIgnored(message, IMessage.INFO)
|| isNotIgnored(message, IMessage.TASKTAG)) {
// The DEBUG, INFO, and TASKTAG ajc message kinds are considered Maven Debug messages.
log.debug(messageText);
} else if (isNotIgnored(message, IMessage.WEAVEINFO)) {
// The WEAVEINFO ajc message kind is considered Maven Info messages.
log.info(messageText);
} else if (isNotIgnored(message, IMessage.WARNING)) {
// The WARNING ajc message kind is considered Maven Warn messages.
log.warn(messageText);
} else if(isNotIgnored(message, IMessage.ERROR)
|| isNotIgnored(message, IMessage.ABORT)
|| isNotIgnored(message, IMessage.FAIL)) {
// We map ERROR, ABORT, and FAIL ajc message kinds to Maven Error messages.
log.error(messageText);
}
// Delegate to normal handling.
return super.handleMessage(message);
} | [
"public",
"boolean",
"handleMessage",
"(",
"final",
"IMessage",
"message",
")",
"{",
"// Compose the message text",
"final",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"message",
".",
"getMessage",
"(",
")",
")",
";",
"if",
"(",
"isMessageDetailDesired",
"(",
"message",
")",
")",
"{",
"//",
"// The AJC details are typically delivered on the format [fileName]:[lineNumber]",
"// (i.e. /src/main/java/Clazz.java:16).",
"//",
"// Mimic this, and include the context of the message as well,",
"// including guarding against NPEs.",
"//",
"final",
"ISourceLocation",
"sourceLocation",
"=",
"message",
".",
"getSourceLocation",
"(",
")",
";",
"final",
"String",
"sourceFile",
"=",
"sourceLocation",
"==",
"null",
"||",
"sourceLocation",
".",
"getSourceFile",
"(",
")",
"==",
"null",
"?",
"\"<unknown source file>\"",
":",
"sourceLocation",
".",
"getSourceFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
";",
"final",
"String",
"context",
"=",
"sourceLocation",
"==",
"null",
"||",
"sourceLocation",
".",
"getContext",
"(",
")",
"==",
"null",
"?",
"\"\"",
":",
"sourceLocation",
".",
"getContext",
"(",
")",
"+",
"\"\\n\"",
";",
"final",
"String",
"line",
"=",
"sourceLocation",
"==",
"null",
"?",
"\"<no line information>\"",
":",
"\"\"",
"+",
"sourceLocation",
".",
"getLine",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"\\n\\t\"",
")",
".",
"append",
"(",
"sourceFile",
")",
".",
"append",
"(",
"\":\"",
")",
".",
"append",
"(",
"line",
")",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"context",
")",
";",
"}",
"final",
"String",
"messageText",
"=",
"builder",
".",
"toString",
"(",
")",
";",
"if",
"(",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"DEBUG",
")",
"||",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"INFO",
")",
"||",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"TASKTAG",
")",
")",
"{",
"// The DEBUG, INFO, and TASKTAG ajc message kinds are considered Maven Debug messages.",
"log",
".",
"debug",
"(",
"messageText",
")",
";",
"}",
"else",
"if",
"(",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"WEAVEINFO",
")",
")",
"{",
"// The WEAVEINFO ajc message kind is considered Maven Info messages.",
"log",
".",
"info",
"(",
"messageText",
")",
";",
"}",
"else",
"if",
"(",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"WARNING",
")",
")",
"{",
"// The WARNING ajc message kind is considered Maven Warn messages.",
"log",
".",
"warn",
"(",
"messageText",
")",
";",
"}",
"else",
"if",
"(",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"ERROR",
")",
"||",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"ABORT",
")",
"||",
"isNotIgnored",
"(",
"message",
",",
"IMessage",
".",
"FAIL",
")",
")",
"{",
"// We map ERROR, ABORT, and FAIL ajc message kinds to Maven Error messages.",
"log",
".",
"error",
"(",
"messageText",
")",
";",
"}",
"// Delegate to normal handling.",
"return",
"super",
".",
"handleMessage",
"(",
"message",
")",
";",
"}"
] | Copies output from the supplied message onto the active Maven Log.
If the message type (i.e. {@code message.getKind()}) is listed in the showDetailsForMessageKindList List,
the message is prefixed with location details (Class, row/line number etc.) as well.
<p/>
{@inheritDoc} | [
"Copies",
"output",
"from",
"the",
"supplied",
"message",
"onto",
"the",
"active",
"Maven",
"Log",
".",
"If",
"the",
"message",
"type",
"(",
"i",
".",
"e",
".",
"{"
] | train | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/MavenMessageHandler.java#L106-L167 |
johnkil/Android-RobotoTextView | robototextview/src/main/java/com/devspark/robototextview/inflater/RobotoCompatInflater.java | RobotoCompatInflater.themifyContext | @SuppressLint("PrivateResource")
private static Context themifyContext(Context context, AttributeSet attrs, boolean useAppTheme) {
"""
Allows us to emulate the {@code android:theme} attribute for devices before L.
"""
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
int themeId = a.getResourceId(R.styleable.View_android_theme, 0);
if (useAppTheme && themeId == 0) {
// ...if that didn't work, try reading app:theme (for legacy reasons) if enabled
themeId = a.getResourceId(R.styleable.View_theme, 0);
if (themeId != 0) {
Log.i(LOG_TAG, "app:theme is now deprecated. "
+ "Please move to using android:theme instead.");
}
}
a.recycle();
if (themeId != 0 && (!(context instanceof ContextThemeWrapper)
|| ((ContextThemeWrapper) context).getThemeResId() != themeId)) {
// If the context isn't a ContextThemeWrapper, or it is but does not have
// the same theme as we need, wrap it in a new wrapper
context = new ContextThemeWrapper(context, themeId);
}
return context;
} | java | @SuppressLint("PrivateResource")
private static Context themifyContext(Context context, AttributeSet attrs, boolean useAppTheme) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
int themeId = a.getResourceId(R.styleable.View_android_theme, 0);
if (useAppTheme && themeId == 0) {
// ...if that didn't work, try reading app:theme (for legacy reasons) if enabled
themeId = a.getResourceId(R.styleable.View_theme, 0);
if (themeId != 0) {
Log.i(LOG_TAG, "app:theme is now deprecated. "
+ "Please move to using android:theme instead.");
}
}
a.recycle();
if (themeId != 0 && (!(context instanceof ContextThemeWrapper)
|| ((ContextThemeWrapper) context).getThemeResId() != themeId)) {
// If the context isn't a ContextThemeWrapper, or it is but does not have
// the same theme as we need, wrap it in a new wrapper
context = new ContextThemeWrapper(context, themeId);
}
return context;
} | [
"@",
"SuppressLint",
"(",
"\"PrivateResource\"",
")",
"private",
"static",
"Context",
"themifyContext",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
",",
"boolean",
"useAppTheme",
")",
"{",
"final",
"TypedArray",
"a",
"=",
"context",
".",
"obtainStyledAttributes",
"(",
"attrs",
",",
"R",
".",
"styleable",
".",
"View",
",",
"0",
",",
"0",
")",
";",
"int",
"themeId",
"=",
"a",
".",
"getResourceId",
"(",
"R",
".",
"styleable",
".",
"View_android_theme",
",",
"0",
")",
";",
"if",
"(",
"useAppTheme",
"&&",
"themeId",
"==",
"0",
")",
"{",
"// ...if that didn't work, try reading app:theme (for legacy reasons) if enabled",
"themeId",
"=",
"a",
".",
"getResourceId",
"(",
"R",
".",
"styleable",
".",
"View_theme",
",",
"0",
")",
";",
"if",
"(",
"themeId",
"!=",
"0",
")",
"{",
"Log",
".",
"i",
"(",
"LOG_TAG",
",",
"\"app:theme is now deprecated. \"",
"+",
"\"Please move to using android:theme instead.\"",
")",
";",
"}",
"}",
"a",
".",
"recycle",
"(",
")",
";",
"if",
"(",
"themeId",
"!=",
"0",
"&&",
"(",
"!",
"(",
"context",
"instanceof",
"ContextThemeWrapper",
")",
"||",
"(",
"(",
"ContextThemeWrapper",
")",
"context",
")",
".",
"getThemeResId",
"(",
")",
"!=",
"themeId",
")",
")",
"{",
"// If the context isn't a ContextThemeWrapper, or it is but does not have",
"// the same theme as we need, wrap it in a new wrapper",
"context",
"=",
"new",
"ContextThemeWrapper",
"(",
"context",
",",
"themeId",
")",
";",
"}",
"return",
"context",
";",
"}"
] | Allows us to emulate the {@code android:theme} attribute for devices before L. | [
"Allows",
"us",
"to",
"emulate",
"the",
"{"
] | train | https://github.com/johnkil/Android-RobotoTextView/blob/1341602f16c08057dddd193411e7dab96f963b77/robototextview/src/main/java/com/devspark/robototextview/inflater/RobotoCompatInflater.java#L141-L163 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagInclude.java | CmsJspTagInclude.includeTagAction | public static void includeTagAction(
PageContext context,
String target,
String element,
boolean editable,
Map<String, String[]> paramMap,
Map<String, Object> attrMap,
ServletRequest req,
ServletResponse res)
throws JspException {
"""
Includes the selected target.<p>
@param context the current JSP page context
@param target the target for the include, might be <code>null</code>
@param element the element to select form the target might be <code>null</code>
@param editable flag to indicate if the target is editable
@param paramMap a map of parameters for the include, will be merged with the request
parameters, might be <code>null</code>
@param attrMap a map of attributes for the include, will be merged with the request
attributes, might be <code>null</code>
@param req the current request
@param res the current response
@throws JspException in case something goes wrong
"""
// no locale and no cachable parameter are used by default
includeTagAction(context, target, element, null, editable, true, paramMap, attrMap, req, res);
} | java | public static void includeTagAction(
PageContext context,
String target,
String element,
boolean editable,
Map<String, String[]> paramMap,
Map<String, Object> attrMap,
ServletRequest req,
ServletResponse res)
throws JspException {
// no locale and no cachable parameter are used by default
includeTagAction(context, target, element, null, editable, true, paramMap, attrMap, req, res);
} | [
"public",
"static",
"void",
"includeTagAction",
"(",
"PageContext",
"context",
",",
"String",
"target",
",",
"String",
"element",
",",
"boolean",
"editable",
",",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"paramMap",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"attrMap",
",",
"ServletRequest",
"req",
",",
"ServletResponse",
"res",
")",
"throws",
"JspException",
"{",
"// no locale and no cachable parameter are used by default",
"includeTagAction",
"(",
"context",
",",
"target",
",",
"element",
",",
"null",
",",
"editable",
",",
"true",
",",
"paramMap",
",",
"attrMap",
",",
"req",
",",
"res",
")",
";",
"}"
] | Includes the selected target.<p>
@param context the current JSP page context
@param target the target for the include, might be <code>null</code>
@param element the element to select form the target might be <code>null</code>
@param editable flag to indicate if the target is editable
@param paramMap a map of parameters for the include, will be merged with the request
parameters, might be <code>null</code>
@param attrMap a map of attributes for the include, will be merged with the request
attributes, might be <code>null</code>
@param req the current request
@param res the current response
@throws JspException in case something goes wrong | [
"Includes",
"the",
"selected",
"target",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagInclude.java#L156-L169 |
google/closure-compiler | src/com/google/javascript/jscomp/ExploitAssigns.java | ExploitAssigns.isCollapsibleValue | private static boolean isCollapsibleValue(Node value, boolean isLValue) {
"""
Determines whether we know enough about the given value to be able
to collapse it into subsequent expressions.
For example, we can collapse booleans and variable names:
<code>
x = 3; y = x; // y = x = 3;
a = true; b = true; // b = a = true;
<code>
But we won't try to collapse complex expressions.
@param value The value node.
@param isLValue Whether it's on the left-hand side of an expr.
"""
switch (value.getToken()) {
case GETPROP:
// Do not collapse GETPROPs on arbitrary objects, because
// they may be implemented setter functions, and oftentimes
// setter functions fail on native objects. This is OK for "THIS"
// objects, because we assume that they are non-native.
return !isLValue || value.getFirstChild().isThis();
case NAME:
return true;
default:
return NodeUtil.isImmutableValue(value);
}
} | java | private static boolean isCollapsibleValue(Node value, boolean isLValue) {
switch (value.getToken()) {
case GETPROP:
// Do not collapse GETPROPs on arbitrary objects, because
// they may be implemented setter functions, and oftentimes
// setter functions fail on native objects. This is OK for "THIS"
// objects, because we assume that they are non-native.
return !isLValue || value.getFirstChild().isThis();
case NAME:
return true;
default:
return NodeUtil.isImmutableValue(value);
}
} | [
"private",
"static",
"boolean",
"isCollapsibleValue",
"(",
"Node",
"value",
",",
"boolean",
"isLValue",
")",
"{",
"switch",
"(",
"value",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"GETPROP",
":",
"// Do not collapse GETPROPs on arbitrary objects, because",
"// they may be implemented setter functions, and oftentimes",
"// setter functions fail on native objects. This is OK for \"THIS\"",
"// objects, because we assume that they are non-native.",
"return",
"!",
"isLValue",
"||",
"value",
".",
"getFirstChild",
"(",
")",
".",
"isThis",
"(",
")",
";",
"case",
"NAME",
":",
"return",
"true",
";",
"default",
":",
"return",
"NodeUtil",
".",
"isImmutableValue",
"(",
"value",
")",
";",
"}",
"}"
] | Determines whether we know enough about the given value to be able
to collapse it into subsequent expressions.
For example, we can collapse booleans and variable names:
<code>
x = 3; y = x; // y = x = 3;
a = true; b = true; // b = a = true;
<code>
But we won't try to collapse complex expressions.
@param value The value node.
@param isLValue Whether it's on the left-hand side of an expr. | [
"Determines",
"whether",
"we",
"know",
"enough",
"about",
"the",
"given",
"value",
"to",
"be",
"able",
"to",
"collapse",
"it",
"into",
"subsequent",
"expressions",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExploitAssigns.java#L80-L95 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductSearchResultUrl.java | ProductSearchResultUrl.getRandomAccessCursorUrl | public static MozuUrl getRandomAccessCursorUrl(String filter, Integer pageSize, String query, String responseFields) {
"""
Get Resource Url for GetRandomAccessCursor
@param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
@param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
@param query Properties for the product location inventory provided for queries to locate products by their location.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/productsearch/randomAccessCursor/?query={query}&filter={filter}&pageSize={pageSize}&responseFields={responseFields}");
formatter.formatUrl("filter", filter);
formatter.formatUrl("pageSize", pageSize);
formatter.formatUrl("query", query);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getRandomAccessCursorUrl(String filter, Integer pageSize, String query, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/productsearch/randomAccessCursor/?query={query}&filter={filter}&pageSize={pageSize}&responseFields={responseFields}");
formatter.formatUrl("filter", filter);
formatter.formatUrl("pageSize", pageSize);
formatter.formatUrl("query", query);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getRandomAccessCursorUrl",
"(",
"String",
"filter",
",",
"Integer",
"pageSize",
",",
"String",
"query",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/storefront/productsearch/randomAccessCursor/?query={query}&filter={filter}&pageSize={pageSize}&responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"filter\"",
",",
"filter",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"pageSize\"",
",",
"pageSize",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"query\"",
",",
"query",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
] | Get Resource Url for GetRandomAccessCursor
@param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
@param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
@param query Properties for the product location inventory provided for queries to locate products by their location.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetRandomAccessCursor"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductSearchResultUrl.java#L24-L32 |
BellaDati/belladati-sdk-api | src/main/java/com/belladati/sdk/intervals/Interval.java | Interval.readInt | static int readInt(JsonNode node, String field) throws NumberFormatException {
"""
Reads a whole number from the given field of the node. Accepts numbers,
numerical strings and fractions.
@param node node from which to read
@param field name of the field to read
@return the field's int value
@throws NumberFormatException if the content cannot be parsed to a number
"""
String stringValue = node.get(field).asText();
return (int) Float.parseFloat(stringValue);
} | java | static int readInt(JsonNode node, String field) throws NumberFormatException {
String stringValue = node.get(field).asText();
return (int) Float.parseFloat(stringValue);
} | [
"static",
"int",
"readInt",
"(",
"JsonNode",
"node",
",",
"String",
"field",
")",
"throws",
"NumberFormatException",
"{",
"String",
"stringValue",
"=",
"node",
".",
"get",
"(",
"field",
")",
".",
"asText",
"(",
")",
";",
"return",
"(",
"int",
")",
"Float",
".",
"parseFloat",
"(",
"stringValue",
")",
";",
"}"
] | Reads a whole number from the given field of the node. Accepts numbers,
numerical strings and fractions.
@param node node from which to read
@param field name of the field to read
@return the field's int value
@throws NumberFormatException if the content cannot be parsed to a number | [
"Reads",
"a",
"whole",
"number",
"from",
"the",
"given",
"field",
"of",
"the",
"node",
".",
"Accepts",
"numbers",
"numerical",
"strings",
"and",
"fractions",
"."
] | train | https://github.com/BellaDati/belladati-sdk-api/blob/ec45a42048d8255838ad0200aa6784a8e8a121c1/src/main/java/com/belladati/sdk/intervals/Interval.java#L91-L94 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java | FeatureScopes.createStaticFeaturesScope | protected IScope createStaticFeaturesScope(EObject featureCall, IScope parent, IFeatureScopeSession session) {
"""
Creates a scope for the statically imported features.
@param featureCall the feature call that is currently processed by the scoping infrastructure
@param parent the parent scope. Is never null.
@param session the currently known scope session. Is never null.
"""
return new StaticImportsScope(parent, session, asAbstractFeatureCall(featureCall));
} | java | protected IScope createStaticFeaturesScope(EObject featureCall, IScope parent, IFeatureScopeSession session) {
return new StaticImportsScope(parent, session, asAbstractFeatureCall(featureCall));
} | [
"protected",
"IScope",
"createStaticFeaturesScope",
"(",
"EObject",
"featureCall",
",",
"IScope",
"parent",
",",
"IFeatureScopeSession",
"session",
")",
"{",
"return",
"new",
"StaticImportsScope",
"(",
"parent",
",",
"session",
",",
"asAbstractFeatureCall",
"(",
"featureCall",
")",
")",
";",
"}"
] | Creates a scope for the statically imported features.
@param featureCall the feature call that is currently processed by the scoping infrastructure
@param parent the parent scope. Is never null.
@param session the currently known scope session. Is never null. | [
"Creates",
"a",
"scope",
"for",
"the",
"statically",
"imported",
"features",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java#L616-L618 |
netty/netty | common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java | SystemPropertyUtil.getBoolean | public static boolean getBoolean(String key, boolean def) {
"""
Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed.
"""
String value = get(key);
if (value == null) {
return def;
}
value = value.trim().toLowerCase();
if (value.isEmpty()) {
return def;
}
if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
return true;
}
if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
return false;
}
logger.warn(
"Unable to parse the boolean system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | java | public static boolean getBoolean(String key, boolean def) {
String value = get(key);
if (value == null) {
return def;
}
value = value.trim().toLowerCase();
if (value.isEmpty()) {
return def;
}
if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
return true;
}
if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
return false;
}
logger.warn(
"Unable to parse the boolean system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | [
"public",
"static",
"boolean",
"getBoolean",
"(",
"String",
"key",
",",
"boolean",
"def",
")",
"{",
"String",
"value",
"=",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"def",
";",
"}",
"value",
"=",
"value",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"value",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"def",
";",
"}",
"if",
"(",
"\"true\"",
".",
"equals",
"(",
"value",
")",
"||",
"\"yes\"",
".",
"equals",
"(",
"value",
")",
"||",
"\"1\"",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"\"false\"",
".",
"equals",
"(",
"value",
")",
"||",
"\"no\"",
".",
"equals",
"(",
"value",
")",
"||",
"\"0\"",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"logger",
".",
"warn",
"(",
"\"Unable to parse the boolean system property '{}':{} - using the default value: {}\"",
",",
"key",
",",
"value",
",",
"def",
")",
";",
"return",
"def",
";",
"}"
] | Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed. | [
"Returns",
"the",
"value",
"of",
"the",
"Java",
"system",
"property",
"with",
"the",
"specified",
"{",
"@code",
"key",
"}",
"while",
"falling",
"back",
"to",
"the",
"specified",
"default",
"value",
"if",
"the",
"property",
"access",
"fails",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/SystemPropertyUtil.java#L98-L123 |
phax/ph-commons | ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java | JAXBContextCache.getFromCache | @Nullable
public JAXBContext getFromCache (@Nonnull final Class <?> aClass, @Nullable final ClassLoader aClassLoader) {
"""
Get the {@link JAXBContext} from an existing {@link Class} object. If the
class's owning package is a valid JAXB package, this method redirects to
{@link #getFromCache(Package)} otherwise a new JAXB context is created and
NOT cached.
@param aClass
The class for which the JAXB context is to be created. May not be
<code>null</code>.
@param aClassLoader
Class loader to use. May be <code>null</code> in which case the
default class loader is used.
@return May be <code>null</code>.
"""
ValueEnforcer.notNull (aClass, "Class");
final Package aPackage = aClass.getPackage ();
if (aPackage.getAnnotation (XmlSchema.class) != null)
{
// Redirect to cached version
return getFromCache (aPackage, aClassLoader);
}
// E.g. an internal class - try anyway!
if (GlobalDebug.isDebugMode ())
LOGGER.info ("Creating JAXB context for class " + aClass.getName ());
if (aClassLoader != null)
LOGGER.warn ("Package " +
aPackage.getName () +
" does not seem to be JAXB generated. Therefore a new JAXBContext is created and the provided ClassLoader is ignored!");
try
{
// Using the version with a ClassLoader would require an
// ObjectFactory.class or an jaxb.index file in the same package!
return JAXBContext.newInstance (aClass);
}
catch (final JAXBException ex)
{
final String sMsg = "Failed to create JAXB context for class '" + aClass.getName () + "'";
LOGGER.error (sMsg + ": " + ex.getMessage ());
throw new IllegalArgumentException (sMsg, ex);
}
} | java | @Nullable
public JAXBContext getFromCache (@Nonnull final Class <?> aClass, @Nullable final ClassLoader aClassLoader)
{
ValueEnforcer.notNull (aClass, "Class");
final Package aPackage = aClass.getPackage ();
if (aPackage.getAnnotation (XmlSchema.class) != null)
{
// Redirect to cached version
return getFromCache (aPackage, aClassLoader);
}
// E.g. an internal class - try anyway!
if (GlobalDebug.isDebugMode ())
LOGGER.info ("Creating JAXB context for class " + aClass.getName ());
if (aClassLoader != null)
LOGGER.warn ("Package " +
aPackage.getName () +
" does not seem to be JAXB generated. Therefore a new JAXBContext is created and the provided ClassLoader is ignored!");
try
{
// Using the version with a ClassLoader would require an
// ObjectFactory.class or an jaxb.index file in the same package!
return JAXBContext.newInstance (aClass);
}
catch (final JAXBException ex)
{
final String sMsg = "Failed to create JAXB context for class '" + aClass.getName () + "'";
LOGGER.error (sMsg + ": " + ex.getMessage ());
throw new IllegalArgumentException (sMsg, ex);
}
} | [
"@",
"Nullable",
"public",
"JAXBContext",
"getFromCache",
"(",
"@",
"Nonnull",
"final",
"Class",
"<",
"?",
">",
"aClass",
",",
"@",
"Nullable",
"final",
"ClassLoader",
"aClassLoader",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aClass",
",",
"\"Class\"",
")",
";",
"final",
"Package",
"aPackage",
"=",
"aClass",
".",
"getPackage",
"(",
")",
";",
"if",
"(",
"aPackage",
".",
"getAnnotation",
"(",
"XmlSchema",
".",
"class",
")",
"!=",
"null",
")",
"{",
"// Redirect to cached version",
"return",
"getFromCache",
"(",
"aPackage",
",",
"aClassLoader",
")",
";",
"}",
"// E.g. an internal class - try anyway!",
"if",
"(",
"GlobalDebug",
".",
"isDebugMode",
"(",
")",
")",
"LOGGER",
".",
"info",
"(",
"\"Creating JAXB context for class \"",
"+",
"aClass",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"aClassLoader",
"!=",
"null",
")",
"LOGGER",
".",
"warn",
"(",
"\"Package \"",
"+",
"aPackage",
".",
"getName",
"(",
")",
"+",
"\" does not seem to be JAXB generated. Therefore a new JAXBContext is created and the provided ClassLoader is ignored!\"",
")",
";",
"try",
"{",
"// Using the version with a ClassLoader would require an",
"// ObjectFactory.class or an jaxb.index file in the same package!",
"return",
"JAXBContext",
".",
"newInstance",
"(",
"aClass",
")",
";",
"}",
"catch",
"(",
"final",
"JAXBException",
"ex",
")",
"{",
"final",
"String",
"sMsg",
"=",
"\"Failed to create JAXB context for class '\"",
"+",
"aClass",
".",
"getName",
"(",
")",
"+",
"\"'\"",
";",
"LOGGER",
".",
"error",
"(",
"sMsg",
"+",
"\": \"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"sMsg",
",",
"ex",
")",
";",
"}",
"}"
] | Get the {@link JAXBContext} from an existing {@link Class} object. If the
class's owning package is a valid JAXB package, this method redirects to
{@link #getFromCache(Package)} otherwise a new JAXB context is created and
NOT cached.
@param aClass
The class for which the JAXB context is to be created. May not be
<code>null</code>.
@param aClassLoader
Class loader to use. May be <code>null</code> in which case the
default class loader is used.
@return May be <code>null</code>. | [
"Get",
"the",
"{",
"@link",
"JAXBContext",
"}",
"from",
"an",
"existing",
"{",
"@link",
"Class",
"}",
"object",
".",
"If",
"the",
"class",
"s",
"owning",
"package",
"is",
"a",
"valid",
"JAXB",
"package",
"this",
"method",
"redirects",
"to",
"{",
"@link",
"#getFromCache",
"(",
"Package",
")",
"}",
"otherwise",
"a",
"new",
"JAXB",
"context",
"is",
"created",
"and",
"NOT",
"cached",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java#L169-L202 |
sculptor/sculptor | sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java | HelperBase.handleSimpleAnnotation | public String handleSimpleAnnotation(String annotation, String value, String validate) {
"""
Handles all simple validation annotations (Max, Min, ...).
@param annotation
the name of the annotation
@param value
the parameter values
@param validate
the validate string
@return annotation validation string
"""
if (value == null)
return "";
// if validate contains annotation, do nothing
if (validate != null && validate.toLowerCase().matches(".*@" + annotation.toLowerCase() + ".*"))
return "";
String result = " @" + annotation;
// if validate contains named annotation parameters
if (value.toLowerCase().matches(".*value.*") || value.toLowerCase().matches(".*message.*")) {
result += "(" + value + ") ";
return result + " ";
}
// a simple annotation only has parameters value and message
String[] params = value.split(",");
if (params.length == 1)
result += "(" + params[0] + ")";
if (params.length == 2)
result += "(value=" + params[0] + ", message=" + params[1] + ")";
return result + " ";
} | java | public String handleSimpleAnnotation(String annotation, String value, String validate) {
if (value == null)
return "";
// if validate contains annotation, do nothing
if (validate != null && validate.toLowerCase().matches(".*@" + annotation.toLowerCase() + ".*"))
return "";
String result = " @" + annotation;
// if validate contains named annotation parameters
if (value.toLowerCase().matches(".*value.*") || value.toLowerCase().matches(".*message.*")) {
result += "(" + value + ") ";
return result + " ";
}
// a simple annotation only has parameters value and message
String[] params = value.split(",");
if (params.length == 1)
result += "(" + params[0] + ")";
if (params.length == 2)
result += "(value=" + params[0] + ", message=" + params[1] + ")";
return result + " ";
} | [
"public",
"String",
"handleSimpleAnnotation",
"(",
"String",
"annotation",
",",
"String",
"value",
",",
"String",
"validate",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"\"\"",
";",
"// if validate contains annotation, do nothing",
"if",
"(",
"validate",
"!=",
"null",
"&&",
"validate",
".",
"toLowerCase",
"(",
")",
".",
"matches",
"(",
"\".*@\"",
"+",
"annotation",
".",
"toLowerCase",
"(",
")",
"+",
"\".*\"",
")",
")",
"return",
"\"\"",
";",
"String",
"result",
"=",
"\" @\"",
"+",
"annotation",
";",
"// if validate contains named annotation parameters",
"if",
"(",
"value",
".",
"toLowerCase",
"(",
")",
".",
"matches",
"(",
"\".*value.*\"",
")",
"||",
"value",
".",
"toLowerCase",
"(",
")",
".",
"matches",
"(",
"\".*message.*\"",
")",
")",
"{",
"result",
"+=",
"\"(\"",
"+",
"value",
"+",
"\") \"",
";",
"return",
"result",
"+",
"\" \"",
";",
"}",
"// a simple annotation only has parameters value and message",
"String",
"[",
"]",
"params",
"=",
"value",
".",
"split",
"(",
"\",\"",
")",
";",
"if",
"(",
"params",
".",
"length",
"==",
"1",
")",
"result",
"+=",
"\"(\"",
"+",
"params",
"[",
"0",
"]",
"+",
"\")\"",
";",
"if",
"(",
"params",
".",
"length",
"==",
"2",
")",
"result",
"+=",
"\"(value=\"",
"+",
"params",
"[",
"0",
"]",
"+",
"\", message=\"",
"+",
"params",
"[",
"1",
"]",
"+",
"\")\"",
";",
"return",
"result",
"+",
"\" \"",
";",
"}"
] | Handles all simple validation annotations (Max, Min, ...).
@param annotation
the name of the annotation
@param value
the parameter values
@param validate
the validate string
@return annotation validation string | [
"Handles",
"all",
"simple",
"validation",
"annotations",
"(",
"Max",
"Min",
"...",
")",
"."
] | train | https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java#L1132-L1157 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/pipeline/Pipelines.java | Pipelines.watchers | public static Pipeline watchers(MavenSession session, File baseDir, Mojo mojo, boolean pomFileMonitoring) {
"""
Creates a 'watching' pipeline.
@param session the maven session
@param baseDir the project's base directory
@param mojo the 'run' mojo
@param pomFileMonitoring flag enabling or disabling the pom file monitoring
@return the created pipeline
"""
return new Pipeline(mojo, baseDir, Watchers.all(session), pomFileMonitoring);
} | java | public static Pipeline watchers(MavenSession session, File baseDir, Mojo mojo, boolean pomFileMonitoring) {
return new Pipeline(mojo, baseDir, Watchers.all(session), pomFileMonitoring);
} | [
"public",
"static",
"Pipeline",
"watchers",
"(",
"MavenSession",
"session",
",",
"File",
"baseDir",
",",
"Mojo",
"mojo",
",",
"boolean",
"pomFileMonitoring",
")",
"{",
"return",
"new",
"Pipeline",
"(",
"mojo",
",",
"baseDir",
",",
"Watchers",
".",
"all",
"(",
"session",
")",
",",
"pomFileMonitoring",
")",
";",
"}"
] | Creates a 'watching' pipeline.
@param session the maven session
@param baseDir the project's base directory
@param mojo the 'run' mojo
@param pomFileMonitoring flag enabling or disabling the pom file monitoring
@return the created pipeline | [
"Creates",
"a",
"watching",
"pipeline",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/pipeline/Pipelines.java#L41-L43 |
FudanNLP/fnlp | fnlp-core/src/main/java/org/fnlp/nlp/langmodel/lda/LdaGibbsSampler.java | LdaGibbsSampler.shadefloat | public static String shadefloat(float d, float max) {
"""
create a string representation whose gray value appears as an indicator
of magnitude, cf. Hinton diagrams in statistics.
@param d
value
@param max
maximum value
@return
"""
int a = (int) Math.floor(d * 10 / max + 0.5);
if (a > 10 || a < 0) {
String x = lnf.format(d);
a = 5 - x.length();
for (int i = 0; i < a; i++) {
x += " ";
}
return "<" + x + ">";
}
return "[" + shades[a] + "]";
} | java | public static String shadefloat(float d, float max) {
int a = (int) Math.floor(d * 10 / max + 0.5);
if (a > 10 || a < 0) {
String x = lnf.format(d);
a = 5 - x.length();
for (int i = 0; i < a; i++) {
x += " ";
}
return "<" + x + ">";
}
return "[" + shades[a] + "]";
} | [
"public",
"static",
"String",
"shadefloat",
"(",
"float",
"d",
",",
"float",
"max",
")",
"{",
"int",
"a",
"=",
"(",
"int",
")",
"Math",
".",
"floor",
"(",
"d",
"*",
"10",
"/",
"max",
"+",
"0.5",
")",
";",
"if",
"(",
"a",
">",
"10",
"||",
"a",
"<",
"0",
")",
"{",
"String",
"x",
"=",
"lnf",
".",
"format",
"(",
"d",
")",
";",
"a",
"=",
"5",
"-",
"x",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"a",
";",
"i",
"++",
")",
"{",
"x",
"+=",
"\" \"",
";",
"}",
"return",
"\"<\"",
"+",
"x",
"+",
"\">\"",
";",
"}",
"return",
"\"[\"",
"+",
"shades",
"[",
"a",
"]",
"+",
"\"]\"",
";",
"}"
] | create a string representation whose gray value appears as an indicator
of magnitude, cf. Hinton diagrams in statistics.
@param d
value
@param max
maximum value
@return | [
"create",
"a",
"string",
"representation",
"whose",
"gray",
"value",
"appears",
"as",
"an",
"indicator",
"of",
"magnitude",
"cf",
".",
"Hinton",
"diagrams",
"in",
"statistics",
"."
] | train | https://github.com/FudanNLP/fnlp/blob/ce258f3e4a5add2ba0b5e4cbac7cab2190af6659/fnlp-core/src/main/java/org/fnlp/nlp/langmodel/lda/LdaGibbsSampler.java#L547-L558 |
guardtime/ksi-java-sdk | ksi-common/src/main/java/com/guardtime/ksi/util/Util.java | Util.loadKeyStore | public static KeyStore loadKeyStore(File file, String password) throws KSIException {
"""
Loads and returns the {@link java.security.KeyStore} from the file system.
@param file file to load from file system.
@param password password to access the keystore.
@return {@link java.security.KeyStore}
@throws KSIException
"""
notNull(file, "Trust store file");
FileInputStream input = null;
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance("JKS");
char[] passwordCharArray = password == null ? null : password.toCharArray();
input = new FileInputStream(file);
keyStore.load(input, passwordCharArray);
} catch (GeneralSecurityException | IOException e) {
throw new KSIException("Loading java key store with path " + file + " failed", e);
} finally {
closeQuietly(input);
}
return keyStore;
} | java | public static KeyStore loadKeyStore(File file, String password) throws KSIException {
notNull(file, "Trust store file");
FileInputStream input = null;
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance("JKS");
char[] passwordCharArray = password == null ? null : password.toCharArray();
input = new FileInputStream(file);
keyStore.load(input, passwordCharArray);
} catch (GeneralSecurityException | IOException e) {
throw new KSIException("Loading java key store with path " + file + " failed", e);
} finally {
closeQuietly(input);
}
return keyStore;
} | [
"public",
"static",
"KeyStore",
"loadKeyStore",
"(",
"File",
"file",
",",
"String",
"password",
")",
"throws",
"KSIException",
"{",
"notNull",
"(",
"file",
",",
"\"Trust store file\"",
")",
";",
"FileInputStream",
"input",
"=",
"null",
";",
"KeyStore",
"keyStore",
"=",
"null",
";",
"try",
"{",
"keyStore",
"=",
"KeyStore",
".",
"getInstance",
"(",
"\"JKS\"",
")",
";",
"char",
"[",
"]",
"passwordCharArray",
"=",
"password",
"==",
"null",
"?",
"null",
":",
"password",
".",
"toCharArray",
"(",
")",
";",
"input",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"keyStore",
".",
"load",
"(",
"input",
",",
"passwordCharArray",
")",
";",
"}",
"catch",
"(",
"GeneralSecurityException",
"|",
"IOException",
"e",
")",
"{",
"throw",
"new",
"KSIException",
"(",
"\"Loading java key store with path \"",
"+",
"file",
"+",
"\" failed\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"closeQuietly",
"(",
"input",
")",
";",
"}",
"return",
"keyStore",
";",
"}"
] | Loads and returns the {@link java.security.KeyStore} from the file system.
@param file file to load from file system.
@param password password to access the keystore.
@return {@link java.security.KeyStore}
@throws KSIException | [
"Loads",
"and",
"returns",
"the",
"{",
"@link",
"java",
".",
"security",
".",
"KeyStore",
"}",
"from",
"the",
"file",
"system",
"."
] | train | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/util/Util.java#L782-L797 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/subset/neigh/SinglePerturbationNeighbourhood.java | SinglePerturbationNeighbourhood.canSwap | private boolean canSwap(SubsetSolution solution, Set<Integer> addCandidates, Set<Integer> deleteCandidates) {
"""
Check if it is possible to swap a selected and unselected item.
@param solution solution for which moves are generated
@param addCandidates set of candidate IDs to be added
@param deleteCandidates set of candidate IDs to be deleted
@return <code>true</code> if it is possible to perform a swap
"""
return !addCandidates.isEmpty()
&& !deleteCandidates.isEmpty()
&& isValidSubsetSize(solution.getNumSelectedIDs());
} | java | private boolean canSwap(SubsetSolution solution, Set<Integer> addCandidates, Set<Integer> deleteCandidates){
return !addCandidates.isEmpty()
&& !deleteCandidates.isEmpty()
&& isValidSubsetSize(solution.getNumSelectedIDs());
} | [
"private",
"boolean",
"canSwap",
"(",
"SubsetSolution",
"solution",
",",
"Set",
"<",
"Integer",
">",
"addCandidates",
",",
"Set",
"<",
"Integer",
">",
"deleteCandidates",
")",
"{",
"return",
"!",
"addCandidates",
".",
"isEmpty",
"(",
")",
"&&",
"!",
"deleteCandidates",
".",
"isEmpty",
"(",
")",
"&&",
"isValidSubsetSize",
"(",
"solution",
".",
"getNumSelectedIDs",
"(",
")",
")",
";",
"}"
] | Check if it is possible to swap a selected and unselected item.
@param solution solution for which moves are generated
@param addCandidates set of candidate IDs to be added
@param deleteCandidates set of candidate IDs to be deleted
@return <code>true</code> if it is possible to perform a swap | [
"Check",
"if",
"it",
"is",
"possible",
"to",
"swap",
"a",
"selected",
"and",
"unselected",
"item",
"."
] | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/SinglePerturbationNeighbourhood.java#L246-L250 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/process/ProcessAdapter.java | ProcessAdapter.waitFor | public boolean waitFor(long timeout, TimeUnit unit) {
"""
Waits until the specified timeout for this {@link Process} to stop.
This method handles the {@link InterruptedException} thrown by {@link Process#waitFor(long, TimeUnit)}
by resetting the interrupt bit on the current (calling) {@link Thread}.
@param timeout long value to indicate the number of units in the timeout.
@param unit {@link TimeUnit} of the timeout (e.g. seconds).
@return a boolean value indicating whether the {@link Process} stopped within the given timeout.
@see java.lang.Process#waitFor(long, TimeUnit)
@see #isNotRunning()
"""
try {
return getProcess().waitFor(timeout, unit);
}
catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
return isNotRunning();
}
} | java | public boolean waitFor(long timeout, TimeUnit unit) {
try {
return getProcess().waitFor(timeout, unit);
}
catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
return isNotRunning();
}
} | [
"public",
"boolean",
"waitFor",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"try",
"{",
"return",
"getProcess",
"(",
")",
".",
"waitFor",
"(",
"timeout",
",",
"unit",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ignore",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"return",
"isNotRunning",
"(",
")",
";",
"}",
"}"
] | Waits until the specified timeout for this {@link Process} to stop.
This method handles the {@link InterruptedException} thrown by {@link Process#waitFor(long, TimeUnit)}
by resetting the interrupt bit on the current (calling) {@link Thread}.
@param timeout long value to indicate the number of units in the timeout.
@param unit {@link TimeUnit} of the timeout (e.g. seconds).
@return a boolean value indicating whether the {@link Process} stopped within the given timeout.
@see java.lang.Process#waitFor(long, TimeUnit)
@see #isNotRunning() | [
"Waits",
"until",
"the",
"specified",
"timeout",
"for",
"this",
"{",
"@link",
"Process",
"}",
"to",
"stop",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/process/ProcessAdapter.java#L677-L685 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.containsKeyFailure | @Override
public boolean containsKeyFailure(K key, StoreAccessException e) {
"""
Return false. It doesn't matter if the key is present in the backend, we consider it's not in the cache.
@param key the key being queried
@param e the triggered failure
@return false
"""
cleanup(key, e);
return false;
} | java | @Override
public boolean containsKeyFailure(K key, StoreAccessException e) {
cleanup(key, e);
return false;
} | [
"@",
"Override",
"public",
"boolean",
"containsKeyFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"key",
",",
"e",
")",
";",
"return",
"false",
";",
"}"
] | Return false. It doesn't matter if the key is present in the backend, we consider it's not in the cache.
@param key the key being queried
@param e the triggered failure
@return false | [
"Return",
"false",
".",
"It",
"doesn",
"t",
"matter",
"if",
"the",
"key",
"is",
"present",
"in",
"the",
"backend",
"we",
"consider",
"it",
"s",
"not",
"in",
"the",
"cache",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L73-L77 |
landawn/AbacusUtil | src/com/landawn/abacus/util/StringUtil.java | StringUtil.removeEnd | public static String removeEnd(final String str, final String removeStr) {
"""
<p>
Removes a substring only if it is at the end of a source string,
otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeEnd(null, *) = null
N.removeEnd("", *) = ""
N.removeEnd(*, null) = *
N.removeEnd("www.domain.com", ".com.") = "www.domain.com"
N.removeEnd("www.domain.com", ".com") = "www.domain"
N.removeEnd("www.domain.com", "domain") = "www.domain.com"
N.removeEnd("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for and remove, may be null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.1
"""
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (str.endsWith(removeStr)) {
return str.substring(0, str.length() - removeStr.length());
}
return str;
} | java | public static String removeEnd(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (str.endsWith(removeStr)) {
return str.substring(0, str.length() - removeStr.length());
}
return str;
} | [
"public",
"static",
"String",
"removeEnd",
"(",
"final",
"String",
"str",
",",
"final",
"String",
"removeStr",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"str",
")",
"||",
"N",
".",
"isNullOrEmpty",
"(",
"removeStr",
")",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"str",
".",
"endsWith",
"(",
"removeStr",
")",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"0",
",",
"str",
".",
"length",
"(",
")",
"-",
"removeStr",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"str",
";",
"}"
] | <p>
Removes a substring only if it is at the end of a source string,
otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeEnd(null, *) = null
N.removeEnd("", *) = ""
N.removeEnd(*, null) = *
N.removeEnd("www.domain.com", ".com.") = "www.domain.com"
N.removeEnd("www.domain.com", ".com") = "www.domain"
N.removeEnd("www.domain.com", "domain") = "www.domain.com"
N.removeEnd("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for and remove, may be null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.1 | [
"<p",
">",
"Removes",
"a",
"substring",
"only",
"if",
"it",
"is",
"at",
"the",
"end",
"of",
"a",
"source",
"string",
"otherwise",
"returns",
"the",
"source",
"string",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1233-L1243 |
tvesalainen/hoski-lib | src/main/java/fi/hoski/datastore/repository/DataObjectModel.java | DataObjectModel.view | public DataObjectModel view(int from, int to) {
"""
Returns a clone of this model where only propertyList starting from from
ending to to (exclusive) are present.
@param from
@param to
@return
"""
DataObjectModel view = clone();
view.propertyList = propertyList.subList(from, to);
return view;
} | java | public DataObjectModel view(int from, int to)
{
DataObjectModel view = clone();
view.propertyList = propertyList.subList(from, to);
return view;
} | [
"public",
"DataObjectModel",
"view",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"DataObjectModel",
"view",
"=",
"clone",
"(",
")",
";",
"view",
".",
"propertyList",
"=",
"propertyList",
".",
"subList",
"(",
"from",
",",
"to",
")",
";",
"return",
"view",
";",
"}"
] | Returns a clone of this model where only propertyList starting from from
ending to to (exclusive) are present.
@param from
@param to
@return | [
"Returns",
"a",
"clone",
"of",
"this",
"model",
"where",
"only",
"propertyList",
"starting",
"from",
"from",
"ending",
"to",
"to",
"(",
"exclusive",
")",
"are",
"present",
"."
] | train | https://github.com/tvesalainen/hoski-lib/blob/9b5bab44113e0adb74bf1ee436013e8a7c608d00/src/main/java/fi/hoski/datastore/repository/DataObjectModel.java#L173-L178 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/RepositoryNodeTypeManager.java | RepositoryNodeTypeManager.registerNodeType | JcrNodeType registerNodeType( NodeTypeDefinition ntd )
throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, RepositoryException {
"""
Registers a new node type or updates an existing node type using the specified definition and returns the resulting
{@code NodeType} object.
<p>
For details, see {@link #registerNodeTypes(Iterable)}.
</p>
@param ntd the {@code NodeTypeDefinition} to register
@return the newly registered (or updated) {@code NodeType}
@throws InvalidNodeTypeDefinitionException if the {@code NodeTypeDefinition} is invalid
@throws NodeTypeExistsException if <code>allowUpdate</code> is false and the {@code NodeTypeDefinition} specifies a node
type name that is already registered
@throws RepositoryException if another error occurs
"""
return registerNodeType(ntd, true);
} | java | JcrNodeType registerNodeType( NodeTypeDefinition ntd )
throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, RepositoryException {
return registerNodeType(ntd, true);
} | [
"JcrNodeType",
"registerNodeType",
"(",
"NodeTypeDefinition",
"ntd",
")",
"throws",
"InvalidNodeTypeDefinitionException",
",",
"NodeTypeExistsException",
",",
"RepositoryException",
"{",
"return",
"registerNodeType",
"(",
"ntd",
",",
"true",
")",
";",
"}"
] | Registers a new node type or updates an existing node type using the specified definition and returns the resulting
{@code NodeType} object.
<p>
For details, see {@link #registerNodeTypes(Iterable)}.
</p>
@param ntd the {@code NodeTypeDefinition} to register
@return the newly registered (or updated) {@code NodeType}
@throws InvalidNodeTypeDefinitionException if the {@code NodeTypeDefinition} is invalid
@throws NodeTypeExistsException if <code>allowUpdate</code> is false and the {@code NodeTypeDefinition} specifies a node
type name that is already registered
@throws RepositoryException if another error occurs | [
"Registers",
"a",
"new",
"node",
"type",
"or",
"updates",
"an",
"existing",
"node",
"type",
"using",
"the",
"specified",
"definition",
"and",
"returns",
"the",
"resulting",
"{",
"@code",
"NodeType",
"}",
"object",
".",
"<p",
">",
"For",
"details",
"see",
"{",
"@link",
"#registerNodeTypes",
"(",
"Iterable",
")",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/RepositoryNodeTypeManager.java#L360-L364 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/data/conversion/converters/CharacterConverter.java | CharacterConverter.canConvert | @Override
public boolean canConvert(Class<?> fromType, Class<?> toType) {
"""
Determines whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@param fromType {@link Class type} to convert from.
@param toType {@link Class type} to convert to.
@return a boolean indicating whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@see org.cp.elements.data.conversion.ConversionService#canConvert(Class, Class)
@see #canConvert(Object, Class)
"""
return isAssignableTo(fromType, Character.class, String.class) && Character.class.equals(toType);
} | java | @Override
public boolean canConvert(Class<?> fromType, Class<?> toType) {
return isAssignableTo(fromType, Character.class, String.class) && Character.class.equals(toType);
} | [
"@",
"Override",
"public",
"boolean",
"canConvert",
"(",
"Class",
"<",
"?",
">",
"fromType",
",",
"Class",
"<",
"?",
">",
"toType",
")",
"{",
"return",
"isAssignableTo",
"(",
"fromType",
",",
"Character",
".",
"class",
",",
"String",
".",
"class",
")",
"&&",
"Character",
".",
"class",
".",
"equals",
"(",
"toType",
")",
";",
"}"
] | Determines whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@param fromType {@link Class type} to convert from.
@param toType {@link Class type} to convert to.
@return a boolean indicating whether this {@link Converter} can convert {@link Object Objects}
{@link Class from type} {@link Class to type}.
@see org.cp.elements.data.conversion.ConversionService#canConvert(Class, Class)
@see #canConvert(Object, Class) | [
"Determines",
"whether",
"this",
"{",
"@link",
"Converter",
"}",
"can",
"convert",
"{",
"@link",
"Object",
"Objects",
"}",
"{",
"@link",
"Class",
"from",
"type",
"}",
"{",
"@link",
"Class",
"to",
"type",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/conversion/converters/CharacterConverter.java#L46-L49 |
ReactiveX/RxGroovy | src/main/java/rx/lang/groovy/RxGroovyExtensionModule.java | RxGroovyExtensionModule.specialCasedOverrideForCreate | private MetaMethod specialCasedOverrideForCreate(final Method m) {
"""
Special case until we finish migrating off the deprecated 'create' method signature
"""
return new MetaMethod() {
@Override
public int getModifiers() {
return m.getModifiers();
}
@Override
public String getName() {
return m.getName();
}
@Override
public Class<?> getReturnType() {
return m.getReturnType();
}
@Override
public CachedClass getDeclaringClass() {
return ReflectionCache.getCachedClass(m.getDeclaringClass());
}
@Override
@SuppressWarnings("unchecked")
public Object invoke(Object object, final Object[] arguments) {
return Observable.create(new GroovyCreateWrapper((Closure) arguments[0]));
}
@Override
public CachedClass[] getParameterTypes() {
if (parameterTypes == null) {
getParametersTypes0();
}
return parameterTypes;
}
private synchronized void getParametersTypes0() {
if (parameterTypes != null)
return;
Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes;
CachedClass[] pt = new CachedClass [npt.length];
for (int i = 0; i != npt.length; ++i) {
if (Function.class.isAssignableFrom(npt[i])) {
// function type to be replaced by closure
pt[i] = ReflectionCache.getCachedClass(Closure.class);
} else {
// non-function type
pt[i] = ReflectionCache.getCachedClass(npt[i]);
}
}
nativeParamTypes = npt;
setParametersTypes(pt);
}
@Override
protected Class[] getPT() {
return m.getParameterTypes();
}
};
} | java | private MetaMethod specialCasedOverrideForCreate(final Method m) {
return new MetaMethod() {
@Override
public int getModifiers() {
return m.getModifiers();
}
@Override
public String getName() {
return m.getName();
}
@Override
public Class<?> getReturnType() {
return m.getReturnType();
}
@Override
public CachedClass getDeclaringClass() {
return ReflectionCache.getCachedClass(m.getDeclaringClass());
}
@Override
@SuppressWarnings("unchecked")
public Object invoke(Object object, final Object[] arguments) {
return Observable.create(new GroovyCreateWrapper((Closure) arguments[0]));
}
@Override
public CachedClass[] getParameterTypes() {
if (parameterTypes == null) {
getParametersTypes0();
}
return parameterTypes;
}
private synchronized void getParametersTypes0() {
if (parameterTypes != null)
return;
Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes;
CachedClass[] pt = new CachedClass [npt.length];
for (int i = 0; i != npt.length; ++i) {
if (Function.class.isAssignableFrom(npt[i])) {
// function type to be replaced by closure
pt[i] = ReflectionCache.getCachedClass(Closure.class);
} else {
// non-function type
pt[i] = ReflectionCache.getCachedClass(npt[i]);
}
}
nativeParamTypes = npt;
setParametersTypes(pt);
}
@Override
protected Class[] getPT() {
return m.getParameterTypes();
}
};
} | [
"private",
"MetaMethod",
"specialCasedOverrideForCreate",
"(",
"final",
"Method",
"m",
")",
"{",
"return",
"new",
"MetaMethod",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"getModifiers",
"(",
")",
"{",
"return",
"m",
".",
"getModifiers",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"m",
".",
"getName",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Class",
"<",
"?",
">",
"getReturnType",
"(",
")",
"{",
"return",
"m",
".",
"getReturnType",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"CachedClass",
"getDeclaringClass",
"(",
")",
"{",
"return",
"ReflectionCache",
".",
"getCachedClass",
"(",
"m",
".",
"getDeclaringClass",
"(",
")",
")",
";",
"}",
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"Object",
"invoke",
"(",
"Object",
"object",
",",
"final",
"Object",
"[",
"]",
"arguments",
")",
"{",
"return",
"Observable",
".",
"create",
"(",
"new",
"GroovyCreateWrapper",
"(",
"(",
"Closure",
")",
"arguments",
"[",
"0",
"]",
")",
")",
";",
"}",
"@",
"Override",
"public",
"CachedClass",
"[",
"]",
"getParameterTypes",
"(",
")",
"{",
"if",
"(",
"parameterTypes",
"==",
"null",
")",
"{",
"getParametersTypes0",
"(",
")",
";",
"}",
"return",
"parameterTypes",
";",
"}",
"private",
"synchronized",
"void",
"getParametersTypes0",
"(",
")",
"{",
"if",
"(",
"parameterTypes",
"!=",
"null",
")",
"return",
";",
"Class",
"[",
"]",
"npt",
"=",
"nativeParamTypes",
"==",
"null",
"?",
"getPT",
"(",
")",
":",
"nativeParamTypes",
";",
"CachedClass",
"[",
"]",
"pt",
"=",
"new",
"CachedClass",
"[",
"npt",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"!=",
"npt",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"Function",
".",
"class",
".",
"isAssignableFrom",
"(",
"npt",
"[",
"i",
"]",
")",
")",
"{",
"// function type to be replaced by closure",
"pt",
"[",
"i",
"]",
"=",
"ReflectionCache",
".",
"getCachedClass",
"(",
"Closure",
".",
"class",
")",
";",
"}",
"else",
"{",
"// non-function type",
"pt",
"[",
"i",
"]",
"=",
"ReflectionCache",
".",
"getCachedClass",
"(",
"npt",
"[",
"i",
"]",
")",
";",
"}",
"}",
"nativeParamTypes",
"=",
"npt",
";",
"setParametersTypes",
"(",
"pt",
")",
";",
"}",
"@",
"Override",
"protected",
"Class",
"[",
"]",
"getPT",
"(",
")",
"{",
"return",
"m",
".",
"getParameterTypes",
"(",
")",
";",
"}",
"}",
";",
"}"
] | Special case until we finish migrating off the deprecated 'create' method signature | [
"Special",
"case",
"until",
"we",
"finish",
"migrating",
"off",
"the",
"deprecated",
"create",
"method",
"signature"
] | train | https://github.com/ReactiveX/RxGroovy/blob/57ac7a44a6a1d5ce3bfaaf35c52d8594034a1267/src/main/java/rx/lang/groovy/RxGroovyExtensionModule.java#L180-L244 |
jmeetsma/Iglu-Util | src/main/java/org/ijsberg/iglu/util/io/BasicChannel.java | BasicChannel.createReceiver | public ReceiverQueue createReceiver(int limit) {
"""
Creates a receiver for this channel.
@param limit the maximum number of objects stored in the receiver queue
@return a receiver
"""
synchronized (receivers) {
ReceiverQueue q = null;
if (!closed && (maxNrofReceivers == 0 || receivers.size() < maxNrofReceivers)) {
q = new ReceiverQueue(/*this, */limit);
receivers.add(q);
}
return q;
}
} | java | public ReceiverQueue createReceiver(int limit) {
synchronized (receivers) {
ReceiverQueue q = null;
if (!closed && (maxNrofReceivers == 0 || receivers.size() < maxNrofReceivers)) {
q = new ReceiverQueue(/*this, */limit);
receivers.add(q);
}
return q;
}
} | [
"public",
"ReceiverQueue",
"createReceiver",
"(",
"int",
"limit",
")",
"{",
"synchronized",
"(",
"receivers",
")",
"{",
"ReceiverQueue",
"q",
"=",
"null",
";",
"if",
"(",
"!",
"closed",
"&&",
"(",
"maxNrofReceivers",
"==",
"0",
"||",
"receivers",
".",
"size",
"(",
")",
"<",
"maxNrofReceivers",
")",
")",
"{",
"q",
"=",
"new",
"ReceiverQueue",
"(",
"/*this, */",
"limit",
")",
";",
"receivers",
".",
"add",
"(",
"q",
")",
";",
"}",
"return",
"q",
";",
"}",
"}"
] | Creates a receiver for this channel.
@param limit the maximum number of objects stored in the receiver queue
@return a receiver | [
"Creates",
"a",
"receiver",
"for",
"this",
"channel",
"."
] | train | https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/io/BasicChannel.java#L148-L157 |
elki-project/elki | elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkcop/MkCoPTreeNode.java | MkCoPTreeNode.conservativeKnnDistanceApproximation | protected ApproximationLine conservativeKnnDistanceApproximation(int k_max) {
"""
Determines and returns the conservative approximation for the knn distances
of this node as the maximum of the conservative approximations of all
entries.
@param k_max the maximum k parameter
@return the conservative approximation for the knn distances
"""
// determine k_0, y_1, y_kmax
int k_0 = k_max;
double y_1 = Double.NEGATIVE_INFINITY;
double y_kmax = Double.NEGATIVE_INFINITY;
for(int i = 0; i < getNumEntries(); i++) {
MkCoPEntry entry = getEntry(i);
ApproximationLine approx = entry.getConservativeKnnDistanceApproximation();
k_0 = Math.min(approx.getK_0(), k_0);
}
for(int i = 0; i < getNumEntries(); i++) {
MkCoPEntry entry = getEntry(i);
ApproximationLine approx = entry.getConservativeKnnDistanceApproximation();
double entry_y_1 = approx.getValueAt(k_0);
double entry_y_kmax = approx.getValueAt(k_max);
if(!Double.isInfinite(entry_y_1)) {
y_1 = Math.max(entry_y_1, y_1);
}
if(!Double.isInfinite(entry_y_kmax)) {
y_kmax = Math.max(entry_y_kmax, y_kmax);
}
}
// determine m and t
double m = (y_kmax - y_1) / (FastMath.log(k_max) - FastMath.log(k_0));
double t = y_1 - m * FastMath.log(k_0);
return new ApproximationLine(k_0, m, t);
} | java | protected ApproximationLine conservativeKnnDistanceApproximation(int k_max) {
// determine k_0, y_1, y_kmax
int k_0 = k_max;
double y_1 = Double.NEGATIVE_INFINITY;
double y_kmax = Double.NEGATIVE_INFINITY;
for(int i = 0; i < getNumEntries(); i++) {
MkCoPEntry entry = getEntry(i);
ApproximationLine approx = entry.getConservativeKnnDistanceApproximation();
k_0 = Math.min(approx.getK_0(), k_0);
}
for(int i = 0; i < getNumEntries(); i++) {
MkCoPEntry entry = getEntry(i);
ApproximationLine approx = entry.getConservativeKnnDistanceApproximation();
double entry_y_1 = approx.getValueAt(k_0);
double entry_y_kmax = approx.getValueAt(k_max);
if(!Double.isInfinite(entry_y_1)) {
y_1 = Math.max(entry_y_1, y_1);
}
if(!Double.isInfinite(entry_y_kmax)) {
y_kmax = Math.max(entry_y_kmax, y_kmax);
}
}
// determine m and t
double m = (y_kmax - y_1) / (FastMath.log(k_max) - FastMath.log(k_0));
double t = y_1 - m * FastMath.log(k_0);
return new ApproximationLine(k_0, m, t);
} | [
"protected",
"ApproximationLine",
"conservativeKnnDistanceApproximation",
"(",
"int",
"k_max",
")",
"{",
"// determine k_0, y_1, y_kmax",
"int",
"k_0",
"=",
"k_max",
";",
"double",
"y_1",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"double",
"y_kmax",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getNumEntries",
"(",
")",
";",
"i",
"++",
")",
"{",
"MkCoPEntry",
"entry",
"=",
"getEntry",
"(",
"i",
")",
";",
"ApproximationLine",
"approx",
"=",
"entry",
".",
"getConservativeKnnDistanceApproximation",
"(",
")",
";",
"k_0",
"=",
"Math",
".",
"min",
"(",
"approx",
".",
"getK_0",
"(",
")",
",",
"k_0",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getNumEntries",
"(",
")",
";",
"i",
"++",
")",
"{",
"MkCoPEntry",
"entry",
"=",
"getEntry",
"(",
"i",
")",
";",
"ApproximationLine",
"approx",
"=",
"entry",
".",
"getConservativeKnnDistanceApproximation",
"(",
")",
";",
"double",
"entry_y_1",
"=",
"approx",
".",
"getValueAt",
"(",
"k_0",
")",
";",
"double",
"entry_y_kmax",
"=",
"approx",
".",
"getValueAt",
"(",
"k_max",
")",
";",
"if",
"(",
"!",
"Double",
".",
"isInfinite",
"(",
"entry_y_1",
")",
")",
"{",
"y_1",
"=",
"Math",
".",
"max",
"(",
"entry_y_1",
",",
"y_1",
")",
";",
"}",
"if",
"(",
"!",
"Double",
".",
"isInfinite",
"(",
"entry_y_kmax",
")",
")",
"{",
"y_kmax",
"=",
"Math",
".",
"max",
"(",
"entry_y_kmax",
",",
"y_kmax",
")",
";",
"}",
"}",
"// determine m and t",
"double",
"m",
"=",
"(",
"y_kmax",
"-",
"y_1",
")",
"/",
"(",
"FastMath",
".",
"log",
"(",
"k_max",
")",
"-",
"FastMath",
".",
"log",
"(",
"k_0",
")",
")",
";",
"double",
"t",
"=",
"y_1",
"-",
"m",
"*",
"FastMath",
".",
"log",
"(",
"k_0",
")",
";",
"return",
"new",
"ApproximationLine",
"(",
"k_0",
",",
"m",
",",
"t",
")",
";",
"}"
] | Determines and returns the conservative approximation for the knn distances
of this node as the maximum of the conservative approximations of all
entries.
@param k_max the maximum k parameter
@return the conservative approximation for the knn distances | [
"Determines",
"and",
"returns",
"the",
"conservative",
"approximation",
"for",
"the",
"knn",
"distances",
"of",
"this",
"node",
"as",
"the",
"maximum",
"of",
"the",
"conservative",
"approximations",
"of",
"all",
"entries",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkcop/MkCoPTreeNode.java#L70-L101 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.asDateTime | public static <T extends Comparable<?>> DateTimeExpression<T> asDateTime(Expression<T> expr) {
"""
Create a new DateTimeExpression
@param expr the date time Expression
@return new DateTimeExpression
"""
Expression<T> underlyingMixin = ExpressionUtils.extract(expr);
if (underlyingMixin instanceof PathImpl) {
return new DateTimePath<T>((PathImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof OperationImpl) {
return new DateTimeOperation<T>((OperationImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof TemplateExpressionImpl) {
return new DateTimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin);
} else {
return new DateTimeExpression<T>(underlyingMixin) {
private static final long serialVersionUID = 8007203530480765244L;
@Override
public <R, C> R accept(Visitor<R, C> v, C context) {
return this.mixin.accept(v, context);
}
};
}
} | java | public static <T extends Comparable<?>> DateTimeExpression<T> asDateTime(Expression<T> expr) {
Expression<T> underlyingMixin = ExpressionUtils.extract(expr);
if (underlyingMixin instanceof PathImpl) {
return new DateTimePath<T>((PathImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof OperationImpl) {
return new DateTimeOperation<T>((OperationImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof TemplateExpressionImpl) {
return new DateTimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin);
} else {
return new DateTimeExpression<T>(underlyingMixin) {
private static final long serialVersionUID = 8007203530480765244L;
@Override
public <R, C> R accept(Visitor<R, C> v, C context) {
return this.mixin.accept(v, context);
}
};
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"?",
">",
">",
"DateTimeExpression",
"<",
"T",
">",
"asDateTime",
"(",
"Expression",
"<",
"T",
">",
"expr",
")",
"{",
"Expression",
"<",
"T",
">",
"underlyingMixin",
"=",
"ExpressionUtils",
".",
"extract",
"(",
"expr",
")",
";",
"if",
"(",
"underlyingMixin",
"instanceof",
"PathImpl",
")",
"{",
"return",
"new",
"DateTimePath",
"<",
"T",
">",
"(",
"(",
"PathImpl",
"<",
"T",
">",
")",
"underlyingMixin",
")",
";",
"}",
"else",
"if",
"(",
"underlyingMixin",
"instanceof",
"OperationImpl",
")",
"{",
"return",
"new",
"DateTimeOperation",
"<",
"T",
">",
"(",
"(",
"OperationImpl",
"<",
"T",
">",
")",
"underlyingMixin",
")",
";",
"}",
"else",
"if",
"(",
"underlyingMixin",
"instanceof",
"TemplateExpressionImpl",
")",
"{",
"return",
"new",
"DateTimeTemplate",
"<",
"T",
">",
"(",
"(",
"TemplateExpressionImpl",
"<",
"T",
">",
")",
"underlyingMixin",
")",
";",
"}",
"else",
"{",
"return",
"new",
"DateTimeExpression",
"<",
"T",
">",
"(",
"underlyingMixin",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"8007203530480765244L",
";",
"@",
"Override",
"public",
"<",
"R",
",",
"C",
">",
"R",
"accept",
"(",
"Visitor",
"<",
"R",
",",
"C",
">",
"v",
",",
"C",
"context",
")",
"{",
"return",
"this",
".",
"mixin",
".",
"accept",
"(",
"v",
",",
"context",
")",
";",
"}",
"}",
";",
"}",
"}"
] | Create a new DateTimeExpression
@param expr the date time Expression
@return new DateTimeExpression | [
"Create",
"a",
"new",
"DateTimeExpression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L1977-L1998 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java | SpecializedOps_DDRM.addIdentity | public static void addIdentity(DMatrix1Row A , DMatrix1Row B , double alpha ) {
"""
<p>
Performs the following operation:<br>
<br>
B = A + αI
<p>
@param A A square matrix. Not modified.
@param B A square matrix that the results are saved to. Modified.
@param alpha Scaling factor for the identity matrix.
"""
if( A.numCols != A.numRows )
throw new IllegalArgumentException("A must be square");
if( B.numCols != A.numCols || B.numRows != A.numRows )
throw new IllegalArgumentException("B must be the same shape as A");
int n = A.numCols;
int index = 0;
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ , index++) {
if( i == j ) {
B.set( index , A.get(index) + alpha);
} else {
B.set( index , A.get(index) );
}
}
}
} | java | public static void addIdentity(DMatrix1Row A , DMatrix1Row B , double alpha )
{
if( A.numCols != A.numRows )
throw new IllegalArgumentException("A must be square");
if( B.numCols != A.numCols || B.numRows != A.numRows )
throw new IllegalArgumentException("B must be the same shape as A");
int n = A.numCols;
int index = 0;
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ , index++) {
if( i == j ) {
B.set( index , A.get(index) + alpha);
} else {
B.set( index , A.get(index) );
}
}
}
} | [
"public",
"static",
"void",
"addIdentity",
"(",
"DMatrix1Row",
"A",
",",
"DMatrix1Row",
"B",
",",
"double",
"alpha",
")",
"{",
"if",
"(",
"A",
".",
"numCols",
"!=",
"A",
".",
"numRows",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"A must be square\"",
")",
";",
"if",
"(",
"B",
".",
"numCols",
"!=",
"A",
".",
"numCols",
"||",
"B",
".",
"numRows",
"!=",
"A",
".",
"numRows",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"B must be the same shape as A\"",
")",
";",
"int",
"n",
"=",
"A",
".",
"numCols",
";",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"n",
";",
"j",
"++",
",",
"index",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"j",
")",
"{",
"B",
".",
"set",
"(",
"index",
",",
"A",
".",
"get",
"(",
"index",
")",
"+",
"alpha",
")",
";",
"}",
"else",
"{",
"B",
".",
"set",
"(",
"index",
",",
"A",
".",
"get",
"(",
"index",
")",
")",
";",
"}",
"}",
"}",
"}"
] | <p>
Performs the following operation:<br>
<br>
B = A + αI
<p>
@param A A square matrix. Not modified.
@param B A square matrix that the results are saved to. Modified.
@param alpha Scaling factor for the identity matrix. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"B",
"=",
"A",
"+",
"&alpha",
";",
"I",
"<p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java#L284-L303 |
sarl/sarl | contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java | PyGenerator.generatePythonField | protected void generatePythonField(SarlField field, PyAppendable it, IExtraLanguageGeneratorContext context) {
"""
Create a field declaration.
@param field the field to generate.
@param it the output
@param context the generation context.
"""
generateBlockComment(getTypeBuilder().getDocumentation(field), it);
if (!field.isStatic()) {
it.append("self."); //$NON-NLS-1$
}
final String fieldName = it.declareUniqueNameVariable(field, field.getName());
it.append(fieldName);
it.append(" = "); //$NON-NLS-1$
if (field.getInitialValue() != null) {
generate(field.getInitialValue(), null, it, context);
} else {
it.append(PyExpressionGenerator.toDefaultValue(field.getType()));
}
it.newLine();
} | java | protected void generatePythonField(SarlField field, PyAppendable it, IExtraLanguageGeneratorContext context) {
generateBlockComment(getTypeBuilder().getDocumentation(field), it);
if (!field.isStatic()) {
it.append("self."); //$NON-NLS-1$
}
final String fieldName = it.declareUniqueNameVariable(field, field.getName());
it.append(fieldName);
it.append(" = "); //$NON-NLS-1$
if (field.getInitialValue() != null) {
generate(field.getInitialValue(), null, it, context);
} else {
it.append(PyExpressionGenerator.toDefaultValue(field.getType()));
}
it.newLine();
} | [
"protected",
"void",
"generatePythonField",
"(",
"SarlField",
"field",
",",
"PyAppendable",
"it",
",",
"IExtraLanguageGeneratorContext",
"context",
")",
"{",
"generateBlockComment",
"(",
"getTypeBuilder",
"(",
")",
".",
"getDocumentation",
"(",
"field",
")",
",",
"it",
")",
";",
"if",
"(",
"!",
"field",
".",
"isStatic",
"(",
")",
")",
"{",
"it",
".",
"append",
"(",
"\"self.\"",
")",
";",
"//$NON-NLS-1$",
"}",
"final",
"String",
"fieldName",
"=",
"it",
".",
"declareUniqueNameVariable",
"(",
"field",
",",
"field",
".",
"getName",
"(",
")",
")",
";",
"it",
".",
"append",
"(",
"fieldName",
")",
";",
"it",
".",
"append",
"(",
"\" = \"",
")",
";",
"//$NON-NLS-1$",
"if",
"(",
"field",
".",
"getInitialValue",
"(",
")",
"!=",
"null",
")",
"{",
"generate",
"(",
"field",
".",
"getInitialValue",
"(",
")",
",",
"null",
",",
"it",
",",
"context",
")",
";",
"}",
"else",
"{",
"it",
".",
"append",
"(",
"PyExpressionGenerator",
".",
"toDefaultValue",
"(",
"field",
".",
"getType",
"(",
")",
")",
")",
";",
"}",
"it",
".",
"newLine",
"(",
")",
";",
"}"
] | Create a field declaration.
@param field the field to generate.
@param it the output
@param context the generation context. | [
"Create",
"a",
"field",
"declaration",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java#L478-L492 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java | ChunkCollision.replaceBlocks | public void replaceBlocks(World world, MBlockState state) {
"""
Replaces to air all the blocks colliding with the {@link AxisAlignedBB} of the {@link MBlockState}.
@param world the world
@param state the state
"""
AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true);
for (AxisAlignedBB aabb : aabbs)
{
if (aabb == null)
continue;
for (BlockPos pos : BlockPosUtils.getAllInBox(aabb))
{
if (world.getBlockState(pos).getBlock().isReplaceable(world, pos))
world.setBlockToAir(pos);
}
}
} | java | public void replaceBlocks(World world, MBlockState state)
{
AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true);
for (AxisAlignedBB aabb : aabbs)
{
if (aabb == null)
continue;
for (BlockPos pos : BlockPosUtils.getAllInBox(aabb))
{
if (world.getBlockState(pos).getBlock().isReplaceable(world, pos))
world.setBlockToAir(pos);
}
}
} | [
"public",
"void",
"replaceBlocks",
"(",
"World",
"world",
",",
"MBlockState",
"state",
")",
"{",
"AxisAlignedBB",
"[",
"]",
"aabbs",
"=",
"AABBUtils",
".",
"getCollisionBoundingBoxes",
"(",
"world",
",",
"state",
",",
"true",
")",
";",
"for",
"(",
"AxisAlignedBB",
"aabb",
":",
"aabbs",
")",
"{",
"if",
"(",
"aabb",
"==",
"null",
")",
"continue",
";",
"for",
"(",
"BlockPos",
"pos",
":",
"BlockPosUtils",
".",
"getAllInBox",
"(",
"aabb",
")",
")",
"{",
"if",
"(",
"world",
".",
"getBlockState",
"(",
"pos",
")",
".",
"getBlock",
"(",
")",
".",
"isReplaceable",
"(",
"world",
",",
"pos",
")",
")",
"world",
".",
"setBlockToAir",
"(",
"pos",
")",
";",
"}",
"}",
"}"
] | Replaces to air all the blocks colliding with the {@link AxisAlignedBB} of the {@link MBlockState}.
@param world the world
@param state the state | [
"Replaces",
"to",
"air",
"all",
"the",
"blocks",
"colliding",
"with",
"the",
"{",
"@link",
"AxisAlignedBB",
"}",
"of",
"the",
"{",
"@link",
"MBlockState",
"}",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java#L266-L280 |
chhh/MSFTBX | MSFileToolbox/src/main/java/umich/ms/util/jaxb/JaxbUtils.java | JaxbUtils.createXmlStreamReader | public static XMLStreamReader createXmlStreamReader(InputStream is, boolean namespaceAware)
throws JAXBException {
"""
Creates an XMLStreamReader based on an input stream.
@param is the input stream from which the data to be parsed will be taken
@param namespaceAware if {@code false} the XMLStreamReader will remove all namespaces from all
XML elements
@return platform-specific XMLStreamReader implementation
@throws JAXBException if the XMLStreamReader could not be created
"""
XMLInputFactory xif = getXmlInputFactory(namespaceAware);
XMLStreamReader xsr = null;
try {
xsr = xif.createXMLStreamReader(is);
} catch (XMLStreamException e) {
throw new JAXBException(e);
}
return xsr;
} | java | public static XMLStreamReader createXmlStreamReader(InputStream is, boolean namespaceAware)
throws JAXBException {
XMLInputFactory xif = getXmlInputFactory(namespaceAware);
XMLStreamReader xsr = null;
try {
xsr = xif.createXMLStreamReader(is);
} catch (XMLStreamException e) {
throw new JAXBException(e);
}
return xsr;
} | [
"public",
"static",
"XMLStreamReader",
"createXmlStreamReader",
"(",
"InputStream",
"is",
",",
"boolean",
"namespaceAware",
")",
"throws",
"JAXBException",
"{",
"XMLInputFactory",
"xif",
"=",
"getXmlInputFactory",
"(",
"namespaceAware",
")",
";",
"XMLStreamReader",
"xsr",
"=",
"null",
";",
"try",
"{",
"xsr",
"=",
"xif",
".",
"createXMLStreamReader",
"(",
"is",
")",
";",
"}",
"catch",
"(",
"XMLStreamException",
"e",
")",
"{",
"throw",
"new",
"JAXBException",
"(",
"e",
")",
";",
"}",
"return",
"xsr",
";",
"}"
] | Creates an XMLStreamReader based on an input stream.
@param is the input stream from which the data to be parsed will be taken
@param namespaceAware if {@code false} the XMLStreamReader will remove all namespaces from all
XML elements
@return platform-specific XMLStreamReader implementation
@throws JAXBException if the XMLStreamReader could not be created | [
"Creates",
"an",
"XMLStreamReader",
"based",
"on",
"an",
"input",
"stream",
"."
] | train | https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/util/jaxb/JaxbUtils.java#L134-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/helper/AuthenticateUserHelper.java | AuthenticateUserHelper.createPartialSubject | protected Subject createPartialSubject(String username, AuthenticationService authenticationService, String customCacheKey) {
"""
/*
Create the partial subject that can be used to authenticate the user with.
"""
Subject partialSubject = null;
partialSubject = new Subject();
Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
hashtable.put(AttributeNameConstants.WSCREDENTIAL_USERID, username);
// only set the property in the hashtable if the public property is not already set;
// this property allows authentication when only the username is supplied
if (!authenticationService.isAllowHashTableLoginWithIdOnly()) {
hashtable.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE);
}
if (customCacheKey != null) {
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, customCacheKey);
}
partialSubject.getPublicCredentials().add(hashtable);
return partialSubject;
} | java | protected Subject createPartialSubject(String username, AuthenticationService authenticationService, String customCacheKey) {
Subject partialSubject = null;
partialSubject = new Subject();
Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
hashtable.put(AttributeNameConstants.WSCREDENTIAL_USERID, username);
// only set the property in the hashtable if the public property is not already set;
// this property allows authentication when only the username is supplied
if (!authenticationService.isAllowHashTableLoginWithIdOnly()) {
hashtable.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE);
}
if (customCacheKey != null) {
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, customCacheKey);
}
partialSubject.getPublicCredentials().add(hashtable);
return partialSubject;
} | [
"protected",
"Subject",
"createPartialSubject",
"(",
"String",
"username",
",",
"AuthenticationService",
"authenticationService",
",",
"String",
"customCacheKey",
")",
"{",
"Subject",
"partialSubject",
"=",
"null",
";",
"partialSubject",
"=",
"new",
"Subject",
"(",
")",
";",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"hashtable",
"=",
"new",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"hashtable",
".",
"put",
"(",
"AttributeNameConstants",
".",
"WSCREDENTIAL_USERID",
",",
"username",
")",
";",
"// only set the property in the hashtable if the public property is not already set;",
"// this property allows authentication when only the username is supplied",
"if",
"(",
"!",
"authenticationService",
".",
"isAllowHashTableLoginWithIdOnly",
"(",
")",
")",
"{",
"hashtable",
".",
"put",
"(",
"AuthenticationConstants",
".",
"INTERNAL_ASSERTION_KEY",
",",
"Boolean",
".",
"TRUE",
")",
";",
"}",
"if",
"(",
"customCacheKey",
"!=",
"null",
")",
"{",
"hashtable",
".",
"put",
"(",
"AttributeNameConstants",
".",
"WSCREDENTIAL_CACHE_KEY",
",",
"customCacheKey",
")",
";",
"}",
"partialSubject",
".",
"getPublicCredentials",
"(",
")",
".",
"add",
"(",
"hashtable",
")",
";",
"return",
"partialSubject",
";",
"}"
] | /*
Create the partial subject that can be used to authenticate the user with. | [
"/",
"*",
"Create",
"the",
"partial",
"subject",
"that",
"can",
"be",
"used",
"to",
"authenticate",
"the",
"user",
"with",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/helper/AuthenticateUserHelper.java#L67-L85 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark-parameterserver/src/main/java/org/deeplearning4j/spark/parameterserver/networking/v2/WiredEncodingHandler.java | WiredEncodingHandler.sendMessage | @Override
protected void sendMessage(@NonNull INDArray message, int iterationNumber, int epochNumber) {
"""
This method sends given message to all registered recipients
@param message
"""
// here we'll send our stuff to other executores over the wire
// and let's pray for udp broadcast availability
// Send this message away
// FIXME: do something with unsafe duplication, which is bad and used ONLY for local spark
try (MemoryWorkspace wsO = Nd4j.getMemoryManager().scopeOutOfWorkspaces()) {
long updateId = updatesCounter.getAndIncrement();
val m = message.unsafeDuplication();
ModelParameterServer.getInstance().sendUpdate(m, iterationNumber, epochNumber);
}
// heere we update local queue
super.sendMessage(message, iterationNumber, epochNumber);
} | java | @Override
protected void sendMessage(@NonNull INDArray message, int iterationNumber, int epochNumber) {
// here we'll send our stuff to other executores over the wire
// and let's pray for udp broadcast availability
// Send this message away
// FIXME: do something with unsafe duplication, which is bad and used ONLY for local spark
try (MemoryWorkspace wsO = Nd4j.getMemoryManager().scopeOutOfWorkspaces()) {
long updateId = updatesCounter.getAndIncrement();
val m = message.unsafeDuplication();
ModelParameterServer.getInstance().sendUpdate(m, iterationNumber, epochNumber);
}
// heere we update local queue
super.sendMessage(message, iterationNumber, epochNumber);
} | [
"@",
"Override",
"protected",
"void",
"sendMessage",
"(",
"@",
"NonNull",
"INDArray",
"message",
",",
"int",
"iterationNumber",
",",
"int",
"epochNumber",
")",
"{",
"// here we'll send our stuff to other executores over the wire",
"// and let's pray for udp broadcast availability",
"// Send this message away",
"// FIXME: do something with unsafe duplication, which is bad and used ONLY for local spark",
"try",
"(",
"MemoryWorkspace",
"wsO",
"=",
"Nd4j",
".",
"getMemoryManager",
"(",
")",
".",
"scopeOutOfWorkspaces",
"(",
")",
")",
"{",
"long",
"updateId",
"=",
"updatesCounter",
".",
"getAndIncrement",
"(",
")",
";",
"val",
"m",
"=",
"message",
".",
"unsafeDuplication",
"(",
")",
";",
"ModelParameterServer",
".",
"getInstance",
"(",
")",
".",
"sendUpdate",
"(",
"m",
",",
"iterationNumber",
",",
"epochNumber",
")",
";",
"}",
"// heere we update local queue",
"super",
".",
"sendMessage",
"(",
"message",
",",
"iterationNumber",
",",
"epochNumber",
")",
";",
"}"
] | This method sends given message to all registered recipients
@param message | [
"This",
"method",
"sends",
"given",
"message",
"to",
"all",
"registered",
"recipients"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark-parameterserver/src/main/java/org/deeplearning4j/spark/parameterserver/networking/v2/WiredEncodingHandler.java#L56-L73 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_virtualMac_macAddress_GET | public OvhVirtualMac serviceName_virtualMac_macAddress_GET(String serviceName, String macAddress) throws IOException {
"""
Get this object properties
REST: GET /dedicated/server/{serviceName}/virtualMac/{macAddress}
@param serviceName [required] The internal name of your dedicated server
@param macAddress [required] Virtual MAC address in 00:00:00:00:00:00 format
"""
String qPath = "/dedicated/server/{serviceName}/virtualMac/{macAddress}";
StringBuilder sb = path(qPath, serviceName, macAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhVirtualMac.class);
} | java | public OvhVirtualMac serviceName_virtualMac_macAddress_GET(String serviceName, String macAddress) throws IOException {
String qPath = "/dedicated/server/{serviceName}/virtualMac/{macAddress}";
StringBuilder sb = path(qPath, serviceName, macAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhVirtualMac.class);
} | [
"public",
"OvhVirtualMac",
"serviceName_virtualMac_macAddress_GET",
"(",
"String",
"serviceName",
",",
"String",
"macAddress",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/virtualMac/{macAddress}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"macAddress",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhVirtualMac",
".",
"class",
")",
";",
"}"
] | Get this object properties
REST: GET /dedicated/server/{serviceName}/virtualMac/{macAddress}
@param serviceName [required] The internal name of your dedicated server
@param macAddress [required] Virtual MAC address in 00:00:00:00:00:00 format | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L559-L564 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/message/ZipMessage.java | ZipMessage.addEntry | public ZipMessage addEntry(String fileName, byte[] content) {
"""
Adds new zip archive entry with given content.
@param fileName
@param content
@return
"""
Entry entry = new Entry(fileName);
entry.setContent(content);
addEntry(entry);
return this;
} | java | public ZipMessage addEntry(String fileName, byte[] content) {
Entry entry = new Entry(fileName);
entry.setContent(content);
addEntry(entry);
return this;
} | [
"public",
"ZipMessage",
"addEntry",
"(",
"String",
"fileName",
",",
"byte",
"[",
"]",
"content",
")",
"{",
"Entry",
"entry",
"=",
"new",
"Entry",
"(",
"fileName",
")",
";",
"entry",
".",
"setContent",
"(",
"content",
")",
";",
"addEntry",
"(",
"entry",
")",
";",
"return",
"this",
";",
"}"
] | Adds new zip archive entry with given content.
@param fileName
@param content
@return | [
"Adds",
"new",
"zip",
"archive",
"entry",
"with",
"given",
"content",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/message/ZipMessage.java#L99-L104 |
glookast/commons-timecode | src/main/java/com/glookast/commons/timecode/AbstractTimecode.java | AbstractTimecode.calculateInPoint | public static Timecode calculateInPoint(Timecode outPoint, TimecodeDuration duration) {
"""
Calculates inPoint of a given outPoint and duration.
In case duration does not have the same Timecode base and/or dropFrame flag
it will convert it to the same Timecode base and dropFrame flag of the outPoint
@param outPoint
@param duration
@return inPoint
"""
if (!outPoint.isCompatible(duration)) {
MutableTimecodeDuration mutableTimecodeDuration = new MutableTimecodeDuration(duration);
mutableTimecodeDuration.setTimecodeBase(outPoint.getTimecodeBase());
mutableTimecodeDuration.setDropFrame(outPoint.isDropFrame());
duration = new TimecodeDuration(mutableTimecodeDuration);
}
MutableTimecode inPoint = new MutableTimecode(outPoint);
inPoint.addFrames(-duration.getFrameNumber());
return new Timecode(inPoint);
} | java | public static Timecode calculateInPoint(Timecode outPoint, TimecodeDuration duration)
{
if (!outPoint.isCompatible(duration)) {
MutableTimecodeDuration mutableTimecodeDuration = new MutableTimecodeDuration(duration);
mutableTimecodeDuration.setTimecodeBase(outPoint.getTimecodeBase());
mutableTimecodeDuration.setDropFrame(outPoint.isDropFrame());
duration = new TimecodeDuration(mutableTimecodeDuration);
}
MutableTimecode inPoint = new MutableTimecode(outPoint);
inPoint.addFrames(-duration.getFrameNumber());
return new Timecode(inPoint);
} | [
"public",
"static",
"Timecode",
"calculateInPoint",
"(",
"Timecode",
"outPoint",
",",
"TimecodeDuration",
"duration",
")",
"{",
"if",
"(",
"!",
"outPoint",
".",
"isCompatible",
"(",
"duration",
")",
")",
"{",
"MutableTimecodeDuration",
"mutableTimecodeDuration",
"=",
"new",
"MutableTimecodeDuration",
"(",
"duration",
")",
";",
"mutableTimecodeDuration",
".",
"setTimecodeBase",
"(",
"outPoint",
".",
"getTimecodeBase",
"(",
")",
")",
";",
"mutableTimecodeDuration",
".",
"setDropFrame",
"(",
"outPoint",
".",
"isDropFrame",
"(",
")",
")",
";",
"duration",
"=",
"new",
"TimecodeDuration",
"(",
"mutableTimecodeDuration",
")",
";",
"}",
"MutableTimecode",
"inPoint",
"=",
"new",
"MutableTimecode",
"(",
"outPoint",
")",
";",
"inPoint",
".",
"addFrames",
"(",
"-",
"duration",
".",
"getFrameNumber",
"(",
")",
")",
";",
"return",
"new",
"Timecode",
"(",
"inPoint",
")",
";",
"}"
] | Calculates inPoint of a given outPoint and duration.
In case duration does not have the same Timecode base and/or dropFrame flag
it will convert it to the same Timecode base and dropFrame flag of the outPoint
@param outPoint
@param duration
@return inPoint | [
"Calculates",
"inPoint",
"of",
"a",
"given",
"outPoint",
"and",
"duration",
".",
"In",
"case",
"duration",
"does",
"not",
"have",
"the",
"same",
"Timecode",
"base",
"and",
"/",
"or",
"dropFrame",
"flag",
"it",
"will",
"convert",
"it",
"to",
"the",
"same",
"Timecode",
"base",
"and",
"dropFrame",
"flag",
"of",
"the",
"outPoint"
] | train | https://github.com/glookast/commons-timecode/blob/ec2f682a51d1cc435d0b42d80de48ff15adb4ee8/src/main/java/com/glookast/commons/timecode/AbstractTimecode.java#L612-L624 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newConfigurationException | public static ConfigurationException newConfigurationException(Throwable cause, String message, Object... args) {
"""
Constructs and initializes a new {@link ConfigurationException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link ConfigurationException} was thrown.
@param message {@link String} describing the {@link ConfigurationException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ConfigurationException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.context.configure.ConfigurationException
"""
return new ConfigurationException(format(message, args), cause);
} | java | public static ConfigurationException newConfigurationException(Throwable cause, String message, Object... args) {
return new ConfigurationException(format(message, args), cause);
} | [
"public",
"static",
"ConfigurationException",
"newConfigurationException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"ConfigurationException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
"cause",
")",
";",
"}"
] | Constructs and initializes a new {@link ConfigurationException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link ConfigurationException} was thrown.
@param message {@link String} describing the {@link ConfigurationException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ConfigurationException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.context.configure.ConfigurationException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"ConfigurationException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L137-L139 |
gwtplus/google-gin | src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java | ReflectUtil.getTypePackageNames | private static void getTypePackageNames(Type type, Map<String, Class<?>> packageNames) {
"""
Visits all the components of a type, collecting a map taking the name of
each package in which package-private types are defined to one of the
classes contained in {@code type} that belongs to that package. If any
private types are encountered, an {@link IllegalArgumentException} is
thrown.
This is required to deal with situations like Generic<Private> where
Generic is publically defined in package A and Private is private to
package B; we need to place code that uses this type in package B, even
though the top-level class is from A.
"""
if (type instanceof Class<?>) {
getClassPackageNames((Class<?>) type, packageNames);
} else if (type instanceof GenericArrayType) {
getTypePackageNames(((GenericArrayType) type).getGenericComponentType(), packageNames);
} else if (type instanceof ParameterizedType) {
getParameterizedTypePackageNames((ParameterizedType) type, packageNames);
} else if (type instanceof TypeVariable) {
getTypeVariablePackageNames((TypeVariable) type, packageNames);
} else if (type instanceof WildcardType) {
getWildcardTypePackageNames((WildcardType) type, packageNames);
}
} | java | private static void getTypePackageNames(Type type, Map<String, Class<?>> packageNames) {
if (type instanceof Class<?>) {
getClassPackageNames((Class<?>) type, packageNames);
} else if (type instanceof GenericArrayType) {
getTypePackageNames(((GenericArrayType) type).getGenericComponentType(), packageNames);
} else if (type instanceof ParameterizedType) {
getParameterizedTypePackageNames((ParameterizedType) type, packageNames);
} else if (type instanceof TypeVariable) {
getTypeVariablePackageNames((TypeVariable) type, packageNames);
} else if (type instanceof WildcardType) {
getWildcardTypePackageNames((WildcardType) type, packageNames);
}
} | [
"private",
"static",
"void",
"getTypePackageNames",
"(",
"Type",
"type",
",",
"Map",
"<",
"String",
",",
"Class",
"<",
"?",
">",
">",
"packageNames",
")",
"{",
"if",
"(",
"type",
"instanceof",
"Class",
"<",
"?",
">",
")",
"{",
"getClassPackageNames",
"(",
"(",
"Class",
"<",
"?",
">",
")",
"type",
",",
"packageNames",
")",
";",
"}",
"else",
"if",
"(",
"type",
"instanceof",
"GenericArrayType",
")",
"{",
"getTypePackageNames",
"(",
"(",
"(",
"GenericArrayType",
")",
"type",
")",
".",
"getGenericComponentType",
"(",
")",
",",
"packageNames",
")",
";",
"}",
"else",
"if",
"(",
"type",
"instanceof",
"ParameterizedType",
")",
"{",
"getParameterizedTypePackageNames",
"(",
"(",
"ParameterizedType",
")",
"type",
",",
"packageNames",
")",
";",
"}",
"else",
"if",
"(",
"type",
"instanceof",
"TypeVariable",
")",
"{",
"getTypeVariablePackageNames",
"(",
"(",
"TypeVariable",
")",
"type",
",",
"packageNames",
")",
";",
"}",
"else",
"if",
"(",
"type",
"instanceof",
"WildcardType",
")",
"{",
"getWildcardTypePackageNames",
"(",
"(",
"WildcardType",
")",
"type",
",",
"packageNames",
")",
";",
"}",
"}"
] | Visits all the components of a type, collecting a map taking the name of
each package in which package-private types are defined to one of the
classes contained in {@code type} that belongs to that package. If any
private types are encountered, an {@link IllegalArgumentException} is
thrown.
This is required to deal with situations like Generic<Private> where
Generic is publically defined in package A and Private is private to
package B; we need to place code that uses this type in package B, even
though the top-level class is from A. | [
"Visits",
"all",
"the",
"components",
"of",
"a",
"type",
"collecting",
"a",
"map",
"taking",
"the",
"name",
"of",
"each",
"package",
"in",
"which",
"package",
"-",
"private",
"types",
"are",
"defined",
"to",
"one",
"of",
"the",
"classes",
"contained",
"in",
"{",
"@code",
"type",
"}",
"that",
"belongs",
"to",
"that",
"package",
".",
"If",
"any",
"private",
"types",
"are",
"encountered",
"an",
"{",
"@link",
"IllegalArgumentException",
"}",
"is",
"thrown",
"."
] | train | https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L216-L228 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/window/EventTimeTrigger.java | EventTimeTrigger.onElement | @Override
public TriggerResult onElement(Object element, long timestamp, TimeWindow window, TriggerContext ctx) {
"""
If a watermark arrives, we need to check all pending windows.
If any of the pending window suffices, we should fire immediately by registering a timer without delay.
Otherwise we register a timer whose time is the window end plus max lag time
"""
ctx.registerEventTimeTimer(window.getEnd() + ctx.getMaxLagMs(), window);
return TriggerResult.CONTINUE;
} | java | @Override
public TriggerResult onElement(Object element, long timestamp, TimeWindow window, TriggerContext ctx) {
ctx.registerEventTimeTimer(window.getEnd() + ctx.getMaxLagMs(), window);
return TriggerResult.CONTINUE;
} | [
"@",
"Override",
"public",
"TriggerResult",
"onElement",
"(",
"Object",
"element",
",",
"long",
"timestamp",
",",
"TimeWindow",
"window",
",",
"TriggerContext",
"ctx",
")",
"{",
"ctx",
".",
"registerEventTimeTimer",
"(",
"window",
".",
"getEnd",
"(",
")",
"+",
"ctx",
".",
"getMaxLagMs",
"(",
")",
",",
"window",
")",
";",
"return",
"TriggerResult",
".",
"CONTINUE",
";",
"}"
] | If a watermark arrives, we need to check all pending windows.
If any of the pending window suffices, we should fire immediately by registering a timer without delay.
Otherwise we register a timer whose time is the window end plus max lag time | [
"If",
"a",
"watermark",
"arrives",
"we",
"need",
"to",
"check",
"all",
"pending",
"windows",
".",
"If",
"any",
"of",
"the",
"pending",
"window",
"suffices",
"we",
"should",
"fire",
"immediately",
"by",
"registering",
"a",
"timer",
"without",
"delay",
".",
"Otherwise",
"we",
"register",
"a",
"timer",
"whose",
"time",
"is",
"the",
"window",
"end",
"plus",
"max",
"lag",
"time"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/window/EventTimeTrigger.java#L32-L36 |
square/dagger | compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java | GraphAnalysisLoader.nextDollar | private static int nextDollar(String className, CharSequence current, int searchStart) {
"""
Finds the next {@code '$'} in a class name which can be changed to a {@code '.'} when computing
a canonical class name.
"""
while (true) {
int index = className.indexOf('$', searchStart);
if (index == -1) {
return -1;
}
// We'll never have two dots nor will a type name end or begin with dot. So no need to
// consider dollars at the beginning, end, or adjacent to dots.
if (index == 0 || index == className.length() - 1
|| current.charAt(index - 1) == '.' || current.charAt(index + 1) == '.') {
searchStart = index + 1;
continue;
}
return index;
}
} | java | private static int nextDollar(String className, CharSequence current, int searchStart) {
while (true) {
int index = className.indexOf('$', searchStart);
if (index == -1) {
return -1;
}
// We'll never have two dots nor will a type name end or begin with dot. So no need to
// consider dollars at the beginning, end, or adjacent to dots.
if (index == 0 || index == className.length() - 1
|| current.charAt(index - 1) == '.' || current.charAt(index + 1) == '.') {
searchStart = index + 1;
continue;
}
return index;
}
} | [
"private",
"static",
"int",
"nextDollar",
"(",
"String",
"className",
",",
"CharSequence",
"current",
",",
"int",
"searchStart",
")",
"{",
"while",
"(",
"true",
")",
"{",
"int",
"index",
"=",
"className",
".",
"indexOf",
"(",
"'",
"'",
",",
"searchStart",
")",
";",
"if",
"(",
"index",
"==",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"// We'll never have two dots nor will a type name end or begin with dot. So no need to",
"// consider dollars at the beginning, end, or adjacent to dots.",
"if",
"(",
"index",
"==",
"0",
"||",
"index",
"==",
"className",
".",
"length",
"(",
")",
"-",
"1",
"||",
"current",
".",
"charAt",
"(",
"index",
"-",
"1",
")",
"==",
"'",
"'",
"||",
"current",
".",
"charAt",
"(",
"index",
"+",
"1",
")",
"==",
"'",
"'",
")",
"{",
"searchStart",
"=",
"index",
"+",
"1",
";",
"continue",
";",
"}",
"return",
"index",
";",
"}",
"}"
] | Finds the next {@code '$'} in a class name which can be changed to a {@code '.'} when computing
a canonical class name. | [
"Finds",
"the",
"next",
"{"
] | train | https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java#L108-L123 |
NessComputing/components-ness-httpclient | client/src/main/java/com/nesscomputing/httpclient/HttpClient.java | HttpClient.perform | public <T> HttpClientRequest.Builder<T> perform(final String methodName, final URI uri, final HttpClientResponseHandler<T> httpHandler) {
"""
Start building a request with a user-supplied HTTP method (of the standard HTTP verbs)
"""
final HttpClientMethod method;
try {
method = HttpClientMethod.valueOf(methodName.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Unknown HTTP method type " + methodName, e);
}
return new HttpClientRequest.Builder<T>(httpClientFactory, method, uri, httpHandler);
} | java | public <T> HttpClientRequest.Builder<T> perform(final String methodName, final URI uri, final HttpClientResponseHandler<T> httpHandler) {
final HttpClientMethod method;
try {
method = HttpClientMethod.valueOf(methodName.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Unknown HTTP method type " + methodName, e);
}
return new HttpClientRequest.Builder<T>(httpClientFactory, method, uri, httpHandler);
} | [
"public",
"<",
"T",
">",
"HttpClientRequest",
".",
"Builder",
"<",
"T",
">",
"perform",
"(",
"final",
"String",
"methodName",
",",
"final",
"URI",
"uri",
",",
"final",
"HttpClientResponseHandler",
"<",
"T",
">",
"httpHandler",
")",
"{",
"final",
"HttpClientMethod",
"method",
";",
"try",
"{",
"method",
"=",
"HttpClientMethod",
".",
"valueOf",
"(",
"methodName",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unknown HTTP method type \"",
"+",
"methodName",
",",
"e",
")",
";",
"}",
"return",
"new",
"HttpClientRequest",
".",
"Builder",
"<",
"T",
">",
"(",
"httpClientFactory",
",",
"method",
",",
"uri",
",",
"httpHandler",
")",
";",
"}"
] | Start building a request with a user-supplied HTTP method (of the standard HTTP verbs) | [
"Start",
"building",
"a",
"request",
"with",
"a",
"user",
"-",
"supplied",
"HTTP",
"method",
"(",
"of",
"the",
"standard",
"HTTP",
"verbs",
")"
] | train | https://github.com/NessComputing/components-ness-httpclient/blob/8e97e8576e470449672c81fa7890c60f9986966d/client/src/main/java/com/nesscomputing/httpclient/HttpClient.java#L271-L280 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/liquibase/changes/FixInvitations.java | FixInvitations.deleteInvitation | private void deleteInvitation(JdbcConnection connection, Long id) throws CustomChangeException {
"""
Deletes an invitation
@param connection connection
@param id invitation id
@throws CustomChangeException on error
"""
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM PANELINVITATION WHERE id = ?")) {
statement.setLong(1, id);
statement.execute();
} catch (Exception e) {
throw new CustomChangeException(e);
}
} | java | private void deleteInvitation(JdbcConnection connection, Long id) throws CustomChangeException {
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM PANELINVITATION WHERE id = ?")) {
statement.setLong(1, id);
statement.execute();
} catch (Exception e) {
throw new CustomChangeException(e);
}
} | [
"private",
"void",
"deleteInvitation",
"(",
"JdbcConnection",
"connection",
",",
"Long",
"id",
")",
"throws",
"CustomChangeException",
"{",
"try",
"(",
"PreparedStatement",
"statement",
"=",
"connection",
".",
"prepareStatement",
"(",
"\"DELETE FROM PANELINVITATION WHERE id = ?\"",
")",
")",
"{",
"statement",
".",
"setLong",
"(",
"1",
",",
"id",
")",
";",
"statement",
".",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"CustomChangeException",
"(",
"e",
")",
";",
"}",
"}"
] | Deletes an invitation
@param connection connection
@param id invitation id
@throws CustomChangeException on error | [
"Deletes",
"an",
"invitation"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/liquibase/changes/FixInvitations.java#L68-L75 |
scalecube/socketio | src/main/java/io/scalecube/socketio/pipeline/ResourceHandler.java | ResourceHandler.setContentTypeHeader | private void setContentTypeHeader(HttpResponse response, URLConnection resUrlConnection) {
"""
Sets the content type header for the HTTP Response
@param response
HTTP response
"""
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String resName = resUrlConnection.getURL().getFile();
response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(resName));
} | java | private void setContentTypeHeader(HttpResponse response, URLConnection resUrlConnection) {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String resName = resUrlConnection.getURL().getFile();
response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(resName));
} | [
"private",
"void",
"setContentTypeHeader",
"(",
"HttpResponse",
"response",
",",
"URLConnection",
"resUrlConnection",
")",
"{",
"MimetypesFileTypeMap",
"mimeTypesMap",
"=",
"new",
"MimetypesFileTypeMap",
"(",
")",
";",
"String",
"resName",
"=",
"resUrlConnection",
".",
"getURL",
"(",
")",
".",
"getFile",
"(",
")",
";",
"response",
".",
"headers",
"(",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"CONTENT_TYPE",
",",
"mimeTypesMap",
".",
"getContentType",
"(",
"resName",
")",
")",
";",
"}"
] | Sets the content type header for the HTTP Response
@param response
HTTP response | [
"Sets",
"the",
"content",
"type",
"header",
"for",
"the",
"HTTP",
"Response"
] | train | https://github.com/scalecube/socketio/blob/bad28fe7a132320750173e7cb71ad6d3688fb626/src/main/java/io/scalecube/socketio/pipeline/ResourceHandler.java#L205-L209 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/ssl_key.java | ssl_key.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
ssl_key_responses result = (ssl_key_responses) service.get_payload_formatter().string_to_resource(ssl_key_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ssl_key_response_array);
}
ssl_key[] result_ssl_key = new ssl_key[result.ssl_key_response_array.length];
for(int i = 0; i < result.ssl_key_response_array.length; i++)
{
result_ssl_key[i] = result.ssl_key_response_array[i].ssl_key[0];
}
return result_ssl_key;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ssl_key_responses result = (ssl_key_responses) service.get_payload_formatter().string_to_resource(ssl_key_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ssl_key_response_array);
}
ssl_key[] result_ssl_key = new ssl_key[result.ssl_key_response_array.length];
for(int i = 0; i < result.ssl_key_response_array.length; i++)
{
result_ssl_key[i] = result.ssl_key_response_array[i].ssl_key[0];
}
return result_ssl_key;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"ssl_key_responses",
"result",
"=",
"(",
"ssl_key_responses",
")",
"service",
".",
"get_payload_formatter",
"(",
")",
".",
"string_to_resource",
"(",
"ssl_key_responses",
".",
"class",
",",
"response",
")",
";",
"if",
"(",
"result",
".",
"errorcode",
"!=",
"0",
")",
"{",
"if",
"(",
"result",
".",
"errorcode",
"==",
"SESSION_NOT_EXISTS",
")",
"service",
".",
"clear_session",
"(",
")",
";",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
",",
"(",
"base_response",
"[",
"]",
")",
"result",
".",
"ssl_key_response_array",
")",
";",
"}",
"ssl_key",
"[",
"]",
"result_ssl_key",
"=",
"new",
"ssl_key",
"[",
"result",
".",
"ssl_key_response_array",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"result",
".",
"ssl_key_response_array",
".",
"length",
";",
"i",
"++",
")",
"{",
"result_ssl_key",
"[",
"i",
"]",
"=",
"result",
".",
"ssl_key_response_array",
"[",
"i",
"]",
".",
"ssl_key",
"[",
"0",
"]",
";",
"}",
"return",
"result_ssl_key",
";",
"}"
] | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/ssl_key.java#L265-L282 |
puniverse/capsule | capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java | ProcessUtil.getLocalConnectorAddress | public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {
"""
Returns the JMX connector address of a child process.
@param p the process to which to connect
@param startAgent whether to installed the JMX agent in the target process if not already in place
@return a {@link JMXServiceURL} to the process's MBean server
"""
return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);
} | java | public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {
return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);
} | [
"public",
"static",
"JMXServiceURL",
"getLocalConnectorAddress",
"(",
"Process",
"p",
",",
"boolean",
"startAgent",
")",
"{",
"return",
"getLocalConnectorAddress",
"(",
"Integer",
".",
"toString",
"(",
"getPid",
"(",
"p",
")",
")",
",",
"startAgent",
")",
";",
"}"
] | Returns the JMX connector address of a child process.
@param p the process to which to connect
@param startAgent whether to installed the JMX agent in the target process if not already in place
@return a {@link JMXServiceURL} to the process's MBean server | [
"Returns",
"the",
"JMX",
"connector",
"address",
"of",
"a",
"child",
"process",
"."
] | train | https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java#L85-L87 |
sculptor/sculptor | sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java | JpaHelper.createResultCountQuery | public static String createResultCountQuery(String query) {
"""
Build a query based on the original query to count results
@param query
@return
"""
String resultCountQueryString = null;
int select = query.toLowerCase().indexOf("select");
int from = query.toLowerCase().indexOf("from");
if (select == -1 || from == -1) {
return null;
}
resultCountQueryString = "select count(" + query.substring(select + 6, from).trim() + ") " + query.substring(from);
// remove order by
// TODO: remove more parts
if (resultCountQueryString.toLowerCase().contains("order by")) {
resultCountQueryString = resultCountQueryString.substring(0, resultCountQueryString.toLowerCase().indexOf("order by"));
}
log.debug("Created query for counting results '{}'", resultCountQueryString);
return resultCountQueryString;
} | java | public static String createResultCountQuery(String query) {
String resultCountQueryString = null;
int select = query.toLowerCase().indexOf("select");
int from = query.toLowerCase().indexOf("from");
if (select == -1 || from == -1) {
return null;
}
resultCountQueryString = "select count(" + query.substring(select + 6, from).trim() + ") " + query.substring(from);
// remove order by
// TODO: remove more parts
if (resultCountQueryString.toLowerCase().contains("order by")) {
resultCountQueryString = resultCountQueryString.substring(0, resultCountQueryString.toLowerCase().indexOf("order by"));
}
log.debug("Created query for counting results '{}'", resultCountQueryString);
return resultCountQueryString;
} | [
"public",
"static",
"String",
"createResultCountQuery",
"(",
"String",
"query",
")",
"{",
"String",
"resultCountQueryString",
"=",
"null",
";",
"int",
"select",
"=",
"query",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"\"select\"",
")",
";",
"int",
"from",
"=",
"query",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"\"from\"",
")",
";",
"if",
"(",
"select",
"==",
"-",
"1",
"||",
"from",
"==",
"-",
"1",
")",
"{",
"return",
"null",
";",
"}",
"resultCountQueryString",
"=",
"\"select count(\"",
"+",
"query",
".",
"substring",
"(",
"select",
"+",
"6",
",",
"from",
")",
".",
"trim",
"(",
")",
"+",
"\") \"",
"+",
"query",
".",
"substring",
"(",
"from",
")",
";",
"// remove order by\r",
"// TODO: remove more parts\r",
"if",
"(",
"resultCountQueryString",
".",
"toLowerCase",
"(",
")",
".",
"contains",
"(",
"\"order by\"",
")",
")",
"{",
"resultCountQueryString",
"=",
"resultCountQueryString",
".",
"substring",
"(",
"0",
",",
"resultCountQueryString",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"\"order by\"",
")",
")",
";",
"}",
"log",
".",
"debug",
"(",
"\"Created query for counting results '{}'\"",
",",
"resultCountQueryString",
")",
";",
"return",
"resultCountQueryString",
";",
"}"
] | Build a query based on the original query to count results
@param query
@return | [
"Build",
"a",
"query",
"based",
"on",
"the",
"original",
"query",
"to",
"count",
"results"
] | train | https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java#L257-L276 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/WWindowInterceptor.java | WWindowInterceptor.preparePaint | @Override
public void preparePaint(final Request request) {
"""
Temporarily replaces the environment while the UI prepares to render.
@param request the request being responded to.
"""
if (windowId == null) {
super.preparePaint(request);
} else {
// Get the window component
ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
if (target == null) {
throw new SystemException("No window component for id " + windowId);
}
UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
Environment originalEnvironment = uic.getEnvironment();
uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target));
UIContextHolder.pushContext(target.getContext());
try {
super.preparePaint(request);
} finally {
uic.setEnvironment(originalEnvironment);
UIContextHolder.popContext();
}
}
} | java | @Override
public void preparePaint(final Request request) {
if (windowId == null) {
super.preparePaint(request);
} else {
// Get the window component
ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
if (target == null) {
throw new SystemException("No window component for id " + windowId);
}
UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
Environment originalEnvironment = uic.getEnvironment();
uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target));
UIContextHolder.pushContext(target.getContext());
try {
super.preparePaint(request);
} finally {
uic.setEnvironment(originalEnvironment);
UIContextHolder.popContext();
}
}
} | [
"@",
"Override",
"public",
"void",
"preparePaint",
"(",
"final",
"Request",
"request",
")",
"{",
"if",
"(",
"windowId",
"==",
"null",
")",
"{",
"super",
".",
"preparePaint",
"(",
"request",
")",
";",
"}",
"else",
"{",
"// Get the window component",
"ComponentWithContext",
"target",
"=",
"WebUtilities",
".",
"getComponentById",
"(",
"windowId",
",",
"true",
")",
";",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"throw",
"new",
"SystemException",
"(",
"\"No window component for id \"",
"+",
"windowId",
")",
";",
"}",
"UIContext",
"uic",
"=",
"UIContextHolder",
".",
"getCurrentPrimaryUIContext",
"(",
")",
";",
"Environment",
"originalEnvironment",
"=",
"uic",
".",
"getEnvironment",
"(",
")",
";",
"uic",
".",
"setEnvironment",
"(",
"new",
"EnvironmentDelegate",
"(",
"originalEnvironment",
",",
"windowId",
",",
"target",
")",
")",
";",
"UIContextHolder",
".",
"pushContext",
"(",
"target",
".",
"getContext",
"(",
")",
")",
";",
"try",
"{",
"super",
".",
"preparePaint",
"(",
"request",
")",
";",
"}",
"finally",
"{",
"uic",
".",
"setEnvironment",
"(",
"originalEnvironment",
")",
";",
"UIContextHolder",
".",
"popContext",
"(",
")",
";",
"}",
"}",
"}"
] | Temporarily replaces the environment while the UI prepares to render.
@param request the request being responded to. | [
"Temporarily",
"replaces",
"the",
"environment",
"while",
"the",
"UI",
"prepares",
"to",
"render",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/WWindowInterceptor.java#L90-L113 |
cdk/cdk | base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/QueryAtomContainerCreator.java | QueryAtomContainerCreator.createAnyAtomContainer | public static QueryAtomContainer createAnyAtomContainer(IAtomContainer container, boolean aromaticity) {
"""
Creates a QueryAtomContainer with the following settings:
<pre>
// aromaticity = true
QueryAtomContainer.create(container,
Expr.Type.IS_AROMATIC,
Expr.Type.ALIPHATIC_ORDER);
// aromaticity = false
QueryAtomContainer.create(container,
Expr.Type.ORDER);
</pre>
@param container The AtomContainer that stands as model
@param aromaticity option flag
@return The new QueryAtomContainer created from container.
"""
if (aromaticity)
return QueryAtomContainer.create(container,
Expr.Type.IS_AROMATIC,
Expr.Type.ALIPHATIC_ORDER);
else
return QueryAtomContainer.create(container,
Expr.Type.ORDER);
} | java | public static QueryAtomContainer createAnyAtomContainer(IAtomContainer container, boolean aromaticity) {
if (aromaticity)
return QueryAtomContainer.create(container,
Expr.Type.IS_AROMATIC,
Expr.Type.ALIPHATIC_ORDER);
else
return QueryAtomContainer.create(container,
Expr.Type.ORDER);
} | [
"public",
"static",
"QueryAtomContainer",
"createAnyAtomContainer",
"(",
"IAtomContainer",
"container",
",",
"boolean",
"aromaticity",
")",
"{",
"if",
"(",
"aromaticity",
")",
"return",
"QueryAtomContainer",
".",
"create",
"(",
"container",
",",
"Expr",
".",
"Type",
".",
"IS_AROMATIC",
",",
"Expr",
".",
"Type",
".",
"ALIPHATIC_ORDER",
")",
";",
"else",
"return",
"QueryAtomContainer",
".",
"create",
"(",
"container",
",",
"Expr",
".",
"Type",
".",
"ORDER",
")",
";",
"}"
] | Creates a QueryAtomContainer with the following settings:
<pre>
// aromaticity = true
QueryAtomContainer.create(container,
Expr.Type.IS_AROMATIC,
Expr.Type.ALIPHATIC_ORDER);
// aromaticity = false
QueryAtomContainer.create(container,
Expr.Type.ORDER);
</pre>
@param container The AtomContainer that stands as model
@param aromaticity option flag
@return The new QueryAtomContainer created from container. | [
"Creates",
"a",
"QueryAtomContainer",
"with",
"the",
"following",
"settings",
":"
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/QueryAtomContainerCreator.java#L151-L159 |
teatrove/teatrove | tea/src/main/java/org/teatrove/tea/util/FileCompilationProvider.java | FileCompilationProvider.getSourceFile | protected File getSourceFile(String name) {
"""
Get the source file relative to the root source directory for the given
template.
@param name The fully-qualified name of the template
@return The file reference to the source file
"""
String fileName = name.replace('.', File.separatorChar) + ".tea";
File file = new File(mRootSourceDir, fileName);
return file;
} | java | protected File getSourceFile(String name) {
String fileName = name.replace('.', File.separatorChar) + ".tea";
File file = new File(mRootSourceDir, fileName);
return file;
} | [
"protected",
"File",
"getSourceFile",
"(",
"String",
"name",
")",
"{",
"String",
"fileName",
"=",
"name",
".",
"replace",
"(",
"'",
"'",
",",
"File",
".",
"separatorChar",
")",
"+",
"\".tea\"",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"mRootSourceDir",
",",
"fileName",
")",
";",
"return",
"file",
";",
"}"
] | Get the source file relative to the root source directory for the given
template.
@param name The fully-qualified name of the template
@return The file reference to the source file | [
"Get",
"the",
"source",
"file",
"relative",
"to",
"the",
"root",
"source",
"directory",
"for",
"the",
"given",
"template",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/tea/src/main/java/org/teatrove/tea/util/FileCompilationProvider.java#L246-L251 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java | EnumHelper.getFromIDOrDefault | @Nullable
public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrDefault (@Nonnull final Class <ENUMTYPE> aClass,
@Nullable final KEYTYPE aID,
@Nullable final ENUMTYPE eDefault) {
"""
Get the enum value with the passed ID
@param <KEYTYPE>
The ID type
@param <ENUMTYPE>
The enum type
@param aClass
The enum class
@param aID
The ID to search
@param eDefault
The default value to be returned, if the ID was not found.
@return The default parameter if no enum item with the given ID is present.
"""
ValueEnforcer.notNull (aClass, "Class");
if (aID == null)
return eDefault;
return findFirst (aClass, x -> x.getID ().equals (aID), eDefault);
} | java | @Nullable
public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrDefault (@Nonnull final Class <ENUMTYPE> aClass,
@Nullable final KEYTYPE aID,
@Nullable final ENUMTYPE eDefault)
{
ValueEnforcer.notNull (aClass, "Class");
if (aID == null)
return eDefault;
return findFirst (aClass, x -> x.getID ().equals (aID), eDefault);
} | [
"@",
"Nullable",
"public",
"static",
"<",
"KEYTYPE",
",",
"ENUMTYPE",
"extends",
"Enum",
"<",
"ENUMTYPE",
">",
"&",
"IHasID",
"<",
"KEYTYPE",
">",
">",
"ENUMTYPE",
"getFromIDOrDefault",
"(",
"@",
"Nonnull",
"final",
"Class",
"<",
"ENUMTYPE",
">",
"aClass",
",",
"@",
"Nullable",
"final",
"KEYTYPE",
"aID",
",",
"@",
"Nullable",
"final",
"ENUMTYPE",
"eDefault",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aClass",
",",
"\"Class\"",
")",
";",
"if",
"(",
"aID",
"==",
"null",
")",
"return",
"eDefault",
";",
"return",
"findFirst",
"(",
"aClass",
",",
"x",
"->",
"x",
".",
"getID",
"(",
")",
".",
"equals",
"(",
"aID",
")",
",",
"eDefault",
")",
";",
"}"
] | Get the enum value with the passed ID
@param <KEYTYPE>
The ID type
@param <ENUMTYPE>
The enum type
@param aClass
The enum class
@param aID
The ID to search
@param eDefault
The default value to be returned, if the ID was not found.
@return The default parameter if no enum item with the given ID is present. | [
"Get",
"the",
"enum",
"value",
"with",
"the",
"passed",
"ID"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java#L123-L133 |
netty/netty | codec/src/main/java/io/netty/handler/codec/compression/Bzip2BitWriter.java | Bzip2BitWriter.writeBits | void writeBits(ByteBuf out, final int count, final long value) {
"""
Writes up to 32 bits to the output {@link ByteBuf}.
@param count The number of bits to write (maximum {@code 32} as a size of {@code int})
@param value The bits to write
"""
if (count < 0 || count > 32) {
throw new IllegalArgumentException("count: " + count + " (expected: 0-32)");
}
int bitCount = this.bitCount;
long bitBuffer = this.bitBuffer | value << 64 - count >>> bitCount;
bitCount += count;
if (bitCount >= 32) {
out.writeInt((int) (bitBuffer >>> 32));
bitBuffer <<= 32;
bitCount -= 32;
}
this.bitBuffer = bitBuffer;
this.bitCount = bitCount;
} | java | void writeBits(ByteBuf out, final int count, final long value) {
if (count < 0 || count > 32) {
throw new IllegalArgumentException("count: " + count + " (expected: 0-32)");
}
int bitCount = this.bitCount;
long bitBuffer = this.bitBuffer | value << 64 - count >>> bitCount;
bitCount += count;
if (bitCount >= 32) {
out.writeInt((int) (bitBuffer >>> 32));
bitBuffer <<= 32;
bitCount -= 32;
}
this.bitBuffer = bitBuffer;
this.bitCount = bitCount;
} | [
"void",
"writeBits",
"(",
"ByteBuf",
"out",
",",
"final",
"int",
"count",
",",
"final",
"long",
"value",
")",
"{",
"if",
"(",
"count",
"<",
"0",
"||",
"count",
">",
"32",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"count: \"",
"+",
"count",
"+",
"\" (expected: 0-32)\"",
")",
";",
"}",
"int",
"bitCount",
"=",
"this",
".",
"bitCount",
";",
"long",
"bitBuffer",
"=",
"this",
".",
"bitBuffer",
"|",
"value",
"<<",
"64",
"-",
"count",
">>>",
"bitCount",
";",
"bitCount",
"+=",
"count",
";",
"if",
"(",
"bitCount",
">=",
"32",
")",
"{",
"out",
".",
"writeInt",
"(",
"(",
"int",
")",
"(",
"bitBuffer",
">>>",
"32",
")",
")",
";",
"bitBuffer",
"<<=",
"32",
";",
"bitCount",
"-=",
"32",
";",
"}",
"this",
".",
"bitBuffer",
"=",
"bitBuffer",
";",
"this",
".",
"bitCount",
"=",
"bitCount",
";",
"}"
] | Writes up to 32 bits to the output {@link ByteBuf}.
@param count The number of bits to write (maximum {@code 32} as a size of {@code int})
@param value The bits to write | [
"Writes",
"up",
"to",
"32",
"bits",
"to",
"the",
"output",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BitWriter.java#L41-L56 |
linkedin/PalDB | paldb/src/main/java/com/linkedin/paldb/utils/LongPacker.java | LongPacker.packInt | static public int packInt(DataOutput os, int value)
throws IOException {
"""
Pack non-negative int into output stream. It will occupy 1-5 bytes
depending on value (lower values occupy smaller space)
@param os the data output
@param value the value
@return the number of bytes written
@throws IOException if an error occurs with the stream
"""
if (value < 0) {
throw new IllegalArgumentException("negative value: v=" + value);
}
int i = 1;
while ((value & ~0x7F) != 0) {
os.write(((value & 0x7F) | 0x80));
value >>>= 7;
i++;
}
os.write((byte) value);
return i;
} | java | static public int packInt(DataOutput os, int value)
throws IOException {
if (value < 0) {
throw new IllegalArgumentException("negative value: v=" + value);
}
int i = 1;
while ((value & ~0x7F) != 0) {
os.write(((value & 0x7F) | 0x80));
value >>>= 7;
i++;
}
os.write((byte) value);
return i;
} | [
"static",
"public",
"int",
"packInt",
"(",
"DataOutput",
"os",
",",
"int",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"value",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"negative value: v=\"",
"+",
"value",
")",
";",
"}",
"int",
"i",
"=",
"1",
";",
"while",
"(",
"(",
"value",
"&",
"~",
"0x7F",
")",
"!=",
"0",
")",
"{",
"os",
".",
"write",
"(",
"(",
"(",
"value",
"&",
"0x7F",
")",
"|",
"0x80",
")",
")",
";",
"value",
">>>=",
"7",
";",
"i",
"++",
";",
"}",
"os",
".",
"write",
"(",
"(",
"byte",
")",
"value",
")",
";",
"return",
"i",
";",
"}"
] | Pack non-negative int into output stream. It will occupy 1-5 bytes
depending on value (lower values occupy smaller space)
@param os the data output
@param value the value
@return the number of bytes written
@throws IOException if an error occurs with the stream | [
"Pack",
"non",
"-",
"negative",
"int",
"into",
"output",
"stream",
".",
"It",
"will",
"occupy",
"1",
"-",
"5",
"bytes",
"depending",
"on",
"value",
"(",
"lower",
"values",
"occupy",
"smaller",
"space",
")"
] | train | https://github.com/linkedin/PalDB/blob/d05ccdd3f67855eb2675dbd82599f19aa7a9f650/paldb/src/main/java/com/linkedin/paldb/utils/LongPacker.java#L149-L165 |
Erudika/para | para-server/src/main/java/com/erudika/para/persistence/AWSDynamoUtils.java | AWSDynamoUtils.getKeyForAppid | public static String getKeyForAppid(String key, String appIdentifier) {
"""
Returns the correct key for an object given the appid (table name).
@param key a row id
@param appIdentifier appid
@return the key
"""
if (StringUtils.isBlank(key) || StringUtils.isBlank(appIdentifier)) {
return key;
}
if (isSharedAppid(appIdentifier)) {
// app is sharing a table with other apps, key is composite "appid_key"
return keyPrefix(appIdentifier) + key;
} else {
return key;
}
} | java | public static String getKeyForAppid(String key, String appIdentifier) {
if (StringUtils.isBlank(key) || StringUtils.isBlank(appIdentifier)) {
return key;
}
if (isSharedAppid(appIdentifier)) {
// app is sharing a table with other apps, key is composite "appid_key"
return keyPrefix(appIdentifier) + key;
} else {
return key;
}
} | [
"public",
"static",
"String",
"getKeyForAppid",
"(",
"String",
"key",
",",
"String",
"appIdentifier",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"key",
")",
"||",
"StringUtils",
".",
"isBlank",
"(",
"appIdentifier",
")",
")",
"{",
"return",
"key",
";",
"}",
"if",
"(",
"isSharedAppid",
"(",
"appIdentifier",
")",
")",
"{",
"// app is sharing a table with other apps, key is composite \"appid_key\"",
"return",
"keyPrefix",
"(",
"appIdentifier",
")",
"+",
"key",
";",
"}",
"else",
"{",
"return",
"key",
";",
"}",
"}"
] | Returns the correct key for an object given the appid (table name).
@param key a row id
@param appIdentifier appid
@return the key | [
"Returns",
"the",
"correct",
"key",
"for",
"an",
"object",
"given",
"the",
"appid",
"(",
"table",
"name",
")",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/persistence/AWSDynamoUtils.java#L355-L365 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/collections/JMListMap.java | JMListMap.addAll | public boolean addAll(K key, List<V> list) {
"""
Add all boolean.
@param key the key
@param list the list
@return the boolean
"""
return getOrPutGetNewList(key).addAll(list);
} | java | public boolean addAll(K key, List<V> list) {
return getOrPutGetNewList(key).addAll(list);
} | [
"public",
"boolean",
"addAll",
"(",
"K",
"key",
",",
"List",
"<",
"V",
">",
"list",
")",
"{",
"return",
"getOrPutGetNewList",
"(",
"key",
")",
".",
"addAll",
"(",
"list",
")",
";",
"}"
] | Add all boolean.
@param key the key
@param list the list
@return the boolean | [
"Add",
"all",
"boolean",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/collections/JMListMap.java#L102-L104 |
mscharhag/oleaster | oleaster-matcher/src/main/java/com/mscharhag/oleaster/matcher/matchers/FloatingPointNumberMatcher.java | FloatingPointNumberMatcher.toBeCloseTo | public void toBeCloseTo(double other, double delta) {
"""
Checks if the stored value is close to another value.
<p>This method throws an {@code AssertionError} if the difference between the stored value and {@code other} is
greater than {@code delta}.
@param other the value to compare with
@param delta the delta
"""
boolean isCloseTo = this.value >= other - delta && this.value <= other + delta;
Expectations.expectTrue(isCloseTo, "Expected %s to be close to %s with delta %s", this.value, other, delta);
} | java | public void toBeCloseTo(double other, double delta) {
boolean isCloseTo = this.value >= other - delta && this.value <= other + delta;
Expectations.expectTrue(isCloseTo, "Expected %s to be close to %s with delta %s", this.value, other, delta);
} | [
"public",
"void",
"toBeCloseTo",
"(",
"double",
"other",
",",
"double",
"delta",
")",
"{",
"boolean",
"isCloseTo",
"=",
"this",
".",
"value",
">=",
"other",
"-",
"delta",
"&&",
"this",
".",
"value",
"<=",
"other",
"+",
"delta",
";",
"Expectations",
".",
"expectTrue",
"(",
"isCloseTo",
",",
"\"Expected %s to be close to %s with delta %s\"",
",",
"this",
".",
"value",
",",
"other",
",",
"delta",
")",
";",
"}"
] | Checks if the stored value is close to another value.
<p>This method throws an {@code AssertionError} if the difference between the stored value and {@code other} is
greater than {@code delta}.
@param other the value to compare with
@param delta the delta | [
"Checks",
"if",
"the",
"stored",
"value",
"is",
"close",
"to",
"another",
"value",
".",
"<p",
">",
"This",
"method",
"throws",
"an",
"{"
] | train | https://github.com/mscharhag/oleaster/blob/ce8c6fe2346cd0c0cf5f641417ff85019d1d09ac/oleaster-matcher/src/main/java/com/mscharhag/oleaster/matcher/matchers/FloatingPointNumberMatcher.java#L56-L59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.