repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/ConversionService.java | ConversionService.addConverter | @SuppressWarnings("rawtypes")
public void addConverter(Function<?, ?> converter) {
LettuceAssert.notNull(converter, "Converter must not be null");
ClassTypeInformation<? extends Function> classTypeInformation = ClassTypeInformation.from(converter.getClass());
TypeInformation<?> typeInformation = classTypeInformation.getSuperTypeInformation(Function.class);
List<TypeInformation<?>> typeArguments = typeInformation.getTypeArguments();
ConvertiblePair pair = new ConvertiblePair(typeArguments.get(0).getType(), typeArguments.get(1).getType());
converterMap.put(pair, converter);
} | java | @SuppressWarnings("rawtypes")
public void addConverter(Function<?, ?> converter) {
LettuceAssert.notNull(converter, "Converter must not be null");
ClassTypeInformation<? extends Function> classTypeInformation = ClassTypeInformation.from(converter.getClass());
TypeInformation<?> typeInformation = classTypeInformation.getSuperTypeInformation(Function.class);
List<TypeInformation<?>> typeArguments = typeInformation.getTypeArguments();
ConvertiblePair pair = new ConvertiblePair(typeArguments.get(0).getType(), typeArguments.get(1).getType());
converterMap.put(pair, converter);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"void",
"addConverter",
"(",
"Function",
"<",
"?",
",",
"?",
">",
"converter",
")",
"{",
"LettuceAssert",
".",
"notNull",
"(",
"converter",
",",
"\"Converter must not be null\"",
")",
";",
"ClassTypeIn... | Register a converter {@link Function}.
@param converter the converter. | [
"Register",
"a",
"converter",
"{",
"@link",
"Function",
"}",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/ConversionService.java#L40-L51 |
Jasig/resource-server | resource-server-utils/src/main/java/org/jasig/resourceserver/utils/aggr/ResourcesElementsProviderImpl.java | ResourcesElementsProviderImpl.resolveResourceContextPath | protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
final String resourceContextPath = this.getResourceServerContextPath();
this.logger.debug("Attempting to locate resource serving webapp with context path: {}", resourceContextPath);
//Try to resolve the
final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
this.logger.warn("Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application", resourceContextPath);
return request.getContextPath();
}
this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);
URL url = null;
try {
url = resourceContext.getResource(resource);
}
catch (MalformedURLException e) {
//Ignore
}
if (url == null) {
this.logger.debug("Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.", resourceContextPath, resource);
return request.getContextPath();
}
this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.", resourceContextPath, resource);
return resourceContextPath;
} | java | protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
final String resourceContextPath = this.getResourceServerContextPath();
this.logger.debug("Attempting to locate resource serving webapp with context path: {}", resourceContextPath);
//Try to resolve the
final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
this.logger.warn("Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application", resourceContextPath);
return request.getContextPath();
}
this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);
URL url = null;
try {
url = resourceContext.getResource(resource);
}
catch (MalformedURLException e) {
//Ignore
}
if (url == null) {
this.logger.debug("Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.", resourceContextPath, resource);
return request.getContextPath();
}
this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.", resourceContextPath, resource);
return resourceContextPath;
} | [
"protected",
"String",
"resolveResourceContextPath",
"(",
"HttpServletRequest",
"request",
",",
"String",
"resource",
")",
"{",
"final",
"String",
"resourceContextPath",
"=",
"this",
".",
"getResourceServerContextPath",
"(",
")",
";",
"this",
".",
"logger",
".",
"de... | If the resource serving servlet context is available and the resource
is available in the context, create a URL to the resource in that context.
If not, create a local URL for the requested resource. | [
"If",
"the",
"resource",
"serving",
"servlet",
"context",
"is",
"available",
"and",
"the",
"resource",
"is",
"available",
"in",
"the",
"context",
"create",
"a",
"URL",
"to",
"the",
"resource",
"in",
"that",
"context",
".",
"If",
"not",
"create",
"a",
"loca... | train | https://github.com/Jasig/resource-server/blob/13375f716777ec3c99ae9917f672881d4aa32df3/resource-server-utils/src/main/java/org/jasig/resourceserver/utils/aggr/ResourcesElementsProviderImpl.java#L383-L412 |
spring-projects/spring-mobile | spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java | SiteSwitcherRequestFilter.dotMobi | private void dotMobi() throws ServletException {
if (serverName == null) {
throw new ServletException("serverName init parameter not found");
}
int lastDot = serverName.lastIndexOf('.');
this.siteSwitcherHandler = new StandardSiteSwitcherHandler(new StandardSiteUrlFactory(serverName),
new StandardSiteUrlFactory(serverName.substring(0, lastDot) + ".mobi"), null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository("." + serverName)), tabletIsMobile);
} | java | private void dotMobi() throws ServletException {
if (serverName == null) {
throw new ServletException("serverName init parameter not found");
}
int lastDot = serverName.lastIndexOf('.');
this.siteSwitcherHandler = new StandardSiteSwitcherHandler(new StandardSiteUrlFactory(serverName),
new StandardSiteUrlFactory(serverName.substring(0, lastDot) + ".mobi"), null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository("." + serverName)), tabletIsMobile);
} | [
"private",
"void",
"dotMobi",
"(",
")",
"throws",
"ServletException",
"{",
"if",
"(",
"serverName",
"==",
"null",
")",
"{",
"throw",
"new",
"ServletException",
"(",
"\"serverName init parameter not found\"",
")",
";",
"}",
"int",
"lastDot",
"=",
"serverName",
".... | Configures a site switcher that redirects to a <code>.mobi</code> domain for normal site requests that either
originate from a mobile device or indicate a mobile site preference.
Will strip off the trailing domain name when building the mobile domain
e.g. "app.com" will become "app.mobi" (the .com will be stripped).
Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is shared between the two domains. | [
"Configures",
"a",
"site",
"switcher",
"that",
"redirects",
"to",
"a",
"<code",
">",
".",
"mobi<",
"/",
"code",
">",
"domain",
"for",
"normal",
"site",
"requests",
"that",
"either",
"originate",
"from",
"a",
"mobile",
"device",
"or",
"indicate",
"a",
"mobi... | train | https://github.com/spring-projects/spring-mobile/blob/a402cbcaf208e24288b957f44c9984bd6e8bf064/spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java#L268-L276 |
airlift/slice | src/main/java/io/airlift/slice/SliceUtf8.java | SliceUtf8.firstNonMatchPosition | private static int firstNonMatchPosition(Slice utf8, int[] codePointsToMatch)
{
int length = utf8.length();
int position = 0;
while (position < length) {
int codePoint = tryGetCodePointAt(utf8, position);
if (codePoint < 0) {
break;
}
if (!matches(codePoint, codePointsToMatch)) {
break;
}
position += lengthOfCodePoint(codePoint);
}
return position;
} | java | private static int firstNonMatchPosition(Slice utf8, int[] codePointsToMatch)
{
int length = utf8.length();
int position = 0;
while (position < length) {
int codePoint = tryGetCodePointAt(utf8, position);
if (codePoint < 0) {
break;
}
if (!matches(codePoint, codePointsToMatch)) {
break;
}
position += lengthOfCodePoint(codePoint);
}
return position;
} | [
"private",
"static",
"int",
"firstNonMatchPosition",
"(",
"Slice",
"utf8",
",",
"int",
"[",
"]",
"codePointsToMatch",
")",
"{",
"int",
"length",
"=",
"utf8",
".",
"length",
"(",
")",
";",
"int",
"position",
"=",
"0",
";",
"while",
"(",
"position",
"<",
... | This function is an exact duplicate of firstNonWhitespacePosition(Slice) except for one line. | [
"This",
"function",
"is",
"an",
"exact",
"duplicate",
"of",
"firstNonWhitespacePosition",
"(",
"Slice",
")",
"except",
"for",
"one",
"line",
"."
] | train | https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/SliceUtf8.java#L417-L433 |
alkacon/opencms-core | src/org/opencms/gwt/shared/CmsTemplateContextInfo.java | CmsTemplateContextInfo.setClientVariant | public void setClientVariant(String context, String variant, CmsClientVariantInfo info) {
if (!m_clientVariantInfo.containsKey(context)) {
Map<String, CmsClientVariantInfo> variants = new LinkedHashMap<String, CmsClientVariantInfo>();
m_clientVariantInfo.put(context, variants);
}
m_clientVariantInfo.get(context).put(variant, info);
} | java | public void setClientVariant(String context, String variant, CmsClientVariantInfo info) {
if (!m_clientVariantInfo.containsKey(context)) {
Map<String, CmsClientVariantInfo> variants = new LinkedHashMap<String, CmsClientVariantInfo>();
m_clientVariantInfo.put(context, variants);
}
m_clientVariantInfo.get(context).put(variant, info);
} | [
"public",
"void",
"setClientVariant",
"(",
"String",
"context",
",",
"String",
"variant",
",",
"CmsClientVariantInfo",
"info",
")",
"{",
"if",
"(",
"!",
"m_clientVariantInfo",
".",
"containsKey",
"(",
"context",
")",
")",
"{",
"Map",
"<",
"String",
",",
"Cms... | Adds a client variant.<p>
@param context a context name
@param variant the variant name
@param info the bean with the variant information | [
"Adds",
"a",
"client",
"variant",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/shared/CmsTemplateContextInfo.java#L195-L202 |
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByAddress2 | public Iterable<DContact> queryByAddress2(Object parent, java.lang.String address2) {
return queryByField(parent, DContactMapper.Field.ADDRESS2.getFieldName(), address2);
} | java | public Iterable<DContact> queryByAddress2(Object parent, java.lang.String address2) {
return queryByField(parent, DContactMapper.Field.ADDRESS2.getFieldName(), address2);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByAddress2",
"(",
"Object",
"parent",
",",
"java",
".",
"lang",
".",
"String",
"address2",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"ADDRESS2",
".",
"getFie... | query-by method for field address2
@param address2 the specified attribute
@return an Iterable of DContacts for the specified address2 | [
"query",
"-",
"by",
"method",
"for",
"field",
"address2"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L79-L81 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java | FeatureTiles.getStylePaint | private Paint getStylePaint(StyleRow style, FeatureDrawType drawType) {
Paint paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
mil.nga.geopackage.style.Color color = null;
Float strokeWidth = null;
switch (drawType) {
case CIRCLE:
color = style.getColorOrDefault();
break;
case STROKE:
color = style.getColorOrDefault();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
case FILL:
color = style.getFillColor();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
default:
throw new GeoPackageException("Unsupported Draw Type: "
+ drawType);
}
Paint stylePaint = new Paint();
stylePaint.setColor(new Color(color.getColorWithAlpha(), true));
if (strokeWidth != null) {
stylePaint.setStrokeWidth(strokeWidth);
}
synchronized (featurePaintCache) {
paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
featurePaintCache.setPaint(style, drawType, stylePaint);
paint = stylePaint;
}
}
}
return paint;
} | java | private Paint getStylePaint(StyleRow style, FeatureDrawType drawType) {
Paint paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
mil.nga.geopackage.style.Color color = null;
Float strokeWidth = null;
switch (drawType) {
case CIRCLE:
color = style.getColorOrDefault();
break;
case STROKE:
color = style.getColorOrDefault();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
case FILL:
color = style.getFillColor();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
default:
throw new GeoPackageException("Unsupported Draw Type: "
+ drawType);
}
Paint stylePaint = new Paint();
stylePaint.setColor(new Color(color.getColorWithAlpha(), true));
if (strokeWidth != null) {
stylePaint.setStrokeWidth(strokeWidth);
}
synchronized (featurePaintCache) {
paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
featurePaintCache.setPaint(style, drawType, stylePaint);
paint = stylePaint;
}
}
}
return paint;
} | [
"private",
"Paint",
"getStylePaint",
"(",
"StyleRow",
"style",
",",
"FeatureDrawType",
"drawType",
")",
"{",
"Paint",
"paint",
"=",
"featurePaintCache",
".",
"getPaint",
"(",
"style",
",",
"drawType",
")",
";",
"if",
"(",
"paint",
"==",
"null",
")",
"{",
"... | Get the style paint from cache, or create and cache it
@param style
style row
@param drawType
draw type
@return paint | [
"Get",
"the",
"style",
"paint",
"from",
"cache",
"or",
"create",
"and",
"cache",
"it"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java#L1480-L1525 |
apereo/person-directory | person-directory-impl/src/main/java/org/apereo/services/persondir/support/MultivaluedPersonAttributeUtils.java | MultivaluedPersonAttributeUtils.addResult | @SuppressWarnings("unchecked")
public static <K, V> void addResult(final Map<K, List<V>> results, final K key, final Object value) {
Validate.notNull(results, "Cannot add a result to a null map.");
Validate.notNull(key, "Cannot add a result with a null key.");
// don't put null values into the Map.
if (value == null) {
return;
}
List<V> currentValue = results.get(key);
if (currentValue == null) {
currentValue = new LinkedList<>();
results.put(key, currentValue);
}
if (value instanceof List) {
currentValue.addAll((List<V>) value);
} else {
currentValue.add((V) value);
}
} | java | @SuppressWarnings("unchecked")
public static <K, V> void addResult(final Map<K, List<V>> results, final K key, final Object value) {
Validate.notNull(results, "Cannot add a result to a null map.");
Validate.notNull(key, "Cannot add a result with a null key.");
// don't put null values into the Map.
if (value == null) {
return;
}
List<V> currentValue = results.get(key);
if (currentValue == null) {
currentValue = new LinkedList<>();
results.put(key, currentValue);
}
if (value instanceof List) {
currentValue.addAll((List<V>) value);
} else {
currentValue.add((V) value);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"K",
",",
"V",
">",
"void",
"addResult",
"(",
"final",
"Map",
"<",
"K",
",",
"List",
"<",
"V",
">",
">",
"results",
",",
"final",
"K",
"key",
",",
"final",
"Object",
"value"... | Adds a key/value pair to the specified {@link Map}, creating multi-valued
values when appropriate.
<br>
Since multi-valued attributes end up with a value of type
{@link List}, passing in a {@link List} of any type will
cause its contents to be added to the <code>results</code>
{@link Map} directly under the specified <code>key</code>
@param <K> Key type (extends Object)
@param <V> Value type (extends Object)
@param results The {@link Map} to modify.
@param key The key to add the value for.
@param value The value to add for the key.
@throws IllegalArgumentException if any argument is null | [
"Adds",
"a",
"key",
"/",
"value",
"pair",
"to",
"the",
"specified",
"{",
"@link",
"Map",
"}",
"creating",
"multi",
"-",
"valued",
"values",
"when",
"appropriate",
".",
"<br",
">",
"Since",
"multi",
"-",
"valued",
"attributes",
"end",
"up",
"with",
"a",
... | train | https://github.com/apereo/person-directory/blob/331200c0878aec202b8aff12a732402d6ba7681f/person-directory-impl/src/main/java/org/apereo/services/persondir/support/MultivaluedPersonAttributeUtils.java#L136-L157 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/cellconverter/CellFormulaHandler.java | CellFormulaHandler.handleFormula | public void handleFormula(final FieldAccessor field, final Configuration config, final Cell cell, final Object targetBean) {
ArgUtils.notNull(field, "field");
ArgUtils.notNull(config, "config");
ArgUtils.notNull(cell, "cell");
final String evaluatedFormula = createFormulaValue(config, cell, targetBean);
if(Utils.isEmpty(evaluatedFormula)) {
cell.setCellType(CellType.BLANK);
return;
}
try {
cell.setCellFormula(evaluatedFormula);
cell.setCellType(CellType.FORMULA);
} catch(FormulaParseException e) {
// 数式の解析に失敗した場合
String message = MessageBuilder.create("cell.failParseFormula")
.var("property", field.getNameWithClass())
.var("cellAddress", CellPosition.of(cell).toString())
.var("formula", evaluatedFormula)
.format();
throw new ConversionException(message, e, field.getType());
}
} | java | public void handleFormula(final FieldAccessor field, final Configuration config, final Cell cell, final Object targetBean) {
ArgUtils.notNull(field, "field");
ArgUtils.notNull(config, "config");
ArgUtils.notNull(cell, "cell");
final String evaluatedFormula = createFormulaValue(config, cell, targetBean);
if(Utils.isEmpty(evaluatedFormula)) {
cell.setCellType(CellType.BLANK);
return;
}
try {
cell.setCellFormula(evaluatedFormula);
cell.setCellType(CellType.FORMULA);
} catch(FormulaParseException e) {
// 数式の解析に失敗した場合
String message = MessageBuilder.create("cell.failParseFormula")
.var("property", field.getNameWithClass())
.var("cellAddress", CellPosition.of(cell).toString())
.var("formula", evaluatedFormula)
.format();
throw new ConversionException(message, e, field.getType());
}
} | [
"public",
"void",
"handleFormula",
"(",
"final",
"FieldAccessor",
"field",
",",
"final",
"Configuration",
"config",
",",
"final",
"Cell",
"cell",
",",
"final",
"Object",
"targetBean",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"field",
",",
"\"field\"",
")",
... | セルに数式を設定する
@param field フィールド情報
@param config システム情報
@param cell セル情報
@param targetBean 処理対象のフィールドが定義されているクラスのインスタンス。
@throws ConversionException 数式の解析に失敗した場合。 | [
"セルに数式を設定する"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/cellconverter/CellFormulaHandler.java#L80-L107 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.toSorted | public static <T> Iterator<T> toSorted(Iterator<T> self) {
return toSorted(self, new NumberAwareComparator<T>());
} | java | public static <T> Iterator<T> toSorted(Iterator<T> self) {
return toSorted(self, new NumberAwareComparator<T>());
} | [
"public",
"static",
"<",
"T",
">",
"Iterator",
"<",
"T",
">",
"toSorted",
"(",
"Iterator",
"<",
"T",
">",
"self",
")",
"{",
"return",
"toSorted",
"(",
"self",
",",
"new",
"NumberAwareComparator",
"<",
"T",
">",
"(",
")",
")",
";",
"}"
] | Sorts the Iterator. Assumes that the Iterator elements are
comparable and uses a {@link NumberAwareComparator} to determine the resulting order.
{@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
natural ordering of the Iterator elements.
A new iterator is produced that traverses the items in sorted order.
@param self the Iterator to be sorted
@return the sorted items as an Iterator
@see #toSorted(Iterator, Comparator)
@since 2.4.0 | [
"Sorts",
"the",
"Iterator",
".",
"Assumes",
"that",
"the",
"Iterator",
"elements",
"are",
"comparable",
"and",
"uses",
"a",
"{",
"@link",
"NumberAwareComparator",
"}",
"to",
"determine",
"the",
"resulting",
"order",
".",
"{",
"@code",
"NumberAwareComparator",
"}... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L9455-L9457 |
lucee/Lucee | core/src/main/java/lucee/commons/surveillance/HeapDumper.java | HeapDumper.dumpTo | public static void dumpTo(Resource res, boolean live) throws IOException {
MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy(mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
String path;
Resource tmp = null;
if (res instanceof FileResource) path = res.getAbsolutePath();
else {
tmp = SystemUtil.getTempFile("hprof", false);
path = tmp.getAbsolutePath();
}
try {
// it only
mxbean.dumpHeap(path, live);
}
finally {
if (tmp != null && tmp.exists()) {
tmp.moveTo(res);
}
}
} | java | public static void dumpTo(Resource res, boolean live) throws IOException {
MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy(mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
String path;
Resource tmp = null;
if (res instanceof FileResource) path = res.getAbsolutePath();
else {
tmp = SystemUtil.getTempFile("hprof", false);
path = tmp.getAbsolutePath();
}
try {
// it only
mxbean.dumpHeap(path, live);
}
finally {
if (tmp != null && tmp.exists()) {
tmp.moveTo(res);
}
}
} | [
"public",
"static",
"void",
"dumpTo",
"(",
"Resource",
"res",
",",
"boolean",
"live",
")",
"throws",
"IOException",
"{",
"MBeanServer",
"mbserver",
"=",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
";",
"HotSpotDiagnosticMXBean",
"mxbean",
"=",
"M... | Dumps the heap to the outputFile file in the same format as the hprof heap dump. If this method
is called remotely from another process, the heap dump output is written to a file named
outputFile on the machine where the target VM is running. If outputFile is a relative path, it is
relative to the working directory where the target VM was started.
@param res Resource to write the .hprof file.
@param live if true dump only live objects i.e. objects that are reachable from others
@throws IOException | [
"Dumps",
"the",
"heap",
"to",
"the",
"outputFile",
"file",
"in",
"the",
"same",
"format",
"as",
"the",
"hprof",
"heap",
"dump",
".",
"If",
"this",
"method",
"is",
"called",
"remotely",
"from",
"another",
"process",
"the",
"heap",
"dump",
"output",
"is",
... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/surveillance/HeapDumper.java#L44-L65 |
centic9/commons-dost | src/main/java/org/dstadler/commons/svn/SVNCommands.java | SVNCommands.getBranchLogStream | public static InputStream getBranchLogStream(String[] branches, Date startDate, Date endDate, String baseUrl, String user, String pwd) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ROOT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
CommandLine cmdLine = getCommandLineForXMLLog(user, pwd);
cmdLine.addArgument("{" + dateFormat.format(startDate) + "}:{" + dateFormat.format(endDate) + "}");
cmdLine.addArgument(baseUrl + branches[0]);
return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000);
} | java | public static InputStream getBranchLogStream(String[] branches, Date startDate, Date endDate, String baseUrl, String user, String pwd) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ROOT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
CommandLine cmdLine = getCommandLineForXMLLog(user, pwd);
cmdLine.addArgument("{" + dateFormat.format(startDate) + "}:{" + dateFormat.format(endDate) + "}");
cmdLine.addArgument(baseUrl + branches[0]);
return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000);
} | [
"public",
"static",
"InputStream",
"getBranchLogStream",
"(",
"String",
"[",
"]",
"branches",
",",
"Date",
"startDate",
",",
"Date",
"endDate",
",",
"String",
"baseUrl",
",",
"String",
"user",
",",
"String",
"pwd",
")",
"throws",
"IOException",
"{",
"SimpleDat... | Retrieve the XML-log of changes on the given branch, starting from and ending with a specific date
This method returns an {@link InputStream} that can be used
to read and process the XML data without storing the complete result. This is useful
when you are potentially reading many revisions and thus need to avoid being limited
in memory or disk.
@param branches The list of branches to fetch logs for, currently only the first entry is used!
@param startDate The starting date for the log-entries that are fetched
@param endDate In case <code>endDate</code> is not specified, the current date is used
@param baseUrl The SVN url to connect to
@param user The SVN user or null if the default user from the machine should be used
@param pwd The SVN password or null if the default user from the machine should be used @return A stream that can be used to read the XML data, should be closed by the caller
@return An InputStream which provides the XML-log response
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure | [
"Retrieve",
"the",
"XML",
"-",
"log",
"of",
"changes",
"on",
"the",
"given",
"branch",
"starting",
"from",
"and",
"ending",
"with",
"a",
"specific",
"date",
"This",
"method",
"returns",
"an",
"{",
"@link",
"InputStream",
"}",
"that",
"can",
"be",
"used",
... | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L194-L203 |
rFlex/SCJavaTools | src/main/java/me/corsin/javatools/task/TaskQueue.java | TaskQueue.executeAsyncTimed | public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) {
final Runnable theRunnable = runnable;
// This implementation is not really suitable for now as the timer uses its own thread
// The TaskQueue itself should be able in the future to handle this without using a new thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TaskQueue.this.executeAsync(theRunnable);
}
}, inMs);
return runnable;
} | java | public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) {
final Runnable theRunnable = runnable;
// This implementation is not really suitable for now as the timer uses its own thread
// The TaskQueue itself should be able in the future to handle this without using a new thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TaskQueue.this.executeAsync(theRunnable);
}
}, inMs);
return runnable;
} | [
"public",
"<",
"T",
"extends",
"Runnable",
">",
"T",
"executeAsyncTimed",
"(",
"T",
"runnable",
",",
"long",
"inMs",
")",
"{",
"final",
"Runnable",
"theRunnable",
"=",
"runnable",
";",
"// This implementation is not really suitable for now as the timer uses its own thread... | Add a Task to the queue. The Task will be executed after "inMs" milliseconds.
@param the runnable to be executed
@param inMs The time after which the task should be processed
@return the runnable, as a convenience method | [
"Add",
"a",
"Task",
"to",
"the",
"queue",
".",
"The",
"Task",
"will",
"be",
"executed",
"after",
"inMs",
"milliseconds",
"."
] | train | https://github.com/rFlex/SCJavaTools/blob/6bafee99f12a6ad73265db64776edac2bab71f67/src/main/java/me/corsin/javatools/task/TaskQueue.java#L197-L212 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java | LegacyBehavior.getScopeExecution | public static PvmExecutionImpl getScopeExecution(ScopeImpl scope, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
ScopeImpl flowScope = scope.getFlowScope();
return activityExecutionMapping.get(flowScope);
} | java | public static PvmExecutionImpl getScopeExecution(ScopeImpl scope, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
ScopeImpl flowScope = scope.getFlowScope();
return activityExecutionMapping.get(flowScope);
} | [
"public",
"static",
"PvmExecutionImpl",
"getScopeExecution",
"(",
"ScopeImpl",
"scope",
",",
"Map",
"<",
"ScopeImpl",
",",
"PvmExecutionImpl",
">",
"activityExecutionMapping",
")",
"{",
"ScopeImpl",
"flowScope",
"=",
"scope",
".",
"getFlowScope",
"(",
")",
";",
"r... | In case the process instance was migrated from a previous version, activities which are now parsed as scopes
do not have scope executions. Use the flow scopes of these activities in order to find their execution.
- For an event subprocess this is the scope execution of the scope in which the event subprocess is embeded in
- For a multi instance sequential subprocess this is the multi instace scope body.
@param scope
@param activityExecutionMapping
@return | [
"In",
"case",
"the",
"process",
"instance",
"was",
"migrated",
"from",
"a",
"previous",
"version",
"activities",
"which",
"are",
"now",
"parsed",
"as",
"scopes",
"do",
"not",
"have",
"scope",
"executions",
".",
"Use",
"the",
"flow",
"scopes",
"of",
"these",
... | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java#L231-L234 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitArrayAccess | @Override
public R visitArrayAccess(ArrayAccessTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getIndex(), p, r);
return r;
} | java | @Override
public R visitArrayAccess(ArrayAccessTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getIndex(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitArrayAccess",
"(",
"ArrayAccessTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getExpression",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"getInde... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L664-L669 |
LearnLib/learnlib | algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java | AbstractTTTLearner.markAndPropagate | private static <I, D> void markAndPropagate(AbstractBaseDTNode<I, D> node, D label) {
AbstractBaseDTNode<I, D> curr = node;
while (curr != null && curr.getSplitData() != null) {
if (!curr.getSplitData().mark(label)) {
return;
}
curr = curr.getParent();
}
} | java | private static <I, D> void markAndPropagate(AbstractBaseDTNode<I, D> node, D label) {
AbstractBaseDTNode<I, D> curr = node;
while (curr != null && curr.getSplitData() != null) {
if (!curr.getSplitData().mark(label)) {
return;
}
curr = curr.getParent();
}
} | [
"private",
"static",
"<",
"I",
",",
"D",
">",
"void",
"markAndPropagate",
"(",
"AbstractBaseDTNode",
"<",
"I",
",",
"D",
">",
"node",
",",
"D",
"label",
")",
"{",
"AbstractBaseDTNode",
"<",
"I",
",",
"D",
">",
"curr",
"=",
"node",
";",
"while",
"(",
... | Marks a node, and propagates the label up to all nodes on the path from the block root to this node.
@param node
the node to mark
@param label
the label to mark the node with | [
"Marks",
"a",
"node",
"and",
"propagates",
"the",
"label",
"up",
"to",
"all",
"nodes",
"on",
"the",
"path",
"from",
"the",
"block",
"root",
"to",
"this",
"node",
"."
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java#L99-L108 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ObjectUtils.java | ObjectUtils.safeGetValue | public static <T> T safeGetValue(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
}
catch (Throwable ignore) {
return defaultValue;
}
} | java | public static <T> T safeGetValue(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
}
catch (Throwable ignore) {
return defaultValue;
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"safeGetValue",
"(",
"Supplier",
"<",
"T",
">",
"supplier",
",",
"T",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"supplier",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ignore",
")",
"{",
... | Safely returns the value supplied by the given {@link Supplier}. If an {@link Exception} or {@link Error} occurs
then the {@code defaultValue} will be returned.
@param <T> {@link Class} type of the value to get.
@param supplier {@link Supplier} of the value.
@param defaultValue value to return if the {@link Supplier} is unable to supply the value.
@return a value from the given {@link Supplier} in an error safe manner. If an {@link Exception} or {@link Error}
occurs then the {@code defaultValue} will be returned.
@see java.util.function.Supplier | [
"Safely",
"returns",
"the",
"value",
"supplied",
"by",
"the",
"given",
"{",
"@link",
"Supplier",
"}",
".",
"If",
"an",
"{",
"@link",
"Exception",
"}",
"or",
"{",
"@link",
"Error",
"}",
"occurs",
"then",
"the",
"{",
"@code",
"defaultValue",
"}",
"will",
... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ObjectUtils.java#L263-L271 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/editor/DefaultDataEditorWidget.java | DefaultDataEditorWidget.executeFilter | @Override
public synchronized void executeFilter(Map<String, Object> parameters) {
if (listWorker == null) {
if (dataProvider.supportsBaseCriteria()) {
dataProvider.setBaseCriteria(getBaseCriteria());
}
StatusBar statusBar = getApplicationConfig().windowManager()
.getActiveWindow().getStatusBar();
statusBar.getProgressMonitor().taskStarted(
getApplicationConfig().messageResolver().getMessage("statusBar",
"loadTable", MessageConstants.LABEL),
StatusBarProgressMonitor.UNKNOWN);
// getFilterForm().getCommitCommand().setEnabled(false);
// getRefreshCommand().setEnabled(false);
listWorker = new ListRetrievingWorker();
if (dataProvider.supportsFiltering()) {
if (parameters.containsKey(PARAMETER_FILTER)) {
setFilterModel(parameters.get(PARAMETER_FILTER));
}
listWorker.filterCriteria = getFilterForm().getFilterCriteria();
}
listWorker.parameters = parameters;
log.debug("Execute Filter with criteria: "
+ listWorker.filterCriteria + " and parameters: "
+ parameters);
listWorker.execute();
}
} | java | @Override
public synchronized void executeFilter(Map<String, Object> parameters) {
if (listWorker == null) {
if (dataProvider.supportsBaseCriteria()) {
dataProvider.setBaseCriteria(getBaseCriteria());
}
StatusBar statusBar = getApplicationConfig().windowManager()
.getActiveWindow().getStatusBar();
statusBar.getProgressMonitor().taskStarted(
getApplicationConfig().messageResolver().getMessage("statusBar",
"loadTable", MessageConstants.LABEL),
StatusBarProgressMonitor.UNKNOWN);
// getFilterForm().getCommitCommand().setEnabled(false);
// getRefreshCommand().setEnabled(false);
listWorker = new ListRetrievingWorker();
if (dataProvider.supportsFiltering()) {
if (parameters.containsKey(PARAMETER_FILTER)) {
setFilterModel(parameters.get(PARAMETER_FILTER));
}
listWorker.filterCriteria = getFilterForm().getFilterCriteria();
}
listWorker.parameters = parameters;
log.debug("Execute Filter with criteria: "
+ listWorker.filterCriteria + " and parameters: "
+ parameters);
listWorker.execute();
}
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"executeFilter",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
")",
"{",
"if",
"(",
"listWorker",
"==",
"null",
")",
"{",
"if",
"(",
"dataProvider",
".",
"supportsBaseCriteria",
"(",
")",
")... | Executes filter and fills table in specific manner:
<p/>
<ul>
<li>set baseCriteria if needed</li>
<li>set searchCriteria on filterForm</li>
<li>set searchCriteria on worker</li>
<li>pass parameter map to worker</li>
<li>launch worker to retrieve list from back-end and fill table</li>
<li>when done, set list and execute additional code taking the parameters
into account</li>
</ul>
@param parameters
a number of parameters that can influence this run. Should be
a non-modifiable map or a specific instance. | [
"Executes",
"filter",
"and",
"fills",
"table",
"in",
"specific",
"manner",
":",
"<p",
"/",
">",
"<ul",
">",
"<li",
">",
"set",
"baseCriteria",
"if",
"needed<",
"/",
"li",
">",
"<li",
">",
"set",
"searchCriteria",
"on",
"filterForm<",
"/",
"li",
">",
"<... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/editor/DefaultDataEditorWidget.java#L480-L511 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java | FormatUtil.format | public static String format(double[] v, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
int width = w + 1;
StringBuilder msg = new StringBuilder() //
.append('\n'); // start on new line.
for(int i = 0; i < v.length; i++) {
String s = format.format(v[i]); // format the number
// At _least_ 1 whitespace is added
whitespace(msg, Math.max(1, width - s.length())).append(s);
}
return msg.toString();
} | java | public static String format(double[] v, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
int width = w + 1;
StringBuilder msg = new StringBuilder() //
.append('\n'); // start on new line.
for(int i = 0; i < v.length; i++) {
String s = format.format(v[i]); // format the number
// At _least_ 1 whitespace is added
whitespace(msg, Math.max(1, width - s.length())).append(s);
}
return msg.toString();
} | [
"public",
"static",
"String",
"format",
"(",
"double",
"[",
"]",
"v",
",",
"int",
"w",
",",
"int",
"d",
")",
"{",
"DecimalFormat",
"format",
"=",
"new",
"DecimalFormat",
"(",
")",
";",
"format",
".",
"setDecimalFormatSymbols",
"(",
"new",
"DecimalFormatSym... | Returns a string representation of this vector.
@param w column width
@param d number of digits after the decimal
@return a string representation of this matrix | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"vector",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java#L240-L257 |
sdl/Testy | src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java | WebLocatorAbstractBuilder.setTitle | @SuppressWarnings("unchecked")
public <T extends WebLocatorAbstractBuilder> T setTitle(String title, SearchType... searchTypes) {
pathBuilder.setTitle(title, searchTypes);
return (T) this;
} | java | @SuppressWarnings("unchecked")
public <T extends WebLocatorAbstractBuilder> T setTitle(String title, SearchType... searchTypes) {
pathBuilder.setTitle(title, searchTypes);
return (T) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"WebLocatorAbstractBuilder",
">",
"T",
"setTitle",
"(",
"String",
"title",
",",
"SearchType",
"...",
"searchTypes",
")",
"{",
"pathBuilder",
".",
"setTitle",
"(",
"title",
",",
... | <p><b>Used for finding element process (to generate xpath address)</b></p>
@param title of element
@param searchTypes see {@link SearchType}
@param <T> the element which calls this method
@return this element | [
"<p",
">",
"<b",
">",
"Used",
"for",
"finding",
"element",
"process",
"(",
"to",
"generate",
"xpath",
"address",
")",
"<",
"/",
"b",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java#L261-L265 |
jenetics/jpx | jpx/src/main/java/io/jenetics/jpx/Length.java | Length.of | public static Length of(final double length, final Unit unit) {
requireNonNull(unit);
return new Length(Unit.METER.convert(length, unit));
} | java | public static Length of(final double length, final Unit unit) {
requireNonNull(unit);
return new Length(Unit.METER.convert(length, unit));
} | [
"public",
"static",
"Length",
"of",
"(",
"final",
"double",
"length",
",",
"final",
"Unit",
"unit",
")",
"{",
"requireNonNull",
"(",
"unit",
")",
";",
"return",
"new",
"Length",
"(",
"Unit",
".",
"METER",
".",
"convert",
"(",
"length",
",",
"unit",
")"... | Create a new {@code Length} object with the given length.
@param length the length
@param unit the length unit
@return a new {@code Length} object with the given length.
@throws NullPointerException if the given length {@code unit} is
{@code null} | [
"Create",
"a",
"new",
"{",
"@code",
"Length",
"}",
"object",
"with",
"the",
"given",
"length",
"."
] | train | https://github.com/jenetics/jpx/blob/58fefc10580602d07f1480d6a5886d13a553ff8f/jpx/src/main/java/io/jenetics/jpx/Length.java#L210-L213 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/DefaultWardenService.java | DefaultWardenService._constructWardenAlertForUser | private Alert _constructWardenAlertForUser(PrincipalUser user, PolicyCounter counter) {
String metricExp = _constructWardenMetricExpression("-1h", user, counter);
Alert alert = new Alert(_adminUser, _adminUser, _constructWardenAlertName(user, counter), metricExp, "*/5 * * * *");
List<Trigger> triggers = new ArrayList<>();
EntityManager em = emf.get();
double limit = PolicyLimit.getLimitByUserAndCounter(em, user, counter);
Trigger trigger = new Trigger(alert, counter.getTriggerType(), "counter-value-" + counter.getTriggerType().toString() + "-policy-limit",
limit, 0.0, 0L);
triggers.add(trigger);
List<Notification> notifications = new ArrayList<>();
Notification notification = new Notification(NOTIFICATION_NAME, alert, _getWardenNotifierClass(counter), new ArrayList<String>(), 3600000);
List<String> metricAnnotationList = new ArrayList<String>();
String wardenMetricAnnotation = MessageFormat.format("{0}:{1}'{'user={2}'}':sum", Counter.WARDEN_TRIGGERS.getScope(),
Counter.WARDEN_TRIGGERS.getMetric(), user.getUserName());
metricAnnotationList.add(wardenMetricAnnotation);
notification.setMetricsToAnnotate(metricAnnotationList);
notification.setTriggers(triggers);
notifications.add(notification);
alert.setTriggers(triggers);
alert.setNotifications(notifications);
return alert;
} | java | private Alert _constructWardenAlertForUser(PrincipalUser user, PolicyCounter counter) {
String metricExp = _constructWardenMetricExpression("-1h", user, counter);
Alert alert = new Alert(_adminUser, _adminUser, _constructWardenAlertName(user, counter), metricExp, "*/5 * * * *");
List<Trigger> triggers = new ArrayList<>();
EntityManager em = emf.get();
double limit = PolicyLimit.getLimitByUserAndCounter(em, user, counter);
Trigger trigger = new Trigger(alert, counter.getTriggerType(), "counter-value-" + counter.getTriggerType().toString() + "-policy-limit",
limit, 0.0, 0L);
triggers.add(trigger);
List<Notification> notifications = new ArrayList<>();
Notification notification = new Notification(NOTIFICATION_NAME, alert, _getWardenNotifierClass(counter), new ArrayList<String>(), 3600000);
List<String> metricAnnotationList = new ArrayList<String>();
String wardenMetricAnnotation = MessageFormat.format("{0}:{1}'{'user={2}'}':sum", Counter.WARDEN_TRIGGERS.getScope(),
Counter.WARDEN_TRIGGERS.getMetric(), user.getUserName());
metricAnnotationList.add(wardenMetricAnnotation);
notification.setMetricsToAnnotate(metricAnnotationList);
notification.setTriggers(triggers);
notifications.add(notification);
alert.setTriggers(triggers);
alert.setNotifications(notifications);
return alert;
} | [
"private",
"Alert",
"_constructWardenAlertForUser",
"(",
"PrincipalUser",
"user",
",",
"PolicyCounter",
"counter",
")",
"{",
"String",
"metricExp",
"=",
"_constructWardenMetricExpression",
"(",
"\"-1h\"",
",",
"user",
",",
"counter",
")",
";",
"Alert",
"alert",
"=",... | Create a warden alert which will annotate the corresponding warden metric with suspension events.
@param user The user for which the notification should be created. Cannot be null.
@param counter The policy counter for which the notification should be created. Cannot be null.
@return The warden alert. | [
"Create",
"a",
"warden",
"alert",
"which",
"will",
"annotate",
"the",
"corresponding",
"warden",
"metric",
"with",
"suspension",
"events",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/warden/DefaultWardenService.java#L441-L466 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_statistics_process_GET | public ArrayList<OvhRtmCommandSize> serviceName_statistics_process_GET(String serviceName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/statistics/process";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t10);
} | java | public ArrayList<OvhRtmCommandSize> serviceName_statistics_process_GET(String serviceName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/statistics/process";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t10);
} | [
"public",
"ArrayList",
"<",
"OvhRtmCommandSize",
">",
"serviceName_statistics_process_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/statistics/process\"",
";",
"StringBuilder",
"sb",
"=",
"p... | Get server process
REST: GET /dedicated/server/{serviceName}/statistics/process
@param serviceName [required] The internal name of your dedicated server | [
"Get",
"server",
"process"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1318-L1323 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java | NodeSetDTM.addNodes | public void addNodes(DTMIterator iterator)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!");
if (null != iterator) // defensive to fix a bug that Sanjiva reported.
{
int obj;
while (DTM.NULL != (obj = iterator.nextNode()))
{
addElement(obj);
}
}
// checkDups();
} | java | public void addNodes(DTMIterator iterator)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!");
if (null != iterator) // defensive to fix a bug that Sanjiva reported.
{
int obj;
while (DTM.NULL != (obj = iterator.nextNode()))
{
addElement(obj);
}
}
// checkDups();
} | [
"public",
"void",
"addNodes",
"(",
"DTMIterator",
"iterator",
")",
"{",
"if",
"(",
"!",
"m_mutable",
")",
"throw",
"new",
"RuntimeException",
"(",
"XSLMessages",
".",
"createXPATHMessage",
"(",
"XPATHErrorResources",
".",
"ER_NODESETDTM_NOT_MUTABLE",
",",
"null",
... | Copy NodeList members into this nodelist, adding in
document order. Null references are not added.
@param iterator DTMIterator which yields the nodes to be added.
@throws RuntimeException thrown if this NodeSetDTM is not of
a mutable type. | [
"Copy",
"NodeList",
"members",
"into",
"this",
"nodelist",
"adding",
"in",
"document",
"order",
".",
"Null",
"references",
"are",
"not",
"added",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java#L646-L663 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/util/GosuStringUtil.java | GosuStringUtil.indexOfAny | public static int indexOfAny(String str, char[] searchChars) {
if (isEmpty(str) || searchChars == null) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
} | java | public static int indexOfAny(String str, char[] searchChars) {
if (isEmpty(str) || searchChars == null) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"indexOfAny",
"(",
"String",
"str",
",",
"char",
"[",
"]",
"searchChars",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
"||",
"searchChars",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"for",
"(",
"int",
"i",... | <p>Search a String to find the first index of any
character in the given set of characters.</p>
<p>A <code>null</code> String will return <code>-1</code>.
A <code>null</code> or zero length search array will return <code>-1</code>.</p>
<pre>
GosuStringUtil.indexOfAny(null, *) = -1
GosuStringUtil.indexOfAny("", *) = -1
GosuStringUtil.indexOfAny(*, null) = -1
GosuStringUtil.indexOfAny(*, []) = -1
GosuStringUtil.indexOfAny("zzabyycdxx",['z','a']) = 0
GosuStringUtil.indexOfAny("zzabyycdxx",['b','y']) = 3
GosuStringUtil.indexOfAny("aba", ['z']) = -1
</pre>
@param str the String to check, may be null
@param searchChars the chars to search for, may be null
@return the index of any of the chars, -1 if no match or null input
@since 2.0 | [
"<p",
">",
"Search",
"a",
"String",
"to",
"find",
"the",
"first",
"index",
"of",
"any",
"character",
"in",
"the",
"given",
"set",
"of",
"characters",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L1067-L1080 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/VoltTrace.java | VoltTrace.closeAllAndShutdown | public static String closeAllAndShutdown(String logDir, long timeOutMillis) throws IOException {
String path = null;
final VoltTrace tracer = s_tracer;
if (tracer != null) {
if (logDir != null) {
path = dump(logDir);
}
s_tracer = null;
if (timeOutMillis >= 0) {
try {
tracer.m_writerThread.shutdownNow();
tracer.m_writerThread.awaitTermination(timeOutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
}
tracer.shutdown();
}
return path;
} | java | public static String closeAllAndShutdown(String logDir, long timeOutMillis) throws IOException {
String path = null;
final VoltTrace tracer = s_tracer;
if (tracer != null) {
if (logDir != null) {
path = dump(logDir);
}
s_tracer = null;
if (timeOutMillis >= 0) {
try {
tracer.m_writerThread.shutdownNow();
tracer.m_writerThread.awaitTermination(timeOutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
}
tracer.shutdown();
}
return path;
} | [
"public",
"static",
"String",
"closeAllAndShutdown",
"(",
"String",
"logDir",
",",
"long",
"timeOutMillis",
")",
"throws",
"IOException",
"{",
"String",
"path",
"=",
"null",
";",
"final",
"VoltTrace",
"tracer",
"=",
"s_tracer",
";",
"if",
"(",
"tracer",
"!=",
... | Close all open files and wait for shutdown.
@param logDir The directory to write the trace events to, null to skip writing to file.
@param timeOutMillis Timeout in milliseconds. Negative to not wait
@return The path to the trace file if written, or null if a write is already in progress. | [
"Close",
"all",
"open",
"files",
"and",
"wait",
"for",
"shutdown",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/VoltTrace.java#L515-L538 |
orhanobut/dialogplus | dialogplus/src/main/java/com/orhanobut/dialogplus/Utils.java | Utils.getAnimationResource | static int getAnimationResource(int gravity, boolean isInAnimation) {
if ((gravity & Gravity.TOP) == Gravity.TOP) {
return isInAnimation ? R.anim.slide_in_top : R.anim.slide_out_top;
}
if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
return isInAnimation ? R.anim.slide_in_bottom : R.anim.slide_out_bottom;
}
if ((gravity & Gravity.CENTER) == Gravity.CENTER) {
return isInAnimation ? R.anim.fade_in_center : R.anim.fade_out_center;
}
return INVALID;
} | java | static int getAnimationResource(int gravity, boolean isInAnimation) {
if ((gravity & Gravity.TOP) == Gravity.TOP) {
return isInAnimation ? R.anim.slide_in_top : R.anim.slide_out_top;
}
if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
return isInAnimation ? R.anim.slide_in_bottom : R.anim.slide_out_bottom;
}
if ((gravity & Gravity.CENTER) == Gravity.CENTER) {
return isInAnimation ? R.anim.fade_in_center : R.anim.fade_out_center;
}
return INVALID;
} | [
"static",
"int",
"getAnimationResource",
"(",
"int",
"gravity",
",",
"boolean",
"isInAnimation",
")",
"{",
"if",
"(",
"(",
"gravity",
"&",
"Gravity",
".",
"TOP",
")",
"==",
"Gravity",
".",
"TOP",
")",
"{",
"return",
"isInAnimation",
"?",
"R",
".",
"anim"... | Get default animation resource when not defined by the user
@param gravity the gravity of the dialog
@param isInAnimation determine if is in or out animation. true when is is
@return the id of the animation resource | [
"Get",
"default",
"animation",
"resource",
"when",
"not",
"defined",
"by",
"the",
"user"
] | train | https://github.com/orhanobut/dialogplus/blob/291bf4daaa3c81bf5537125f547913beb8ee2c17/dialogplus/src/main/java/com/orhanobut/dialogplus/Utils.java#L63-L74 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.updateGroup | public GitlabGroup updateGroup(GitlabGroup group, GitlabUser sudoUser) throws IOException {
Query query = new Query()
.appendIf("name", group.getName())
.appendIf("path", group.getPath())
.appendIf("description", group.getDescription())
.appendIf("membership_lock", group.getMembershipLock())
.appendIf("share_with_group_lock", group.getShareWithGroupLock())
.appendIf("visibility", group.getVisibility().toString())
.appendIf("lfs_enabled", group.isLfsEnabled())
.appendIf("request_access_enabled", group.isRequestAccessEnabled())
.appendIf("shared_runners_minutes_limit", group.getSharedRunnersMinutesLimit())
.appendIf("ldap_cn", group.getLdapCn())
.appendIf("ldap_access", group.getLdapAccess())
.appendIf(PARAM_SUDO, sudoUser != null ? sudoUser.getId() : null);
String tailUrl = GitlabGroup.URL + "/" + group.getId() + query.toString();
return retrieve().method(PUT).to(tailUrl, GitlabGroup.class);
} | java | public GitlabGroup updateGroup(GitlabGroup group, GitlabUser sudoUser) throws IOException {
Query query = new Query()
.appendIf("name", group.getName())
.appendIf("path", group.getPath())
.appendIf("description", group.getDescription())
.appendIf("membership_lock", group.getMembershipLock())
.appendIf("share_with_group_lock", group.getShareWithGroupLock())
.appendIf("visibility", group.getVisibility().toString())
.appendIf("lfs_enabled", group.isLfsEnabled())
.appendIf("request_access_enabled", group.isRequestAccessEnabled())
.appendIf("shared_runners_minutes_limit", group.getSharedRunnersMinutesLimit())
.appendIf("ldap_cn", group.getLdapCn())
.appendIf("ldap_access", group.getLdapAccess())
.appendIf(PARAM_SUDO, sudoUser != null ? sudoUser.getId() : null);
String tailUrl = GitlabGroup.URL + "/" + group.getId() + query.toString();
return retrieve().method(PUT).to(tailUrl, GitlabGroup.class);
} | [
"public",
"GitlabGroup",
"updateGroup",
"(",
"GitlabGroup",
"group",
",",
"GitlabUser",
"sudoUser",
")",
"throws",
"IOException",
"{",
"Query",
"query",
"=",
"new",
"Query",
"(",
")",
".",
"appendIf",
"(",
"\"name\"",
",",
"group",
".",
"getName",
"(",
")",
... | Updates a Group
@param group the group object
@param sudoUser The user to create the group on behalf of
@return The GitLab Group
@throws IOException on gitlab api call error | [
"Updates",
"a",
"Group"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L689-L708 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java | MutableRoaringArray.appendCopy | protected void appendCopy(PointableRoaringArray highLowContainer, int startingIndex, int end) {
extendArray(end - startingIndex);
for (int i = startingIndex; i < end; ++i) {
this.keys[this.size] = highLowContainer.getKeyAtIndex(i);
this.values[this.size] = highLowContainer.getContainerAtIndex(i).clone();
this.size++;
}
} | java | protected void appendCopy(PointableRoaringArray highLowContainer, int startingIndex, int end) {
extendArray(end - startingIndex);
for (int i = startingIndex; i < end; ++i) {
this.keys[this.size] = highLowContainer.getKeyAtIndex(i);
this.values[this.size] = highLowContainer.getContainerAtIndex(i).clone();
this.size++;
}
} | [
"protected",
"void",
"appendCopy",
"(",
"PointableRoaringArray",
"highLowContainer",
",",
"int",
"startingIndex",
",",
"int",
"end",
")",
"{",
"extendArray",
"(",
"end",
"-",
"startingIndex",
")",
";",
"for",
"(",
"int",
"i",
"=",
"startingIndex",
";",
"i",
... | Append copies of the values from another array
@param highLowContainer other array
@param startingIndex starting index in the other array
@param end last index array in the other array | [
"Append",
"copies",
"of",
"the",
"values",
"from",
"another",
"array"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringArray.java#L188-L195 |
actframework/actframework | src/main/java/act/event/EventBus.java | EventBus.emitAsync | public EventBus emitAsync(String event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
} | java | public EventBus emitAsync(String event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
} | [
"public",
"EventBus",
"emitAsync",
"(",
"String",
"event",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"_emitWithOnceBus",
"(",
"eventContextAsync",
"(",
"event",
",",
"args",
")",
")",
";",
"}"
] | Emit a string event with parameters and force all listeners to be called asynchronously.
@param event
the target event
@param args
the arguments passed in
@see #emit(String, Object...) | [
"Emit",
"a",
"string",
"event",
"with",
"parameters",
"and",
"force",
"all",
"listeners",
"to",
"be",
"called",
"asynchronously",
"."
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1022-L1024 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/notifier/GOCNotifier.java | GOCNotifier._sendAdditionalNotification | protected void _sendAdditionalNotification(NotificationContext context, NotificationStatus status) {
requireArgument(context != null, "Notification context cannot be null.");
if(status == NotificationStatus.TRIGGERED) {
super.sendAdditionalNotification(context);
}else {
super.clearAdditionalNotification(context);
}
Notification notification = null;
Trigger trigger = null;
for (Notification tempNotification : context.getAlert().getNotifications()) {
if (tempNotification.getName().equalsIgnoreCase(context.getNotification().getName())) {
notification = tempNotification;
break;
}
}
requireArgument(notification != null, "Notification in notification context cannot be null.");
for (Trigger tempTrigger : context.getAlert().getTriggers()) {
if (tempTrigger.getName().equalsIgnoreCase(context.getTrigger().getName())) {
trigger = tempTrigger;
break;
}
}
requireArgument(trigger != null, "Trigger in notification context cannot be null.");
String body = getGOCMessageBody(notification, trigger, context, status);
Severity sev = status == NotificationStatus.CLEARED ? Severity.OK : Severity.ERROR;
sendMessage(sev, TemplateReplacer.applyTemplateChanges(context, context.getNotification().getName()), TemplateReplacer.applyTemplateChanges(context, context.getAlert().getName()), TemplateReplacer.applyTemplateChanges(context, context.getTrigger().getName()), body,
context.getNotification().getSeverityLevel(),context.getNotification().getSRActionable(), context.getTriggerFiredTime(), context.getTriggeredMetric());
} | java | protected void _sendAdditionalNotification(NotificationContext context, NotificationStatus status) {
requireArgument(context != null, "Notification context cannot be null.");
if(status == NotificationStatus.TRIGGERED) {
super.sendAdditionalNotification(context);
}else {
super.clearAdditionalNotification(context);
}
Notification notification = null;
Trigger trigger = null;
for (Notification tempNotification : context.getAlert().getNotifications()) {
if (tempNotification.getName().equalsIgnoreCase(context.getNotification().getName())) {
notification = tempNotification;
break;
}
}
requireArgument(notification != null, "Notification in notification context cannot be null.");
for (Trigger tempTrigger : context.getAlert().getTriggers()) {
if (tempTrigger.getName().equalsIgnoreCase(context.getTrigger().getName())) {
trigger = tempTrigger;
break;
}
}
requireArgument(trigger != null, "Trigger in notification context cannot be null.");
String body = getGOCMessageBody(notification, trigger, context, status);
Severity sev = status == NotificationStatus.CLEARED ? Severity.OK : Severity.ERROR;
sendMessage(sev, TemplateReplacer.applyTemplateChanges(context, context.getNotification().getName()), TemplateReplacer.applyTemplateChanges(context, context.getAlert().getName()), TemplateReplacer.applyTemplateChanges(context, context.getTrigger().getName()), body,
context.getNotification().getSeverityLevel(),context.getNotification().getSRActionable(), context.getTriggerFiredTime(), context.getTriggeredMetric());
} | [
"protected",
"void",
"_sendAdditionalNotification",
"(",
"NotificationContext",
"context",
",",
"NotificationStatus",
"status",
")",
"{",
"requireArgument",
"(",
"context",
"!=",
"null",
",",
"\"Notification context cannot be null.\"",
")",
";",
"if",
"(",
"status",
"==... | Update the state of the notification to indicate whether the triggering condition exists or has been cleared.
@param context The notification context. Cannot be null.
@param status The notification status. If null, will set the notification severity to <tt>ERROR</tt> | [
"Update",
"the",
"state",
"of",
"the",
"notification",
"to",
"indicate",
"whether",
"the",
"triggering",
"condition",
"exists",
"or",
"has",
"been",
"cleared",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/notifier/GOCNotifier.java#L232-L264 |
xm-online/xm-commons | xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/service/PermissionCheckService.java | PermissionCheckService.hasPermission | @SuppressWarnings("unchecked")
public boolean hasPermission(Authentication authentication,
Serializable resource,
String resourceType,
Object privilege) {
boolean logPermission = isLogPermission(resource);
if (checkRole(authentication, privilege, logPermission)) {
return true;
}
if (resource != null) {
Object resourceId = ((Map<String, Object>) resource).get("id");
if (resourceId != null) {
((Map<String, Object>) resource).put(resourceType,
resourceFactory.getResource(resourceId, resourceType));
}
}
return checkPermission(authentication, resource, privilege, true, logPermission);
} | java | @SuppressWarnings("unchecked")
public boolean hasPermission(Authentication authentication,
Serializable resource,
String resourceType,
Object privilege) {
boolean logPermission = isLogPermission(resource);
if (checkRole(authentication, privilege, logPermission)) {
return true;
}
if (resource != null) {
Object resourceId = ((Map<String, Object>) resource).get("id");
if (resourceId != null) {
((Map<String, Object>) resource).put(resourceType,
resourceFactory.getResource(resourceId, resourceType));
}
}
return checkPermission(authentication, resource, privilege, true, logPermission);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"boolean",
"hasPermission",
"(",
"Authentication",
"authentication",
",",
"Serializable",
"resource",
",",
"String",
"resourceType",
",",
"Object",
"privilege",
")",
"{",
"boolean",
"logPermission",
"=",
... | Check permission for role, privilege key, new resource and old resource.
@param authentication the authentication
@param resource the old resource
@param resourceType the resource type
@param privilege the privilege key
@return true if permitted | [
"Check",
"permission",
"for",
"role",
"privilege",
"key",
"new",
"resource",
"and",
"old",
"resource",
"."
] | train | https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/service/PermissionCheckService.java#L84-L101 |
apache/groovy | subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java | DateUtilExtensions.plus | public static java.sql.Date plus(java.sql.Date self, int days) {
return new java.sql.Date(plus((Date) self, days).getTime());
} | java | public static java.sql.Date plus(java.sql.Date self, int days) {
return new java.sql.Date(plus((Date) self, days).getTime());
} | [
"public",
"static",
"java",
".",
"sql",
".",
"Date",
"plus",
"(",
"java",
".",
"sql",
".",
"Date",
"self",
",",
"int",
"days",
")",
"{",
"return",
"new",
"java",
".",
"sql",
".",
"Date",
"(",
"plus",
"(",
"(",
"Date",
")",
"self",
",",
"days",
... | Add a number of days to this date and returns the new date.
@param self a java.sql.Date
@param days the number of days to increase
@return the new date
@since 1.0 | [
"Add",
"a",
"number",
"of",
"days",
"to",
"this",
"date",
"and",
"returns",
"the",
"new",
"date",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java#L392-L394 |
alipay/sofa-rpc | core/common/src/main/java/com/alipay/sofa/rpc/common/utils/CommonUtils.java | CommonUtils.join | public static String join(Collection collection, String separator) {
if (isEmpty(collection)) {
return StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder();
for (Object object : collection) {
if (object != null) {
String string = StringUtils.toString(object);
if (string != null) {
sb.append(string).append(separator);
}
}
}
return sb.length() > 0 ? sb.substring(0, sb.length() - separator.length()) : StringUtils.EMPTY;
} | java | public static String join(Collection collection, String separator) {
if (isEmpty(collection)) {
return StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder();
for (Object object : collection) {
if (object != null) {
String string = StringUtils.toString(object);
if (string != null) {
sb.append(string).append(separator);
}
}
}
return sb.length() > 0 ? sb.substring(0, sb.length() - separator.length()) : StringUtils.EMPTY;
} | [
"public",
"static",
"String",
"join",
"(",
"Collection",
"collection",
",",
"String",
"separator",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"collection",
")",
")",
"{",
"return",
"StringUtils",
".",
"EMPTY",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"String... | 连接集合类为字符串
@param collection 集合
@param separator 分隔符
@return 分隔符连接的字符串 | [
"连接集合类为字符串"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/CommonUtils.java#L263-L277 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/Matrix.java | Matrix.diagMult | public static void diagMult(Matrix A, Vec b)
{
if(A.cols() != b.length())
throw new ArithmeticException("Could not multiply, matrix dimensions must agree");
for(int i = 0; i < A.rows(); i++)
RowColumnOps.multRow(A, i, b);
} | java | public static void diagMult(Matrix A, Vec b)
{
if(A.cols() != b.length())
throw new ArithmeticException("Could not multiply, matrix dimensions must agree");
for(int i = 0; i < A.rows(); i++)
RowColumnOps.multRow(A, i, b);
} | [
"public",
"static",
"void",
"diagMult",
"(",
"Matrix",
"A",
",",
"Vec",
"b",
")",
"{",
"if",
"(",
"A",
".",
"cols",
"(",
")",
"!=",
"b",
".",
"length",
"(",
")",
")",
"throw",
"new",
"ArithmeticException",
"(",
"\"Could not multiply, matrix dimensions must... | Alters the matrix <i>A</i> so that it contains the result of <i>A</i>
times a sparse matrix represented by only its diagonal values or
<i>A = A*diag(<b>b</b>)</i>. This is equivalent to the code
<code>
A = A{@link #multiply(jsat.linear.Matrix) .multiply}
({@link #diag(jsat.linear.Vec) diag}(b))
</code>
@param A the square matrix to update
@param b the diagonal value vector | [
"Alters",
"the",
"matrix",
"<i",
">",
"A<",
"/",
"i",
">",
"so",
"that",
"it",
"contains",
"the",
"result",
"of",
"<i",
">",
"A<",
"/",
"i",
">",
"times",
"a",
"sparse",
"matrix",
"represented",
"by",
"only",
"its",
"diagonal",
"values",
"or",
"<i",
... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/Matrix.java#L1037-L1043 |
alkacon/opencms-core | src/org/opencms/ui/contextmenu/CmsContextMenu.java | CmsContextMenu.setEntries | public <T> void setEntries(Collection<I_CmsSimpleContextMenuEntry<T>> entries, T data) {
removeAllItems();
Locale locale = UI.getCurrent().getLocale();
for (final I_CmsSimpleContextMenuEntry<T> entry : entries) {
CmsMenuItemVisibilityMode visibility = entry.getVisibility(data);
if (!visibility.isInVisible()) {
ContextMenuItem item = addItem(entry.getTitle(locale));
if (visibility.isInActive()) {
item.setEnabled(false);
if (visibility.getMessageKey() != null) {
item.setDescription(CmsVaadinUtils.getMessageText(visibility.getMessageKey()));
}
} else {
item.setData(data);
item.addItemClickListener(new ContextMenuItemClickListener() {
@SuppressWarnings("unchecked")
public void contextMenuItemClicked(ContextMenuItemClickEvent event) {
entry.executeAction((T)((ContextMenuItem)event.getSource()).getData());
}
});
}
if (entry instanceof I_CmsSimpleContextMenuEntry.I_HasCssStyles) {
item.addStyleName(((I_CmsSimpleContextMenuEntry.I_HasCssStyles)entry).getStyles());
}
}
}
} | java | public <T> void setEntries(Collection<I_CmsSimpleContextMenuEntry<T>> entries, T data) {
removeAllItems();
Locale locale = UI.getCurrent().getLocale();
for (final I_CmsSimpleContextMenuEntry<T> entry : entries) {
CmsMenuItemVisibilityMode visibility = entry.getVisibility(data);
if (!visibility.isInVisible()) {
ContextMenuItem item = addItem(entry.getTitle(locale));
if (visibility.isInActive()) {
item.setEnabled(false);
if (visibility.getMessageKey() != null) {
item.setDescription(CmsVaadinUtils.getMessageText(visibility.getMessageKey()));
}
} else {
item.setData(data);
item.addItemClickListener(new ContextMenuItemClickListener() {
@SuppressWarnings("unchecked")
public void contextMenuItemClicked(ContextMenuItemClickEvent event) {
entry.executeAction((T)((ContextMenuItem)event.getSource()).getData());
}
});
}
if (entry instanceof I_CmsSimpleContextMenuEntry.I_HasCssStyles) {
item.addStyleName(((I_CmsSimpleContextMenuEntry.I_HasCssStyles)entry).getStyles());
}
}
}
} | [
"public",
"<",
"T",
">",
"void",
"setEntries",
"(",
"Collection",
"<",
"I_CmsSimpleContextMenuEntry",
"<",
"T",
">",
">",
"entries",
",",
"T",
"data",
")",
"{",
"removeAllItems",
"(",
")",
";",
"Locale",
"locale",
"=",
"UI",
".",
"getCurrent",
"(",
")",
... | Sets the context menu entries. Removes all previously present entries.<p>
@param entries the entries
@param data the context data | [
"Sets",
"the",
"context",
"menu",
"entries",
".",
"Removes",
"all",
"previously",
"present",
"entries",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/contextmenu/CmsContextMenu.java#L1252-L1281 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository.liberty/src/com/ibm/ws/repository/connections/liberty/MainRepository.java | MainRepository.repositoryDescriptionFileExists | public static boolean repositoryDescriptionFileExists(RestRepositoryConnectionProxy proxy) {
boolean exists = false;
try {
URL propertiesFileURL = getPropertiesFileLocation();
// Are we accessing the properties file (from DHE) using a proxy ?
if (proxy != null) {
if (proxy.isHTTPorHTTPS()) {
Proxy javaNetProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getProxyURL().getHost(), proxy.getProxyURL().getPort()));
URLConnection connection = propertiesFileURL.openConnection(javaNetProxy);
InputStream is = connection.getInputStream();
exists = true;
is.close();
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
} else {
// The proxy is not an HTTP or HTTPS proxy we do not support this
UnsupportedOperationException ue = new UnsupportedOperationException("Non-HTTP proxy not supported");
throw new IOException(ue);
}
} else {
// not using a proxy
InputStream is = propertiesFileURL.openStream();
exists = true;
is.close();
}
} catch (MalformedURLException e) {
// ignore
} catch (IOException e) {
// ignore
}
return exists;
} | java | public static boolean repositoryDescriptionFileExists(RestRepositoryConnectionProxy proxy) {
boolean exists = false;
try {
URL propertiesFileURL = getPropertiesFileLocation();
// Are we accessing the properties file (from DHE) using a proxy ?
if (proxy != null) {
if (proxy.isHTTPorHTTPS()) {
Proxy javaNetProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getProxyURL().getHost(), proxy.getProxyURL().getPort()));
URLConnection connection = propertiesFileURL.openConnection(javaNetProxy);
InputStream is = connection.getInputStream();
exists = true;
is.close();
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
} else {
// The proxy is not an HTTP or HTTPS proxy we do not support this
UnsupportedOperationException ue = new UnsupportedOperationException("Non-HTTP proxy not supported");
throw new IOException(ue);
}
} else {
// not using a proxy
InputStream is = propertiesFileURL.openStream();
exists = true;
is.close();
}
} catch (MalformedURLException e) {
// ignore
} catch (IOException e) {
// ignore
}
return exists;
} | [
"public",
"static",
"boolean",
"repositoryDescriptionFileExists",
"(",
"RestRepositoryConnectionProxy",
"proxy",
")",
"{",
"boolean",
"exists",
"=",
"false",
";",
"try",
"{",
"URL",
"propertiesFileURL",
"=",
"getPropertiesFileLocation",
"(",
")",
";",
"// Are we accessi... | Tests if the repository description properties file exists as defined by the
location override system property or at the default location
@return true if the properties file exists, otherwise false | [
"Tests",
"if",
"the",
"repository",
"description",
"properties",
"file",
"exists",
"as",
"defined",
"by",
"the",
"location",
"override",
"system",
"property",
"or",
"at",
"the",
"default",
"location"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.liberty/src/com/ibm/ws/repository/connections/liberty/MainRepository.java#L118-L160 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java | HelixSolver.getRise | private static double getRise(Matrix4d transformation, Point3d p1,
Point3d p2) {
AxisAngle4d axis = getAxisAngle(transformation);
Vector3d h = new Vector3d(axis.x, axis.y, axis.z);
Vector3d p = new Vector3d();
p.sub(p1, p2);
return p.dot(h);
} | java | private static double getRise(Matrix4d transformation, Point3d p1,
Point3d p2) {
AxisAngle4d axis = getAxisAngle(transformation);
Vector3d h = new Vector3d(axis.x, axis.y, axis.z);
Vector3d p = new Vector3d();
p.sub(p1, p2);
return p.dot(h);
} | [
"private",
"static",
"double",
"getRise",
"(",
"Matrix4d",
"transformation",
",",
"Point3d",
"p1",
",",
"Point3d",
"p2",
")",
"{",
"AxisAngle4d",
"axis",
"=",
"getAxisAngle",
"(",
"transformation",
")",
";",
"Vector3d",
"h",
"=",
"new",
"Vector3d",
"(",
"axi... | Returns the rise of a helix given the subunit centers of two adjacent
subunits and the helix transformation
@param transformation
helix transformation
@param p1
center of one subunit
@param p2
center of an adjacent subunit
@return | [
"Returns",
"the",
"rise",
"of",
"a",
"helix",
"given",
"the",
"subunit",
"centers",
"of",
"two",
"adjacent",
"subunits",
"and",
"the",
"helix",
"transformation"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java#L407-L414 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WPartialDateField.java | WPartialDateField.isValidCharacters | private boolean isValidCharacters(final String component, final char padding) {
// Check the component is either all padding chars or all digit chars
boolean paddingChars = false;
boolean digitChars = false;
for (int i = 0; i < component.length(); i++) {
char chr = component.charAt(i);
// Padding
if (chr == padding) {
if (digitChars) {
return false;
}
paddingChars = true;
} else if (chr >= '0' && chr <= '9') { // Digit
if (paddingChars) {
return false;
}
digitChars = true;
} else {
return false;
}
}
return true;
} | java | private boolean isValidCharacters(final String component, final char padding) {
// Check the component is either all padding chars or all digit chars
boolean paddingChars = false;
boolean digitChars = false;
for (int i = 0; i < component.length(); i++) {
char chr = component.charAt(i);
// Padding
if (chr == padding) {
if (digitChars) {
return false;
}
paddingChars = true;
} else if (chr >= '0' && chr <= '9') { // Digit
if (paddingChars) {
return false;
}
digitChars = true;
} else {
return false;
}
}
return true;
} | [
"private",
"boolean",
"isValidCharacters",
"(",
"final",
"String",
"component",
",",
"final",
"char",
"padding",
")",
"{",
"// Check the component is either all padding chars or all digit chars",
"boolean",
"paddingChars",
"=",
"false",
";",
"boolean",
"digitChars",
"=",
... | Check the component is either all padding chars or all digit chars.
@param component the date component.
@param padding the padding character.
@return true if the component is valid, otherwise false | [
"Check",
"the",
"component",
"is",
"either",
"all",
"padding",
"chars",
"or",
"all",
"digit",
"chars",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WPartialDateField.java#L695-L718 |
mgm-tp/jfunk | jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/data/FormData.java | FormData.indexFormEntry | private boolean indexFormEntry(final FormData formData, final Field field, final int index, final Map<String, String> fixedValues) {
String entryKey = field.getEntryKey();
FormEntry entry = formData.getFormEntry(entryKey);
boolean unique = field.isUnique();
String value = entry.getValue();
String indexedKey = entryKey + JFunkConstants.INDEXED_KEY_SEPARATOR + index;
if (fixedValues != null && fixedValues.containsKey(indexedKey)) {
return true;
}
if (unique && !uniqueValuesMap.put(entry.getKey(), value)) {
log.debug("Value for " + entryKey + " has already been generated, but has to be unique.");
return false;
}
FormEntry target = getFormEntry(indexedKey);
target.setCurrentValue(value);
return true;
} | java | private boolean indexFormEntry(final FormData formData, final Field field, final int index, final Map<String, String> fixedValues) {
String entryKey = field.getEntryKey();
FormEntry entry = formData.getFormEntry(entryKey);
boolean unique = field.isUnique();
String value = entry.getValue();
String indexedKey = entryKey + JFunkConstants.INDEXED_KEY_SEPARATOR + index;
if (fixedValues != null && fixedValues.containsKey(indexedKey)) {
return true;
}
if (unique && !uniqueValuesMap.put(entry.getKey(), value)) {
log.debug("Value for " + entryKey + " has already been generated, but has to be unique.");
return false;
}
FormEntry target = getFormEntry(indexedKey);
target.setCurrentValue(value);
return true;
} | [
"private",
"boolean",
"indexFormEntry",
"(",
"final",
"FormData",
"formData",
",",
"final",
"Field",
"field",
",",
"final",
"int",
"index",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"fixedValues",
")",
"{",
"String",
"entryKey",
"=",
"field",
... | Sets the {@link FormEntry} for {@code key+index} to the value of the {@link FormEntry} for
{@code key}. This method can be used for several lines within the same basic data set.
@return true if a value could be generated, false if the value already existed (but cannot be
regenerated because of it having to be unique) | [
"Sets",
"the",
"{",
"@link",
"FormEntry",
"}",
"for",
"{",
"@code",
"key",
"+",
"index",
"}",
"to",
"the",
"value",
"of",
"the",
"{",
"@link",
"FormEntry",
"}",
"for",
"{",
"@code",
"key",
"}",
".",
"This",
"method",
"can",
"be",
"used",
"for",
"se... | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/data/FormData.java#L287-L306 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java | Metric.addDatapoints | public void addDatapoints(Map<Long, Double> datapoints) {
if (datapoints != null) {
_datapoints.putAll(datapoints);
}
} | java | public void addDatapoints(Map<Long, Double> datapoints) {
if (datapoints != null) {
_datapoints.putAll(datapoints);
}
} | [
"public",
"void",
"addDatapoints",
"(",
"Map",
"<",
"Long",
",",
"Double",
">",
"datapoints",
")",
"{",
"if",
"(",
"datapoints",
"!=",
"null",
")",
"{",
"_datapoints",
".",
"putAll",
"(",
"datapoints",
")",
";",
"}",
"}"
] | Adds the current set of data points to the current set.
@param datapoints The set of data points to add. If null or empty, only the deletion of the current set of data points is performed. | [
"Adds",
"the",
"current",
"set",
"of",
"data",
"points",
"to",
"the",
"current",
"set",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java#L173-L177 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java | CacheManager.downloadAreaAsync | public CacheManagerTask downloadAreaAsync(Context ctx, List<Long> pTiles, final int zoomMin, final int zoomMax) {
final CacheManagerTask task = new CacheManagerTask(this, getDownloadingAction(), pTiles, zoomMin, zoomMax);
task.addCallback(getDownloadingDialog(ctx, task));
return execute(task);
} | java | public CacheManagerTask downloadAreaAsync(Context ctx, List<Long> pTiles, final int zoomMin, final int zoomMax) {
final CacheManagerTask task = new CacheManagerTask(this, getDownloadingAction(), pTiles, zoomMin, zoomMax);
task.addCallback(getDownloadingDialog(ctx, task));
return execute(task);
} | [
"public",
"CacheManagerTask",
"downloadAreaAsync",
"(",
"Context",
"ctx",
",",
"List",
"<",
"Long",
">",
"pTiles",
",",
"final",
"int",
"zoomMin",
",",
"final",
"int",
"zoomMax",
")",
"{",
"final",
"CacheManagerTask",
"task",
"=",
"new",
"CacheManagerTask",
"(... | Download in background all tiles of the specified area in osmdroid cache.
@param ctx
@param pTiles
@param zoomMin
@param zoomMax | [
"Download",
"in",
"background",
"all",
"tiles",
"of",
"the",
"specified",
"area",
"in",
"osmdroid",
"cache",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java#L495-L499 |
BioPAX/Paxtools | paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java | BioPAXIOHandlerAdapter.createAndAdd | protected void createAndAdd(Model model, String id, String localName)
{
BioPAXElement bpe = this.getFactory().create(localName, id);
if (log.isTraceEnabled())
{
log.trace("id:" + id + " " + localName + " : " + bpe);
}
/* null might occur here,
* so the following is to prevent the NullPointerException
* and to continue the model assembling.
*/
if (bpe != null)
{
model.add(bpe);
} else
{
log.warn("null object created during reading. It might not be an official BioPAX class.ID: " + id +
" Class " +
"name " + localName);
}
} | java | protected void createAndAdd(Model model, String id, String localName)
{
BioPAXElement bpe = this.getFactory().create(localName, id);
if (log.isTraceEnabled())
{
log.trace("id:" + id + " " + localName + " : " + bpe);
}
/* null might occur here,
* so the following is to prevent the NullPointerException
* and to continue the model assembling.
*/
if (bpe != null)
{
model.add(bpe);
} else
{
log.warn("null object created during reading. It might not be an official BioPAX class.ID: " + id +
" Class " +
"name " + localName);
}
} | [
"protected",
"void",
"createAndAdd",
"(",
"Model",
"model",
",",
"String",
"id",
",",
"String",
"localName",
")",
"{",
"BioPAXElement",
"bpe",
"=",
"this",
".",
"getFactory",
"(",
")",
".",
"create",
"(",
"localName",
",",
"id",
")",
";",
"if",
"(",
"l... | This method is called by the reader for each OWL instance in the OWL model. It creates a POJO instance, with
the given id and inserts it into the model. The inserted object is "clean" in the sense that its properties are
not set yet.
Implementers of this abstract class can override this method to inject code during object creation.
@param model to be inserted
@param id of the new object. The model should not contain another object with the same ID.
@param localName of the class to be instantiated. | [
"This",
"method",
"is",
"called",
"by",
"the",
"reader",
"for",
"each",
"OWL",
"instance",
"in",
"the",
"OWL",
"model",
".",
"It",
"creates",
"a",
"POJO",
"instance",
"with",
"the",
"given",
"id",
"and",
"inserts",
"it",
"into",
"the",
"model",
".",
"T... | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java#L244-L265 |
dadoonet/fscrawler | framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java | FsCrawlerUtil.readJsonVersionedFile | private static String readJsonVersionedFile(Path dir, String version, String type) throws IOException {
Path file = dir.resolve(version).resolve(type + ".json");
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
} | java | private static String readJsonVersionedFile(Path dir, String version, String type) throws IOException {
Path file = dir.resolve(version).resolve(type + ".json");
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
} | [
"private",
"static",
"String",
"readJsonVersionedFile",
"(",
"Path",
"dir",
",",
"String",
"version",
",",
"String",
"type",
")",
"throws",
"IOException",
"{",
"Path",
"file",
"=",
"dir",
".",
"resolve",
"(",
"version",
")",
".",
"resolve",
"(",
"type",
"+... | Reads a mapping from dir/version/type.json file
@param dir Directory containing mapping files per major version
@param version Elasticsearch major version number (only major digit is kept so for 2.3.4 it will be 2)
@param type The expected type (will be expanded to type.json)
@return the mapping
@throws IOException If the mapping can not be read | [
"Reads",
"a",
"mapping",
"from",
"dir",
"/",
"version",
"/",
"type",
".",
"json",
"file"
] | train | https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java#L100-L103 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newAuthorizationException | public static AuthorizationException newAuthorizationException(String message, Object... args) {
return newAuthorizationException(null, message, args);
} | java | public static AuthorizationException newAuthorizationException(String message, Object... args) {
return newAuthorizationException(null, message, args);
} | [
"public",
"static",
"AuthorizationException",
"newAuthorizationException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newAuthorizationException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] | Constructs and initializes a new {@link AuthorizationException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link AuthorizationException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link AuthorizationException} with the given {@link String message}.
@see #newAuthorizationException(Throwable, String, Object...)
@see org.cp.elements.security.AuthorizationException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"AuthorizationException",
"}",
"with",
"the",
"given",
"{",
"@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#L613-L615 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/QueryBuilder.java | QueryBuilder.selectDistinct | @NonNull
public static Select selectDistinct(@NonNull SelectResult... results) {
if (results == null) { throw new IllegalArgumentException("results cannot be null."); }
return new Select(true, results);
} | java | @NonNull
public static Select selectDistinct(@NonNull SelectResult... results) {
if (results == null) { throw new IllegalArgumentException("results cannot be null."); }
return new Select(true, results);
} | [
"@",
"NonNull",
"public",
"static",
"Select",
"selectDistinct",
"(",
"@",
"NonNull",
"SelectResult",
"...",
"results",
")",
"{",
"if",
"(",
"results",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"results cannot be null.\"",
")",
";... | Create a SELECT DISTINCT statement instance that you can use further
(e.g. calling the from() function) to construct the complete query statement.
@param results The array of the SelectResult object for specifying the returned values.
@return A Select distinct object. | [
"Create",
"a",
"SELECT",
"DISTINCT",
"statement",
"instance",
"that",
"you",
"can",
"use",
"further",
"(",
"e",
".",
"g",
".",
"calling",
"the",
"from",
"()",
"function",
")",
"to",
"construct",
"the",
"complete",
"query",
"statement",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/QueryBuilder.java#L48-L52 |
protostuff/protostuff | protostuff-msgpack/src/main/java/io/protostuff/MsgpackXIOUtil.java | MsgpackXIOUtil.writeListTo | public static <T> void writeListTo(LinkedBuffer buffer,
List<T> messages, Schema<T> schema, boolean numeric)
{
if (buffer.start != buffer.offset)
{
throw new IllegalArgumentException("Buffer previously used and had not been reset.");
}
if (messages.isEmpty())
{
return;
}
MsgpackXOutput output = new MsgpackXOutput(buffer, numeric, schema);
try
{
for (T m : messages)
{
LinkedBuffer objectStarter = output.writeStartObject();
schema.writeTo(output, m);
if (output.isLastRepeated())
{
output.writeEndArray();
}
output.writeEndObject(objectStarter);
}
}
catch (IOException e)
{
throw new RuntimeException("Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
} | java | public static <T> void writeListTo(LinkedBuffer buffer,
List<T> messages, Schema<T> schema, boolean numeric)
{
if (buffer.start != buffer.offset)
{
throw new IllegalArgumentException("Buffer previously used and had not been reset.");
}
if (messages.isEmpty())
{
return;
}
MsgpackXOutput output = new MsgpackXOutput(buffer, numeric, schema);
try
{
for (T m : messages)
{
LinkedBuffer objectStarter = output.writeStartObject();
schema.writeTo(output, m);
if (output.isLastRepeated())
{
output.writeEndArray();
}
output.writeEndObject(objectStarter);
}
}
catch (IOException e)
{
throw new RuntimeException("Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"writeListTo",
"(",
"LinkedBuffer",
"buffer",
",",
"List",
"<",
"T",
">",
"messages",
",",
"Schema",
"<",
"T",
">",
"schema",
",",
"boolean",
"numeric",
")",
"{",
"if",
"(",
"buffer",
".",
"start",
"!=",
"bu... | Serializes the {@code messages} into the {@link LinkedBuffer} using the given schema. | [
"Serializes",
"the",
"{"
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-msgpack/src/main/java/io/protostuff/MsgpackXIOUtil.java#L137-L176 |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java | ConvertBitmap.bitmapToGray | public static <T extends ImageGray<T>>
T bitmapToGray( Bitmap input , T output , Class<T> imageType , byte[] storage) {
if( imageType == GrayF32.class )
return (T)bitmapToGray(input,(GrayF32)output,storage);
else if( imageType == GrayU8.class )
return (T)bitmapToGray(input,(GrayU8)output,storage);
else
throw new IllegalArgumentException("Unsupported BoofCV Image Type");
} | java | public static <T extends ImageGray<T>>
T bitmapToGray( Bitmap input , T output , Class<T> imageType , byte[] storage) {
if( imageType == GrayF32.class )
return (T)bitmapToGray(input,(GrayF32)output,storage);
else if( imageType == GrayU8.class )
return (T)bitmapToGray(input,(GrayU8)output,storage);
else
throw new IllegalArgumentException("Unsupported BoofCV Image Type");
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
">",
"T",
"bitmapToGray",
"(",
"Bitmap",
"input",
",",
"T",
"output",
",",
"Class",
"<",
"T",
">",
"imageType",
",",
"byte",
"[",
"]",
"storage",
")",
"{",
"if",
"(",
"imageType",
... | Converts Bitmap image into a single band image of arbitrary type.
@see #declareStorage(android.graphics.Bitmap, byte[])
@param input Input Bitmap image.
@param output Output single band image. If null a new one will be declared.
@param imageType Type of single band image.
@param storage Byte array used for internal storage. If null it will be declared internally.
@return The converted gray scale image. | [
"Converts",
"Bitmap",
"image",
"into",
"a",
"single",
"band",
"image",
"of",
"arbitrary",
"type",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java#L98-L107 |
vlingo/vlingo-actors | src/main/java/io/vlingo/actors/Stage.java | Stage.actorFor | public Protocols actorFor(final Class<?>[] protocols, final Definition definition) {
final ActorProtocolActor<Object>[] all =
actorProtocolFor(
protocols,
definition,
definition.parentOr(world.defaultParent()),
definition.supervisor(),
definition.loggerOr(world.defaultLogger()));
return new Protocols(ActorProtocolActor.toActors(all));
} | java | public Protocols actorFor(final Class<?>[] protocols, final Definition definition) {
final ActorProtocolActor<Object>[] all =
actorProtocolFor(
protocols,
definition,
definition.parentOr(world.defaultParent()),
definition.supervisor(),
definition.loggerOr(world.defaultLogger()));
return new Protocols(ActorProtocolActor.toActors(all));
} | [
"public",
"Protocols",
"actorFor",
"(",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"protocols",
",",
"final",
"Definition",
"definition",
")",
"{",
"final",
"ActorProtocolActor",
"<",
"Object",
">",
"[",
"]",
"all",
"=",
"actorProtocolFor",
"(",
"protocols",... | Answers a {@code Protocols} that provides one or more supported {@code protocols} for the
newly created {@code Actor} according to {@code definition}.
@param protocols the {@code Class<?>}[] array of protocols that the {@code Actor} supports
@param definition the {@code Definition} providing parameters to the {@code Actor}
@return Protocols | [
"Answers",
"a",
"{"
] | train | https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/Stage.java#L145-L155 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/account/PreferenceInputFactory.java | PreferenceInputFactory.createSingleTextPreference | public static Preference createSingleTextPreference(String name, String label) {
return createSingleTextPreference(
name, "attribute.displayName." + name, TextDisplay.TEXT, null);
} | java | public static Preference createSingleTextPreference(String name, String label) {
return createSingleTextPreference(
name, "attribute.displayName." + name, TextDisplay.TEXT, null);
} | [
"public",
"static",
"Preference",
"createSingleTextPreference",
"(",
"String",
"name",
",",
"String",
"label",
")",
"{",
"return",
"createSingleTextPreference",
"(",
"name",
",",
"\"attribute.displayName.\"",
"+",
"name",
",",
"TextDisplay",
".",
"TEXT",
",",
"null"... | Define a single-valued text input preferences. This method is a convenient wrapper for the
most common expected use case and assumes null values for the default value and a predictable
label.
@param name
@param label
@return | [
"Define",
"a",
"single",
"-",
"valued",
"text",
"input",
"preferences",
".",
"This",
"method",
"is",
"a",
"convenient",
"wrapper",
"for",
"the",
"most",
"common",
"expected",
"use",
"case",
"and",
"assumes",
"null",
"values",
"for",
"the",
"default",
"value"... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/account/PreferenceInputFactory.java#L45-L48 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/ExpressionValue.java | ExpressionValue.voltMutateToBigintType | public static boolean voltMutateToBigintType(Expression maybeConstantNode, Expression parent, int childIndex) {
if (maybeConstantNode.opType == OpTypes.VALUE
&& maybeConstantNode.dataType != null
&& maybeConstantNode.dataType.isBinaryType()) {
ExpressionValue exprVal = (ExpressionValue)maybeConstantNode;
if (exprVal.valueData == null) {
return false;
}
BinaryData data = (BinaryData)exprVal.valueData;
parent.nodes[childIndex] = new ExpressionValue(data.toLong(), Type.SQL_BIGINT);
return true;
}
return false;
} | java | public static boolean voltMutateToBigintType(Expression maybeConstantNode, Expression parent, int childIndex) {
if (maybeConstantNode.opType == OpTypes.VALUE
&& maybeConstantNode.dataType != null
&& maybeConstantNode.dataType.isBinaryType()) {
ExpressionValue exprVal = (ExpressionValue)maybeConstantNode;
if (exprVal.valueData == null) {
return false;
}
BinaryData data = (BinaryData)exprVal.valueData;
parent.nodes[childIndex] = new ExpressionValue(data.toLong(), Type.SQL_BIGINT);
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"voltMutateToBigintType",
"(",
"Expression",
"maybeConstantNode",
",",
"Expression",
"parent",
",",
"int",
"childIndex",
")",
"{",
"if",
"(",
"maybeConstantNode",
".",
"opType",
"==",
"OpTypes",
".",
"VALUE",
"&&",
"maybeConstantNode",... | Given a ExpressionValue that is a VARBINARY constant,
convert it to a BIGINT constant. Returns true for a
successful conversion and false otherwise.
For more details on how the conversion is performed, see BinaryData.toLong().
@param parent Reference of parent expression
@param childIndex Index of this node in parent
@return true for a successful conversion and false otherwise. | [
"Given",
"a",
"ExpressionValue",
"that",
"is",
"a",
"VARBINARY",
"constant",
"convert",
"it",
"to",
"a",
"BIGINT",
"constant",
".",
"Returns",
"true",
"for",
"a",
"successful",
"conversion",
"and",
"false",
"otherwise",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/ExpressionValue.java#L116-L131 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/transform/TypeAdapterAwareSQLTransform.java | TypeAdapterAwareSQLTransform.generateWriteParam2ContentValues | @Override
public void generateWriteParam2ContentValues(Builder methodBuilder, SQLiteModelMethod method, String paramName, TypeName paramTypeName, ModelProperty property) {
if (property != null && property.hasTypeAdapter()) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, property.typeAdapter.getAdapterTypeName(), paramName);
} else if (method.hasAdapterForParam(paramName)) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, method.getAdapterForParam(paramName), paramName);
} else {
methodBuilder.addCode(WRITE_COSTANT + "$L", paramName);
}
} | java | @Override
public void generateWriteParam2ContentValues(Builder methodBuilder, SQLiteModelMethod method, String paramName, TypeName paramTypeName, ModelProperty property) {
if (property != null && property.hasTypeAdapter()) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, property.typeAdapter.getAdapterTypeName(), paramName);
} else if (method.hasAdapterForParam(paramName)) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, method.getAdapterForParam(paramName), paramName);
} else {
methodBuilder.addCode(WRITE_COSTANT + "$L", paramName);
}
} | [
"@",
"Override",
"public",
"void",
"generateWriteParam2ContentValues",
"(",
"Builder",
"methodBuilder",
",",
"SQLiteModelMethod",
"method",
",",
"String",
"paramName",
",",
"TypeName",
"paramTypeName",
",",
"ModelProperty",
"property",
")",
"{",
"if",
"(",
"property",... | /* (non-Javadoc)
@see com.abubusoft.kripton.processor.sqlite.transform.AbstractSQLTransform#generateWriteParam2ContentValues(com.squareup.javapoet.MethodSpec.Builder, com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod, java.lang.String, com.squareup.javapoet.TypeName, com.abubusoft.kripton.processor.core.ModelProperty) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/transform/TypeAdapterAwareSQLTransform.java#L29-L38 |
tvesalainen/util | security/src/main/java/org/vesalainen/net/ssl/SSLSocketChannel.java | SSLSocketChannel.open | public static SSLSocketChannel open(String peer, int port, SSLContext sslContext) throws IOException
{
SSLEngine engine = sslContext.createSSLEngine(peer, port);
engine.setUseClientMode(true);
SSLParameters sslParameters = engine.getSSLParameters();
SNIServerName hostName = new SNIHostName(peer);
List<SNIServerName> list = new ArrayList<>();
list.add(hostName);
sslParameters.setServerNames(list);
engine.setSSLParameters(sslParameters);
InetSocketAddress address = new InetSocketAddress(peer, port);
SocketChannel socketChannel = SocketChannel.open(address);
SSLSocketChannel sslSocketChannel = new SSLSocketChannel(socketChannel, engine, null, false);
return sslSocketChannel;
} | java | public static SSLSocketChannel open(String peer, int port, SSLContext sslContext) throws IOException
{
SSLEngine engine = sslContext.createSSLEngine(peer, port);
engine.setUseClientMode(true);
SSLParameters sslParameters = engine.getSSLParameters();
SNIServerName hostName = new SNIHostName(peer);
List<SNIServerName> list = new ArrayList<>();
list.add(hostName);
sslParameters.setServerNames(list);
engine.setSSLParameters(sslParameters);
InetSocketAddress address = new InetSocketAddress(peer, port);
SocketChannel socketChannel = SocketChannel.open(address);
SSLSocketChannel sslSocketChannel = new SSLSocketChannel(socketChannel, engine, null, false);
return sslSocketChannel;
} | [
"public",
"static",
"SSLSocketChannel",
"open",
"(",
"String",
"peer",
",",
"int",
"port",
",",
"SSLContext",
"sslContext",
")",
"throws",
"IOException",
"{",
"SSLEngine",
"engine",
"=",
"sslContext",
".",
"createSSLEngine",
"(",
"peer",
",",
"port",
")",
";",... | Creates connection to a named peer using given SSLContext. Connection
is in client mode but can be changed before read/write.
@param peer
@param port
@param sslContext
@return
@throws IOException | [
"Creates",
"connection",
"to",
"a",
"named",
"peer",
"using",
"given",
"SSLContext",
".",
"Connection",
"is",
"in",
"client",
"mode",
"but",
"can",
"be",
"changed",
"before",
"read",
"/",
"write",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/security/src/main/java/org/vesalainen/net/ssl/SSLSocketChannel.java#L81-L95 |
fcrepo4/fcrepo4 | fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/NodeServiceImpl.java | NodeServiceImpl.find | @Override
public FedoraResource find(final FedoraSession session, final String path) {
final Session jcrSession = getJcrSession(session);
try {
return new FedoraResourceImpl(jcrSession.getNode(path));
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
} | java | @Override
public FedoraResource find(final FedoraSession session, final String path) {
final Session jcrSession = getJcrSession(session);
try {
return new FedoraResourceImpl(jcrSession.getNode(path));
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
} | [
"@",
"Override",
"public",
"FedoraResource",
"find",
"(",
"final",
"FedoraSession",
"session",
",",
"final",
"String",
"path",
")",
"{",
"final",
"Session",
"jcrSession",
"=",
"getJcrSession",
"(",
"session",
")",
";",
"try",
"{",
"return",
"new",
"FedoraResou... | Retrieve an existing Fedora resource at the given path
@param session a JCR session
@param path a JCR path
@return Fedora resource at the given path | [
"Retrieve",
"an",
"existing",
"Fedora",
"resource",
"at",
"the",
"given",
"path"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/NodeServiceImpl.java#L75-L83 |
phax/ph-commons | ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java | XPathHelper.createNewXPathExpression | @Nonnull
public static XPathExpression createNewXPathExpression (@Nonnull final XPath aXPath,
@Nonnull @Nonempty final String sXPath)
{
ValueEnforcer.notNull (aXPath, "XPath");
ValueEnforcer.notNull (sXPath, "XPathExpression");
try
{
return aXPath.compile (sXPath);
}
catch (final XPathExpressionException ex)
{
throw new IllegalArgumentException ("Failed to compile XPath expression '" + sXPath + "'", ex);
}
} | java | @Nonnull
public static XPathExpression createNewXPathExpression (@Nonnull final XPath aXPath,
@Nonnull @Nonempty final String sXPath)
{
ValueEnforcer.notNull (aXPath, "XPath");
ValueEnforcer.notNull (sXPath, "XPathExpression");
try
{
return aXPath.compile (sXPath);
}
catch (final XPathExpressionException ex)
{
throw new IllegalArgumentException ("Failed to compile XPath expression '" + sXPath + "'", ex);
}
} | [
"@",
"Nonnull",
"public",
"static",
"XPathExpression",
"createNewXPathExpression",
"(",
"@",
"Nonnull",
"final",
"XPath",
"aXPath",
",",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sXPath",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aXPath",
",",
... | Create a new XPath expression for evaluation.
@param aXPath
The pre-created XPath object. May not be <code>null</code>.
@param sXPath
The main XPath string to be evaluated
@return The {@link XPathExpression} object to be used.
@throws IllegalArgumentException
if the XPath cannot be compiled | [
"Create",
"a",
"new",
"XPath",
"expression",
"for",
"evaluation",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java#L414-L429 |
jhy/jsoup | src/main/java/org/jsoup/safety/Whitelist.java | Whitelist.isSafeAttribute | protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
TagName tag = TagName.valueOf(tagName);
AttributeKey key = AttributeKey.valueOf(attr.getKey());
Set<AttributeKey> okSet = attributes.get(tag);
if (okSet != null && okSet.contains(key)) {
if (protocols.containsKey(tag)) {
Map<AttributeKey, Set<Protocol>> attrProts = protocols.get(tag);
// ok if not defined protocol; otherwise test
return !attrProts.containsKey(key) || testValidProtocol(el, attr, attrProts.get(key));
} else { // attribute found, no protocols defined, so OK
return true;
}
}
// might be an enforced attribute?
Map<AttributeKey, AttributeValue> enforcedSet = enforcedAttributes.get(tag);
if (enforcedSet != null) {
Attributes expect = getEnforcedAttributes(tagName);
String attrKey = attr.getKey();
if (expect.hasKeyIgnoreCase(attrKey)) {
return expect.getIgnoreCase(attrKey).equals(attr.getValue());
}
}
// no attributes defined for tag, try :all tag
return !tagName.equals(":all") && isSafeAttribute(":all", el, attr);
} | java | protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
TagName tag = TagName.valueOf(tagName);
AttributeKey key = AttributeKey.valueOf(attr.getKey());
Set<AttributeKey> okSet = attributes.get(tag);
if (okSet != null && okSet.contains(key)) {
if (protocols.containsKey(tag)) {
Map<AttributeKey, Set<Protocol>> attrProts = protocols.get(tag);
// ok if not defined protocol; otherwise test
return !attrProts.containsKey(key) || testValidProtocol(el, attr, attrProts.get(key));
} else { // attribute found, no protocols defined, so OK
return true;
}
}
// might be an enforced attribute?
Map<AttributeKey, AttributeValue> enforcedSet = enforcedAttributes.get(tag);
if (enforcedSet != null) {
Attributes expect = getEnforcedAttributes(tagName);
String attrKey = attr.getKey();
if (expect.hasKeyIgnoreCase(attrKey)) {
return expect.getIgnoreCase(attrKey).equals(attr.getValue());
}
}
// no attributes defined for tag, try :all tag
return !tagName.equals(":all") && isSafeAttribute(":all", el, attr);
} | [
"protected",
"boolean",
"isSafeAttribute",
"(",
"String",
"tagName",
",",
"Element",
"el",
",",
"Attribute",
"attr",
")",
"{",
"TagName",
"tag",
"=",
"TagName",
".",
"valueOf",
"(",
"tagName",
")",
";",
"AttributeKey",
"key",
"=",
"AttributeKey",
".",
"value... | Test if the supplied attribute is allowed by this whitelist for this tag
@param tagName tag to consider allowing the attribute in
@param el element under test, to confirm protocol
@param attr attribute under test
@return true if allowed | [
"Test",
"if",
"the",
"supplied",
"attribute",
"is",
"allowed",
"by",
"this",
"whitelist",
"for",
"this",
"tag"
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/safety/Whitelist.java#L496-L521 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java | FatStringUtils.extractRegexGroup | public static String extractRegexGroup(String fromContent, String regex) throws Exception {
return extractRegexGroup(fromContent, regex, 1);
} | java | public static String extractRegexGroup(String fromContent, String regex) throws Exception {
return extractRegexGroup(fromContent, regex, 1);
} | [
"public",
"static",
"String",
"extractRegexGroup",
"(",
"String",
"fromContent",
",",
"String",
"regex",
")",
"throws",
"Exception",
"{",
"return",
"extractRegexGroup",
"(",
"fromContent",
",",
"regex",
",",
"1",
")",
";",
"}"
] | Extracts the first matching group in the provided content, if the regex includes at least one group. An exception is
thrown if the regex does not include a group, or if a matching group cannot be found in the content. | [
"Extracts",
"the",
"first",
"matching",
"group",
"in",
"the",
"provided",
"content",
"if",
"the",
"regex",
"includes",
"at",
"least",
"one",
"group",
".",
"An",
"exception",
"is",
"thrown",
"if",
"the",
"regex",
"does",
"not",
"include",
"a",
"group",
"or"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java#L22-L24 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java | MultiViewOps.decomposeMetricCamera | public static void decomposeMetricCamera(DMatrixRMaj cameraMatrix, DMatrixRMaj K, Se3_F64 worldToView) {
DMatrixRMaj A = new DMatrixRMaj(3,3);
CommonOps_DDRM.extract(cameraMatrix, 0, 3, 0, 3, A, 0, 0);
worldToView.T.set(cameraMatrix.get(0,3),cameraMatrix.get(1,3),cameraMatrix.get(2,3));
QRDecomposition<DMatrixRMaj> qr = DecompositionFactory_DDRM.qr(3, 3);
// Need to do an RQ decomposition, but we only have QR
// by permuting the rows in KR we can get the desired result
DMatrixRMaj Pv = SpecializedOps_DDRM.pivotMatrix(null,new int[]{2,1,0},3,false);
DMatrixRMaj A_p = new DMatrixRMaj(3,3);
CommonOps_DDRM.mult(Pv,A,A_p);
CommonOps_DDRM.transpose(A_p);
if( !qr.decompose(A_p) )
throw new RuntimeException("QR decomposition failed! Bad input?");
// extract the rotation
qr.getQ(A,false);
CommonOps_DDRM.multTransB(Pv,A,worldToView.R);
// extract the calibration matrix
qr.getR(K,false);
CommonOps_DDRM.multTransB(Pv,K,A);
CommonOps_DDRM.mult(A,Pv,K);
// there are four solutions, massage it so that it's the correct one.
// each of these row/column negations produces the same camera matrix
for (int i = 0; i < 3; i++) {
if( K.get(i,i) < 0) {
CommonOps_DDRM.scaleCol(-1,K,i);
CommonOps_DDRM.scaleRow(-1,worldToView.R,i);
}
}
// rotation matrices have det() == 1
if( CommonOps_DDRM.det(worldToView.R) < 0 ) {
CommonOps_DDRM.scale(-1,worldToView.R);
worldToView.T.scale(-1);
}
// make sure it's a proper camera matrix
CommonOps_DDRM.divide(K,K.get(2,2));
// could do a very fast triangule inverse. EJML doesn't have one for upper triangle, yet.
if( !CommonOps_DDRM.invert(K,A) )
throw new RuntimeException("Inverse failed! Bad input?");
GeometryMath_F64.mult(A, worldToView.T, worldToView.T);
} | java | public static void decomposeMetricCamera(DMatrixRMaj cameraMatrix, DMatrixRMaj K, Se3_F64 worldToView) {
DMatrixRMaj A = new DMatrixRMaj(3,3);
CommonOps_DDRM.extract(cameraMatrix, 0, 3, 0, 3, A, 0, 0);
worldToView.T.set(cameraMatrix.get(0,3),cameraMatrix.get(1,3),cameraMatrix.get(2,3));
QRDecomposition<DMatrixRMaj> qr = DecompositionFactory_DDRM.qr(3, 3);
// Need to do an RQ decomposition, but we only have QR
// by permuting the rows in KR we can get the desired result
DMatrixRMaj Pv = SpecializedOps_DDRM.pivotMatrix(null,new int[]{2,1,0},3,false);
DMatrixRMaj A_p = new DMatrixRMaj(3,3);
CommonOps_DDRM.mult(Pv,A,A_p);
CommonOps_DDRM.transpose(A_p);
if( !qr.decompose(A_p) )
throw new RuntimeException("QR decomposition failed! Bad input?");
// extract the rotation
qr.getQ(A,false);
CommonOps_DDRM.multTransB(Pv,A,worldToView.R);
// extract the calibration matrix
qr.getR(K,false);
CommonOps_DDRM.multTransB(Pv,K,A);
CommonOps_DDRM.mult(A,Pv,K);
// there are four solutions, massage it so that it's the correct one.
// each of these row/column negations produces the same camera matrix
for (int i = 0; i < 3; i++) {
if( K.get(i,i) < 0) {
CommonOps_DDRM.scaleCol(-1,K,i);
CommonOps_DDRM.scaleRow(-1,worldToView.R,i);
}
}
// rotation matrices have det() == 1
if( CommonOps_DDRM.det(worldToView.R) < 0 ) {
CommonOps_DDRM.scale(-1,worldToView.R);
worldToView.T.scale(-1);
}
// make sure it's a proper camera matrix
CommonOps_DDRM.divide(K,K.get(2,2));
// could do a very fast triangule inverse. EJML doesn't have one for upper triangle, yet.
if( !CommonOps_DDRM.invert(K,A) )
throw new RuntimeException("Inverse failed! Bad input?");
GeometryMath_F64.mult(A, worldToView.T, worldToView.T);
} | [
"public",
"static",
"void",
"decomposeMetricCamera",
"(",
"DMatrixRMaj",
"cameraMatrix",
",",
"DMatrixRMaj",
"K",
",",
"Se3_F64",
"worldToView",
")",
"{",
"DMatrixRMaj",
"A",
"=",
"new",
"DMatrixRMaj",
"(",
"3",
",",
"3",
")",
";",
"CommonOps_DDRM",
".",
"extr... | <p>
Decomposes a metric camera matrix P=K*[R|T], where A is an upper triangular camera calibration
matrix, R is a rotation matrix, and T is a translation vector.
<ul>
<li> NOTE: There are multiple valid solutions to this problem and only one solution is returned.
<li> NOTE: The camera center will be on the plane at infinity.
</ul>
</p>
@param cameraMatrix Input: Camera matrix, 3 by 4
@param K Output: Camera calibration matrix, 3 by 3.
@param worldToView Output: The rotation and translation. | [
"<p",
">",
"Decomposes",
"a",
"metric",
"camera",
"matrix",
"P",
"=",
"K",
"*",
"[",
"R|T",
"]",
"where",
"A",
"is",
"an",
"upper",
"triangular",
"camera",
"calibration",
"matrix",
"R",
"is",
"a",
"rotation",
"matrix",
"and",
"T",
"is",
"a",
"translati... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L1073-L1121 |
GoogleCloudPlatform/bigdata-interop | bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/FederatedBigQueryOutputFormat.java | FederatedBigQueryOutputFormat.createCommitter | @Override
public OutputCommitter createCommitter(TaskAttemptContext context) throws IOException {
Configuration conf = context.getConfiguration();
OutputCommitter delegateCommitter = getDelegate(conf).getOutputCommitter(context);
OutputCommitter committer = new FederatedBigQueryOutputCommitter(context, delegateCommitter);
return committer;
} | java | @Override
public OutputCommitter createCommitter(TaskAttemptContext context) throws IOException {
Configuration conf = context.getConfiguration();
OutputCommitter delegateCommitter = getDelegate(conf).getOutputCommitter(context);
OutputCommitter committer = new FederatedBigQueryOutputCommitter(context, delegateCommitter);
return committer;
} | [
"@",
"Override",
"public",
"OutputCommitter",
"createCommitter",
"(",
"TaskAttemptContext",
"context",
")",
"throws",
"IOException",
"{",
"Configuration",
"conf",
"=",
"context",
".",
"getConfiguration",
"(",
")",
";",
"OutputCommitter",
"delegateCommitter",
"=",
"get... | Wraps the delegate's committer in a {@link FederatedBigQueryOutputCommitter}. | [
"Wraps",
"the",
"delegate",
"s",
"committer",
"in",
"a",
"{"
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/FederatedBigQueryOutputFormat.java#L31-L37 |
apache/reef | lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/StorageKeyCloudBlobProvider.java | StorageKeyCloudBlobProvider.getCloudBlobClient | @Override
public CloudBlobClient getCloudBlobClient() throws IOException {
String connectionString = String.format(AZURE_STORAGE_CONNECTION_STRING_FORMAT,
this.azureStorageAccountName, this.azureStorageAccountKey);
try {
return CloudStorageAccount.parse(connectionString).createCloudBlobClient();
} catch (URISyntaxException | InvalidKeyException e) {
throw new IOException("Failed to create a Cloud Storage Account.", e);
}
} | java | @Override
public CloudBlobClient getCloudBlobClient() throws IOException {
String connectionString = String.format(AZURE_STORAGE_CONNECTION_STRING_FORMAT,
this.azureStorageAccountName, this.azureStorageAccountKey);
try {
return CloudStorageAccount.parse(connectionString).createCloudBlobClient();
} catch (URISyntaxException | InvalidKeyException e) {
throw new IOException("Failed to create a Cloud Storage Account.", e);
}
} | [
"@",
"Override",
"public",
"CloudBlobClient",
"getCloudBlobClient",
"(",
")",
"throws",
"IOException",
"{",
"String",
"connectionString",
"=",
"String",
".",
"format",
"(",
"AZURE_STORAGE_CONNECTION_STRING_FORMAT",
",",
"this",
".",
"azureStorageAccountName",
",",
"this... | Returns an instance of {@link CloudBlobClient} based on available authentication mechanism.
@return an instance of {@link CloudBlobClient}.
@throws IOException | [
"Returns",
"an",
"instance",
"of",
"{"
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/StorageKeyCloudBlobProvider.java#L62-L71 |
kiegroup/drools | drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseFactory.java | KnowledgeBaseFactory.newKnowledgeBase | public static InternalKnowledgeBase newKnowledgeBase(String kbaseId,
KieBaseConfiguration conf) {
return new KnowledgeBaseImpl( kbaseId, (RuleBaseConfiguration) conf);
} | java | public static InternalKnowledgeBase newKnowledgeBase(String kbaseId,
KieBaseConfiguration conf) {
return new KnowledgeBaseImpl( kbaseId, (RuleBaseConfiguration) conf);
} | [
"public",
"static",
"InternalKnowledgeBase",
"newKnowledgeBase",
"(",
"String",
"kbaseId",
",",
"KieBaseConfiguration",
"conf",
")",
"{",
"return",
"new",
"KnowledgeBaseImpl",
"(",
"kbaseId",
",",
"(",
"RuleBaseConfiguration",
")",
"conf",
")",
";",
"}"
] | Create a new KnowledgeBase using the given KnowledgeBaseConfiguration and
the given KnowledgeBase ID.
@param kbaseId
A string Identifier for the knowledge base. Specially useful when enabling
JMX monitoring and management, as that ID will be used to compose the
JMX ObjectName for all related MBeans. The application must ensure all kbase
IDs are unique.
@return
The KnowledgeBase | [
"Create",
"a",
"new",
"KnowledgeBase",
"using",
"the",
"given",
"KnowledgeBaseConfiguration",
"and",
"the",
"given",
"KnowledgeBase",
"ID",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseFactory.java#L104-L107 |
hdbeukel/james-extensions | src/main/java/org/jamesframework/ext/analysis/AnalysisResults.java | AnalysisResults.writeJSON | public void writeJSON(String filePath, JsonConverter<SolutionType> solutionJsonConverter) throws IOException{
/**************************************************/
/* STEP 1: Convert results to JSON representation */
/**************************************************/
Json resultsJson = Json.object();
// register problems
results.forEach((problemID, searches) -> {
Json problemJson = Json.object();
searches.forEach((searchID, runs) -> {
Json searchJson = Json.array();
// register search runs
runs.forEach(run -> {
Json runJson = Json.object();
// register update times and values
Json times = Json.array(run.getTimes().toArray());
Json values = Json.array(run.getValues().toArray());
runJson.set("times", times);
runJson.set("values", values);
// register best found solution, if a JSON converter is given
if(solutionJsonConverter != null){
runJson.set("best.solution", solutionJsonConverter.toJson(run.getBestSolution()));
}
searchJson.add(runJson);
});
problemJson.set(searchID, searchJson);
});
resultsJson.set(problemID, problemJson);
});
/*************************************/
/* STEP 2: Write JSON string to file */
/*************************************/
Files.write(Paths.get(filePath), Collections.singleton(resultsJson.toString()));
} | java | public void writeJSON(String filePath, JsonConverter<SolutionType> solutionJsonConverter) throws IOException{
/**************************************************/
/* STEP 1: Convert results to JSON representation */
/**************************************************/
Json resultsJson = Json.object();
// register problems
results.forEach((problemID, searches) -> {
Json problemJson = Json.object();
searches.forEach((searchID, runs) -> {
Json searchJson = Json.array();
// register search runs
runs.forEach(run -> {
Json runJson = Json.object();
// register update times and values
Json times = Json.array(run.getTimes().toArray());
Json values = Json.array(run.getValues().toArray());
runJson.set("times", times);
runJson.set("values", values);
// register best found solution, if a JSON converter is given
if(solutionJsonConverter != null){
runJson.set("best.solution", solutionJsonConverter.toJson(run.getBestSolution()));
}
searchJson.add(runJson);
});
problemJson.set(searchID, searchJson);
});
resultsJson.set(problemID, problemJson);
});
/*************************************/
/* STEP 2: Write JSON string to file */
/*************************************/
Files.write(Paths.get(filePath), Collections.singleton(resultsJson.toString()));
} | [
"public",
"void",
"writeJSON",
"(",
"String",
"filePath",
",",
"JsonConverter",
"<",
"SolutionType",
">",
"solutionJsonConverter",
")",
"throws",
"IOException",
"{",
"/**************************************************/",
"/* STEP 1: Convert results to JSON representation */",
"/... | Write the results to a JSON file that can be loaded into R to be inspected and visualized using
the james-analysis R package. If the specified file already exists, it is overwritten. This method
stores the evaluation values, the update times and the actual best found solution for each search
run. The solutions are converted to a JSON representation using the given converter. If the latter
is <code>null</code>, the actual solutions are not stored in the output file.
@param filePath path of the file to which the JSON output is written
@param solutionJsonConverter converts solutions to a JSON representation
@throws IOException if an I/O error occurs when writing to the file | [
"Write",
"the",
"results",
"to",
"a",
"JSON",
"file",
"that",
"can",
"be",
"loaded",
"into",
"R",
"to",
"be",
"inspected",
"and",
"visualized",
"using",
"the",
"james",
"-",
"analysis",
"R",
"package",
".",
"If",
"the",
"specified",
"file",
"already",
"e... | train | https://github.com/hdbeukel/james-extensions/blob/37a43aa6ac4d67575cabc7aed25fd96c91d4c7b2/src/main/java/org/jamesframework/ext/analysis/AnalysisResults.java#L201-L252 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.1/src/com/ibm/ws/microprofile/config/converters/UserConverter.java | UserConverter.newInstance | @Trivial
public static <K> UserConverter<K> newInstance(Type type, Converter<K> converter) {
return newInstance(type, getPriority(converter), converter);
} | java | @Trivial
public static <K> UserConverter<K> newInstance(Type type, Converter<K> converter) {
return newInstance(type, getPriority(converter), converter);
} | [
"@",
"Trivial",
"public",
"static",
"<",
"K",
">",
"UserConverter",
"<",
"K",
">",
"newInstance",
"(",
"Type",
"type",
",",
"Converter",
"<",
"K",
">",
"converter",
")",
"{",
"return",
"newInstance",
"(",
"type",
",",
"getPriority",
"(",
"converter",
")"... | Construct a new PriorityConverter using discovered or default priority
@param converter | [
"Construct",
"a",
"new",
"PriorityConverter",
"using",
"discovered",
"or",
"default",
"priority"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.1/src/com/ibm/ws/microprofile/config/converters/UserConverter.java#L50-L53 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/predicate/FullText.java | FullText.fullTextMatch | public static P<String> fullTextMatch(String configuration,final String value){
return fullTextMatch(configuration,false, value);
} | java | public static P<String> fullTextMatch(String configuration,final String value){
return fullTextMatch(configuration,false, value);
} | [
"public",
"static",
"P",
"<",
"String",
">",
"fullTextMatch",
"(",
"String",
"configuration",
",",
"final",
"String",
"value",
")",
"{",
"return",
"fullTextMatch",
"(",
"configuration",
",",
"false",
",",
"value",
")",
";",
"}"
] | Build full text matching predicate (use in has(column,...))
@param configuration the full text configuration to use
@param value the value to search for
@return the predicate | [
"Build",
"full",
"text",
"matching",
"predicate",
"(",
"use",
"in",
"has",
"(",
"column",
"...",
"))"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/predicate/FullText.java#L42-L44 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/Document.java | Document.putExistingRevision | @InterfaceAudience.Public
public boolean putExistingRevision(Map<String, Object> properties,
Map<String, Object> attachments,
List<String> revIDs,
URL sourceURL)
throws CouchbaseLiteException {
assert (revIDs != null && revIDs.size() > 0);
boolean deleted = false;
if (properties != null)
deleted = properties.get("_deleted") != null &&
((Boolean) properties.get("_deleted")).booleanValue();
RevisionInternal rev = new RevisionInternal(documentId, revIDs.get(0), deleted);
rev.setProperties(propertiesToInsert(properties));
Status status = new Status();
if (!database.registerAttachmentBodies(attachments, rev, status))
return false;
database.forceInsert(rev, revIDs, sourceURL);
return true;
} | java | @InterfaceAudience.Public
public boolean putExistingRevision(Map<String, Object> properties,
Map<String, Object> attachments,
List<String> revIDs,
URL sourceURL)
throws CouchbaseLiteException {
assert (revIDs != null && revIDs.size() > 0);
boolean deleted = false;
if (properties != null)
deleted = properties.get("_deleted") != null &&
((Boolean) properties.get("_deleted")).booleanValue();
RevisionInternal rev = new RevisionInternal(documentId, revIDs.get(0), deleted);
rev.setProperties(propertiesToInsert(properties));
Status status = new Status();
if (!database.registerAttachmentBodies(attachments, rev, status))
return false;
database.forceInsert(rev, revIDs, sourceURL);
return true;
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"boolean",
"putExistingRevision",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"attachments",
",",
"List",
"<",
"String",
">",
"revIDs",
",",
... | Adds an existing revision copied from another database. Unlike a normal insertion, this does
not assign a new revision ID; instead the revision's ID must be given. The revision's history
(ancestry) must be given, which can put it anywhere in the revision tree. It's not an error if
the revision already exists locally; it will just be ignored.
This is not an operation that clients normally perform; it's used by the replicator.
You might want to use it if you're pre-loading a database with canned content, or if you're
implementing some new kind of replicator that transfers revisions from another database.
@param properties The properties of the revision (_id and _rev will be ignored, but _deleted
and _attachments are recognized.)
@param attachments A dictionary providing attachment bodies. The keys are the attachment
names (matching the keys in the properties' `_attachments` dictionary) and
the values are the attachment bodies as NSData or NSURL.
@param revIDs The revision history in the form of an array of revision-ID strings, in
reverse chronological order. The first item must be the new revision's ID.
Following items are its parent's ID, etc.
@param sourceURL The URL of the database this revision came from, if any. (This value shows
up in the CBLDatabaseChange triggered by this insertion, and can help clients
decide whether the change is local or not.)
@return true on success, false on failure.
@throws CouchbaseLiteException Error information will be thrown if the insertion fails. | [
"Adds",
"an",
"existing",
"revision",
"copied",
"from",
"another",
"database",
".",
"Unlike",
"a",
"normal",
"insertion",
"this",
"does",
"not",
"assign",
"a",
"new",
"revision",
"ID",
";",
"instead",
"the",
"revision",
"s",
"ID",
"must",
"be",
"given",
".... | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L417-L437 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.checkIfParameterTypesAreSame | public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
} | java | public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
} | [
"public",
"static",
"boolean",
"checkIfParameterTypesAreSame",
"(",
"boolean",
"isVarArgs",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"expectedParameterTypes",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"actualParameterTypes",
")",
"{",
"return",
"new",
"ParameterTypes... | Check if parameter types are same.
@param isVarArgs Whether or not the method or constructor contains var args.
@param expectedParameterTypes the expected parameter types
@param actualParameterTypes the actual parameter types
@return if all actual parameter types are assignable from the expected
parameter types, otherwise. | [
"Check",
"if",
"parameter",
"types",
"are",
"same",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2242-L2245 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.getPermissions | public CmsPermissionSetCustom getPermissions(CmsDbContext dbc, CmsResource resource, CmsUser user)
throws CmsException {
CmsAccessControlList acList = getAccessControlList(dbc, resource, false);
return acList.getPermissions(user, getGroupsOfUser(dbc, user.getName(), false), getRolesForUser(dbc, user));
} | java | public CmsPermissionSetCustom getPermissions(CmsDbContext dbc, CmsResource resource, CmsUser user)
throws CmsException {
CmsAccessControlList acList = getAccessControlList(dbc, resource, false);
return acList.getPermissions(user, getGroupsOfUser(dbc, user.getName(), false), getRolesForUser(dbc, user));
} | [
"public",
"CmsPermissionSetCustom",
"getPermissions",
"(",
"CmsDbContext",
"dbc",
",",
"CmsResource",
"resource",
",",
"CmsUser",
"user",
")",
"throws",
"CmsException",
"{",
"CmsAccessControlList",
"acList",
"=",
"getAccessControlList",
"(",
"dbc",
",",
"resource",
",... | Returns the set of permissions of the current user for a given resource.<p>
@param dbc the current database context
@param resource the resource
@param user the user
@return bit set with allowed permissions
@throws CmsException if something goes wrong | [
"Returns",
"the",
"set",
"of",
"permissions",
"of",
"the",
"current",
"user",
"for",
"a",
"given",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L4281-L4286 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/gm/model/VarConfig.java | VarConfig.put | public void put(Var var, String stateName) {
int state = var.getState(stateName);
if (state == -1) {
throw new IllegalArgumentException("Unknown state name " + stateName + " for var " + var);
}
put(var, state);
} | java | public void put(Var var, String stateName) {
int state = var.getState(stateName);
if (state == -1) {
throw new IllegalArgumentException("Unknown state name " + stateName + " for var " + var);
}
put(var, state);
} | [
"public",
"void",
"put",
"(",
"Var",
"var",
",",
"String",
"stateName",
")",
"{",
"int",
"state",
"=",
"var",
".",
"getState",
"(",
"stateName",
")",
";",
"if",
"(",
"state",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
... | Sets the state value to stateName for the given variable, adding it if necessary. | [
"Sets",
"the",
"state",
"value",
"to",
"stateName",
"for",
"the",
"given",
"variable",
"adding",
"it",
"if",
"necessary",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/model/VarConfig.java#L82-L88 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java | LOF.computeLOFScore | protected double computeLOFScore(KNNQuery<O> knnq, DBIDRef cur, DoubleDataStore lrds) {
final double lrdp = lrds.doubleValue(cur);
if(Double.isInfinite(lrdp)) {
return 1.0;
}
double sum = 0.;
int count = 0;
final KNNList neighbors = knnq.getKNNForDBID(cur, k);
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(cur, neighbor)) {
continue;
}
sum += lrds.doubleValue(neighbor);
++count;
}
return sum / (lrdp * count);
} | java | protected double computeLOFScore(KNNQuery<O> knnq, DBIDRef cur, DoubleDataStore lrds) {
final double lrdp = lrds.doubleValue(cur);
if(Double.isInfinite(lrdp)) {
return 1.0;
}
double sum = 0.;
int count = 0;
final KNNList neighbors = knnq.getKNNForDBID(cur, k);
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(cur, neighbor)) {
continue;
}
sum += lrds.doubleValue(neighbor);
++count;
}
return sum / (lrdp * count);
} | [
"protected",
"double",
"computeLOFScore",
"(",
"KNNQuery",
"<",
"O",
">",
"knnq",
",",
"DBIDRef",
"cur",
",",
"DoubleDataStore",
"lrds",
")",
"{",
"final",
"double",
"lrdp",
"=",
"lrds",
".",
"doubleValue",
"(",
"cur",
")",
";",
"if",
"(",
"Double",
".",... | Compute a single LOF score.
@param knnq kNN query
@param cur Current object
@param lrds Stored reachability densities
@return LOF score. | [
"Compute",
"a",
"single",
"LOF",
"score",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java#L223-L240 |
softindex/datakernel | core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBuf.java | ByteBuf.drainTo | public int drainTo(@NotNull ByteBuf buf, int length) {
assert !buf.isRecycled();
assert buf.tail + length <= buf.array.length;
drainTo(buf.array, buf.tail, length);
buf.tail += length;
return length;
} | java | public int drainTo(@NotNull ByteBuf buf, int length) {
assert !buf.isRecycled();
assert buf.tail + length <= buf.array.length;
drainTo(buf.array, buf.tail, length);
buf.tail += length;
return length;
} | [
"public",
"int",
"drainTo",
"(",
"@",
"NotNull",
"ByteBuf",
"buf",
",",
"int",
"length",
")",
"{",
"assert",
"!",
"buf",
".",
"isRecycled",
"(",
")",
";",
"assert",
"buf",
".",
"tail",
"+",
"length",
"<=",
"buf",
".",
"array",
".",
"length",
";",
"... | Drains bytes to a given {@code ByteBuf}.
@see #drainTo(byte[], int, int) | [
"Drains",
"bytes",
"to",
"a",
"given",
"{",
"@code",
"ByteBuf",
"}",
"."
] | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBuf.java#L590-L596 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/NativeAppCallAttachmentStore.java | NativeAppCallAttachmentStore.cleanupAttachmentsForCall | public void cleanupAttachmentsForCall(Context context, UUID callId) {
File dir = getAttachmentsDirectoryForCall(callId, false);
Utility.deleteDirectory(dir);
} | java | public void cleanupAttachmentsForCall(Context context, UUID callId) {
File dir = getAttachmentsDirectoryForCall(callId, false);
Utility.deleteDirectory(dir);
} | [
"public",
"void",
"cleanupAttachmentsForCall",
"(",
"Context",
"context",
",",
"UUID",
"callId",
")",
"{",
"File",
"dir",
"=",
"getAttachmentsDirectoryForCall",
"(",
"callId",
",",
"false",
")",
";",
"Utility",
".",
"deleteDirectory",
"(",
"dir",
")",
";",
"}"... | Removes any temporary files associated with a particular native app call.
@param context the Context the call is being made from
@param callId the unique ID of the call | [
"Removes",
"any",
"temporary",
"files",
"associated",
"with",
"a",
"particular",
"native",
"app",
"call",
"."
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/NativeAppCallAttachmentStore.java#L164-L167 |
wuman/orientdb-android | core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java | OMMapManagerNew.mapNew | private OMMapBufferEntry mapNew(final OFileMMap file, final long beginOffset) throws IOException {
return new OMMapBufferEntry(file, file.map(beginOffset, file.getFileSize() - (int) beginOffset), beginOffset,
file.getFileSize() - (int) beginOffset);
} | java | private OMMapBufferEntry mapNew(final OFileMMap file, final long beginOffset) throws IOException {
return new OMMapBufferEntry(file, file.map(beginOffset, file.getFileSize() - (int) beginOffset), beginOffset,
file.getFileSize() - (int) beginOffset);
} | [
"private",
"OMMapBufferEntry",
"mapNew",
"(",
"final",
"OFileMMap",
"file",
",",
"final",
"long",
"beginOffset",
")",
"throws",
"IOException",
"{",
"return",
"new",
"OMMapBufferEntry",
"(",
"file",
",",
"file",
".",
"map",
"(",
"beginOffset",
",",
"file",
".",... | This method maps new part of file if not all file content is mapped.
@param file
that will be mapped.
@param beginOffset
position in file from what mapping should be applied.
@return mapped entry.
@throws IOException
is thrown if mapping is unsuccessfully. | [
"This",
"method",
"maps",
"new",
"part",
"of",
"file",
"if",
"not",
"all",
"file",
"content",
"is",
"mapped",
"."
] | train | https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OMMapManagerNew.java#L328-L331 |
kohsuke/com4j | runtime/src/main/java/com4j/COM4J.java | COM4J.createInstance | public static<T extends Com4jObject>
T createInstance( Class<T> primaryInterface, String clsid ) throws ComException {
// create instance
return createInstance(primaryInterface,clsid,CLSCTX.ALL);
} | java | public static<T extends Com4jObject>
T createInstance( Class<T> primaryInterface, String clsid ) throws ComException {
// create instance
return createInstance(primaryInterface,clsid,CLSCTX.ALL);
} | [
"public",
"static",
"<",
"T",
"extends",
"Com4jObject",
">",
"T",
"createInstance",
"(",
"Class",
"<",
"T",
">",
"primaryInterface",
",",
"String",
"clsid",
")",
"throws",
"ComException",
"{",
"// create instance",
"return",
"createInstance",
"(",
"primaryInterfac... | Creates a new COM object of the given CLSID and returns
it in a wrapped interface.
@param primaryInterface The created COM object is returned as this interface.
Must be non-null. Passing in {@link Com4jObject} allows
the caller to create a new instance without knowing
its primary interface.
@param clsid The CLSID of the COM object in the
"<tt>{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}</tt>" format,
or the ProgID of the object (like "Microsoft.XMLParser.1.0")
@param <T> the type of the return value and the type parameter of the class object of primaryInterface
@return non-null valid object.
@throws ComException if the instantiation fails. | [
"Creates",
"a",
"new",
"COM",
"object",
"of",
"the",
"given",
"CLSID",
"and",
"returns",
"it",
"in",
"a",
"wrapped",
"interface",
"."
] | train | https://github.com/kohsuke/com4j/blob/1e690b805fb0e4e9ef61560e20a56335aecb0b24/runtime/src/main/java/com4j/COM4J.java#L70-L75 |
Netflix/ribbon | ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java | LoadBalancingHttpClient.submitToServerInURI | private Observable<HttpClientResponse<O>> submitToServerInURI(
HttpClientRequest<I> request, IClientConfig requestConfig, ClientConfig config,
RetryHandler errorHandler, ExecutionContext<HttpClientRequest<I>> context) {
// First, determine server from the URI
URI uri;
try {
uri = new URI(request.getUri());
} catch (URISyntaxException e) {
return Observable.error(e);
}
String host = uri.getHost();
if (host == null) {
return null;
}
int port = uri.getPort();
if (port < 0) {
if (Optional.ofNullable(clientConfig.get(IClientConfigKey.Keys.IsSecure)).orElse(false)) {
port = 443;
} else {
port = 80;
}
}
return LoadBalancerCommand.<HttpClientResponse<O>>builder()
.withRetryHandler(errorHandler)
.withLoadBalancerContext(lbContext)
.withListeners(listeners)
.withExecutionContext(context)
.withServer(new Server(host, port))
.build()
.submit(this.requestToOperation(request, getRxClientConfig(requestConfig, config)));
} | java | private Observable<HttpClientResponse<O>> submitToServerInURI(
HttpClientRequest<I> request, IClientConfig requestConfig, ClientConfig config,
RetryHandler errorHandler, ExecutionContext<HttpClientRequest<I>> context) {
// First, determine server from the URI
URI uri;
try {
uri = new URI(request.getUri());
} catch (URISyntaxException e) {
return Observable.error(e);
}
String host = uri.getHost();
if (host == null) {
return null;
}
int port = uri.getPort();
if (port < 0) {
if (Optional.ofNullable(clientConfig.get(IClientConfigKey.Keys.IsSecure)).orElse(false)) {
port = 443;
} else {
port = 80;
}
}
return LoadBalancerCommand.<HttpClientResponse<O>>builder()
.withRetryHandler(errorHandler)
.withLoadBalancerContext(lbContext)
.withListeners(listeners)
.withExecutionContext(context)
.withServer(new Server(host, port))
.build()
.submit(this.requestToOperation(request, getRxClientConfig(requestConfig, config)));
} | [
"private",
"Observable",
"<",
"HttpClientResponse",
"<",
"O",
">",
">",
"submitToServerInURI",
"(",
"HttpClientRequest",
"<",
"I",
">",
"request",
",",
"IClientConfig",
"requestConfig",
",",
"ClientConfig",
"config",
",",
"RetryHandler",
"errorHandler",
",",
"Execut... | Submits the request to the server indicated in the URI
@param request
@param requestConfig
@param config
@param errorHandler
@param context
@return | [
"Submits",
"the",
"request",
"to",
"the",
"server",
"indicated",
"in",
"the",
"URI"
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.java#L443-L474 |
liferay/com-liferay-commerce | commerce-payment-api/src/main/java/com/liferay/commerce/payment/model/CommercePaymentMethodGroupRelWrapper.java | CommercePaymentMethodGroupRelWrapper.getName | @Override
public String getName(String languageId, boolean useDefault) {
return _commercePaymentMethodGroupRel.getName(languageId, useDefault);
} | java | @Override
public String getName(String languageId, boolean useDefault) {
return _commercePaymentMethodGroupRel.getName(languageId, useDefault);
} | [
"@",
"Override",
"public",
"String",
"getName",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_commercePaymentMethodGroupRel",
".",
"getName",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
] | Returns the localized name of this commerce payment method group rel in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized name of this commerce payment method group rel | [
"Returns",
"the",
"localized",
"name",
"of",
"this",
"commerce",
"payment",
"method",
"group",
"rel",
"in",
"the",
"language",
"optionally",
"using",
"the",
"default",
"language",
"if",
"no",
"localization",
"exists",
"for",
"the",
"requested",
"language",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-payment-api/src/main/java/com/liferay/commerce/payment/model/CommercePaymentMethodGroupRelWrapper.java#L403-L406 |
ReactiveX/RxNetty | rxnetty-http/src/main/java/io/reactivex/netty/protocol/http/ws/server/WebSocketHandshaker.java | WebSocketHandshaker.selectSubprotocol | protected static String selectSubprotocol(String requestedSubprotocols, String[] supportedSubProtocols) {
if (requestedSubprotocols == null || supportedSubProtocols.length == 0) {
return null;
}
String[] requestedSubprotocolArray = requestedSubprotocols.split(",");
for (String p: requestedSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol: supportedSubProtocols) {
if (WebSocketServerHandshaker.SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol)
|| requestedSubprotocol.equals(supportedSubprotocol)) {
return requestedSubprotocol;
}
}
}
// No match found
return null;
} | java | protected static String selectSubprotocol(String requestedSubprotocols, String[] supportedSubProtocols) {
if (requestedSubprotocols == null || supportedSubProtocols.length == 0) {
return null;
}
String[] requestedSubprotocolArray = requestedSubprotocols.split(",");
for (String p: requestedSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol: supportedSubProtocols) {
if (WebSocketServerHandshaker.SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol)
|| requestedSubprotocol.equals(supportedSubprotocol)) {
return requestedSubprotocol;
}
}
}
// No match found
return null;
} | [
"protected",
"static",
"String",
"selectSubprotocol",
"(",
"String",
"requestedSubprotocols",
",",
"String",
"[",
"]",
"supportedSubProtocols",
")",
"{",
"if",
"(",
"requestedSubprotocols",
"==",
"null",
"||",
"supportedSubProtocols",
".",
"length",
"==",
"0",
")",
... | <b>This is copied from {@link WebSocketServerHandshaker}</b>
Selects the first matching supported sub protocol
@param requestedSubprotocols CSV of protocols to be supported. e.g. "chat, superchat"
@return First matching supported sub protocol. Null if not found. | [
"<b",
">",
"This",
"is",
"copied",
"from",
"{",
"@link",
"WebSocketServerHandshaker",
"}",
"<",
"/",
"b",
">"
] | train | https://github.com/ReactiveX/RxNetty/blob/a7ca9a9c1d544a79c82f7b17036daf6958bf1cd6/rxnetty-http/src/main/java/io/reactivex/netty/protocol/http/ws/server/WebSocketHandshaker.java#L71-L91 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/RequestXmlFactory.java | RequestXmlFactory.convertToXmlByteArray | public static byte[] convertToXmlByteArray(List<PartETag> partETags) {
XmlWriter xml = new XmlWriter();
xml.start("CompleteMultipartUpload");
if (partETags != null) {
List<PartETag> sortedPartETags = new ArrayList<PartETag>(partETags);
Collections.sort(sortedPartETags, new Comparator<PartETag>() {
public int compare(PartETag tag1, PartETag tag2) {
if (tag1.getPartNumber() < tag2.getPartNumber()) return -1;
if (tag1.getPartNumber() > tag2.getPartNumber()) return 1;
return 0;
}
});
for (PartETag partEtag : sortedPartETags) {
xml.start("Part");
xml.start("PartNumber").value(Integer.toString(partEtag.getPartNumber())).end();
xml.start("ETag").value(partEtag.getETag()).end();
xml.end();
}
}
xml.end();
return xml.getBytes();
} | java | public static byte[] convertToXmlByteArray(List<PartETag> partETags) {
XmlWriter xml = new XmlWriter();
xml.start("CompleteMultipartUpload");
if (partETags != null) {
List<PartETag> sortedPartETags = new ArrayList<PartETag>(partETags);
Collections.sort(sortedPartETags, new Comparator<PartETag>() {
public int compare(PartETag tag1, PartETag tag2) {
if (tag1.getPartNumber() < tag2.getPartNumber()) return -1;
if (tag1.getPartNumber() > tag2.getPartNumber()) return 1;
return 0;
}
});
for (PartETag partEtag : sortedPartETags) {
xml.start("Part");
xml.start("PartNumber").value(Integer.toString(partEtag.getPartNumber())).end();
xml.start("ETag").value(partEtag.getETag()).end();
xml.end();
}
}
xml.end();
return xml.getBytes();
} | [
"public",
"static",
"byte",
"[",
"]",
"convertToXmlByteArray",
"(",
"List",
"<",
"PartETag",
">",
"partETags",
")",
"{",
"XmlWriter",
"xml",
"=",
"new",
"XmlWriter",
"(",
")",
";",
"xml",
".",
"start",
"(",
"\"CompleteMultipartUpload\"",
")",
";",
"if",
"(... | Converts the specified list of PartETags to an XML fragment that can be
sent to the CompleteMultipartUpload operation of Amazon S3.
@param partETags
The list of part ETags containing the data to include in the
new XML fragment.
@return A byte array containing the data | [
"Converts",
"the",
"specified",
"list",
"of",
"PartETags",
"to",
"an",
"XML",
"fragment",
"that",
"can",
"be",
"sent",
"to",
"the",
"CompleteMultipartUpload",
"operation",
"of",
"Amazon",
"S3",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/RequestXmlFactory.java#L56-L79 |
craterdog/java-general-utilities | src/main/java/craterdog/utils/ByteUtils.java | ByteUtils.bytesToLong | static public long bytesToLong(byte[] buffer, int index) {
int length = buffer.length - index;
if (length > 8) length = 8;
long l = 0;
for (int i = 0; i < length; i++) {
l |= ((buffer[index + length - i - 1] & 0xFFL) << (i * 8));
}
return l;
} | java | static public long bytesToLong(byte[] buffer, int index) {
int length = buffer.length - index;
if (length > 8) length = 8;
long l = 0;
for (int i = 0; i < length; i++) {
l |= ((buffer[index + length - i - 1] & 0xFFL) << (i * 8));
}
return l;
} | [
"static",
"public",
"long",
"bytesToLong",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"index",
")",
"{",
"int",
"length",
"=",
"buffer",
".",
"length",
"-",
"index",
";",
"if",
"(",
"length",
">",
"8",
")",
"length",
"=",
"8",
";",
"long",
"l",
... | This function converts the bytes in a byte array at the specified index to its
corresponding long value.
@param buffer The byte array containing the long.
@param index The index for the first byte in the byte array.
@return The corresponding long value. | [
"This",
"function",
"converts",
"the",
"bytes",
"in",
"a",
"byte",
"array",
"at",
"the",
"specified",
"index",
"to",
"its",
"corresponding",
"long",
"value",
"."
] | train | https://github.com/craterdog/java-general-utilities/blob/a3ff45eaa00c2b8ed5c53efe9fe5166065fc1f57/src/main/java/craterdog/utils/ByteUtils.java#L309-L317 |
aoindustries/aocode-public | src/main/java/com/aoindustries/servlet/http/Includer.java | Includer.setLocation | public static void setLocation(HttpServletRequest request, HttpServletResponse response, String location) {
if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) {
// Not included, setHeader directly
response.setHeader("Location", location);
} else {
// Is included, set attribute so top level tag can perform actual setHeader call
request.setAttribute(LOCATION_REQUEST_ATTRIBUTE_NAME, location);
}
} | java | public static void setLocation(HttpServletRequest request, HttpServletResponse response, String location) {
if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) {
// Not included, setHeader directly
response.setHeader("Location", location);
} else {
// Is included, set attribute so top level tag can perform actual setHeader call
request.setAttribute(LOCATION_REQUEST_ATTRIBUTE_NAME, location);
}
} | [
"public",
"static",
"void",
"setLocation",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"String",
"location",
")",
"{",
"if",
"(",
"request",
".",
"getAttribute",
"(",
"IS_INCLUDED_REQUEST_ATTRIBUTE_NAME",
")",
"==",
"null",
")"... | Sets a Location header. When not in an included page, calls setHeader directly.
When inside of an include will set request attribute so outermost include can call setHeader. | [
"Sets",
"a",
"Location",
"header",
".",
"When",
"not",
"in",
"an",
"included",
"page",
"calls",
"setHeader",
"directly",
".",
"When",
"inside",
"of",
"an",
"include",
"will",
"set",
"request",
"attribute",
"so",
"outermost",
"include",
"can",
"call",
"setHea... | train | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/Includer.java#L127-L135 |
ben-manes/caffeine | caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java | BoundedLocalCache.afterRead | void afterRead(Node<K, V> node, long now, boolean recordHit) {
if (recordHit) {
statsCounter().recordHits(1);
}
boolean delayable = skipReadBuffer() || (readBuffer.offer(node) != Buffer.FULL);
if (shouldDrainBuffers(delayable)) {
scheduleDrainBuffers();
}
refreshIfNeeded(node, now);
} | java | void afterRead(Node<K, V> node, long now, boolean recordHit) {
if (recordHit) {
statsCounter().recordHits(1);
}
boolean delayable = skipReadBuffer() || (readBuffer.offer(node) != Buffer.FULL);
if (shouldDrainBuffers(delayable)) {
scheduleDrainBuffers();
}
refreshIfNeeded(node, now);
} | [
"void",
"afterRead",
"(",
"Node",
"<",
"K",
",",
"V",
">",
"node",
",",
"long",
"now",
",",
"boolean",
"recordHit",
")",
"{",
"if",
"(",
"recordHit",
")",
"{",
"statsCounter",
"(",
")",
".",
"recordHits",
"(",
"1",
")",
";",
"}",
"boolean",
"delaya... | Performs the post-processing work required after a read.
@param node the entry in the page replacement policy
@param now the current time, in nanoseconds
@param recordHit if the hit count should be incremented | [
"Performs",
"the",
"post",
"-",
"processing",
"work",
"required",
"after",
"a",
"read",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L1106-L1116 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java | XBasePanel.printReport | public void printReport(PrintWriter out, ResourceBundle reg)
throws DBException
{
if (reg == null)
reg = ((BaseApplication)this.getTask().getApplication()).getResources(HtmlConstants.XML_RESOURCE, false);
String string = XmlUtilities.XML_LEAD_LINE;
out.println(string);
String strStylesheetPath = this.getStylesheetPath();
if (strStylesheetPath != null)
{
string = "<?xml-stylesheet type=\"text/xsl\" href=\"" + strStylesheetPath + "\" ?>";
out.println(string);
}
out.println(Utility.startTag(XMLTags.FULL_SCREEN));
this.printXMLParams(out, reg); // URL params
this.printXMLHeaderInfo(out, reg); // Title, keywords, etc.
this.printXmlHeader(out, reg); // Top menu
this.printXmlMenu(out, reg);
this.printXmlNavMenu(out, reg);
this.printXmlTrailer(out, reg);
this.processInputData(out);
((BasePanel)this.getScreenField()).prePrintReport();
out.println(Utility.startTag(XMLTags.CONTENT_AREA));
this.getScreenField().printScreen(out, reg);
out.println(Utility.endTag(XMLTags.CONTENT_AREA));
out.println(Utility.endTag(XMLTags.FULL_SCREEN));
} | java | public void printReport(PrintWriter out, ResourceBundle reg)
throws DBException
{
if (reg == null)
reg = ((BaseApplication)this.getTask().getApplication()).getResources(HtmlConstants.XML_RESOURCE, false);
String string = XmlUtilities.XML_LEAD_LINE;
out.println(string);
String strStylesheetPath = this.getStylesheetPath();
if (strStylesheetPath != null)
{
string = "<?xml-stylesheet type=\"text/xsl\" href=\"" + strStylesheetPath + "\" ?>";
out.println(string);
}
out.println(Utility.startTag(XMLTags.FULL_SCREEN));
this.printXMLParams(out, reg); // URL params
this.printXMLHeaderInfo(out, reg); // Title, keywords, etc.
this.printXmlHeader(out, reg); // Top menu
this.printXmlMenu(out, reg);
this.printXmlNavMenu(out, reg);
this.printXmlTrailer(out, reg);
this.processInputData(out);
((BasePanel)this.getScreenField()).prePrintReport();
out.println(Utility.startTag(XMLTags.CONTENT_AREA));
this.getScreenField().printScreen(out, reg);
out.println(Utility.endTag(XMLTags.CONTENT_AREA));
out.println(Utility.endTag(XMLTags.FULL_SCREEN));
} | [
"public",
"void",
"printReport",
"(",
"PrintWriter",
"out",
",",
"ResourceBundle",
"reg",
")",
"throws",
"DBException",
"{",
"if",
"(",
"reg",
"==",
"null",
")",
"reg",
"=",
"(",
"(",
"BaseApplication",
")",
"this",
".",
"getTask",
"(",
")",
".",
"getApp... | Output this screen using XML.
Display the html headers, etc. then:
<ol>
- Parse any parameters passed in and set the field values.
- Process any command (such as move=Next).
- Render this screen as Html (by calling printHtmlScreen()).
</ol>
@exception DBException File exception. | [
"Output",
"this",
"screen",
"using",
"XML",
".",
"Display",
"the",
"html",
"headers",
"etc",
".",
"then",
":",
"<ol",
">",
"-",
"Parse",
"any",
"parameters",
"passed",
"in",
"and",
"set",
"the",
"field",
"values",
".",
"-",
"Process",
"any",
"command",
... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java#L82-L115 |
hap-java/HAP-Java | src/main/java/io/github/hapjava/impl/pairing/ClientEvidenceRoutineImpl.java | ClientEvidenceRoutineImpl.computeClientEvidence | @Override
public BigInteger computeClientEvidence(
SRP6CryptoParams cryptoParams, SRP6ClientEvidenceContext ctx) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(cryptoParams.H);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not locate requested algorithm", e);
}
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.N));
byte[] hN = digest.digest();
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.g));
byte[] hg = digest.digest();
byte[] hNhg = xor(hN, hg);
digest.update(ctx.userID.getBytes(StandardCharsets.UTF_8));
byte[] hu = digest.digest();
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.S));
byte[] hS = digest.digest();
digest.update(hNhg);
digest.update(hu);
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.s));
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.A));
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.B));
digest.update(hS);
BigInteger ret = new BigInteger(1, digest.digest());
return ret;
} | java | @Override
public BigInteger computeClientEvidence(
SRP6CryptoParams cryptoParams, SRP6ClientEvidenceContext ctx) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(cryptoParams.H);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not locate requested algorithm", e);
}
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.N));
byte[] hN = digest.digest();
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.g));
byte[] hg = digest.digest();
byte[] hNhg = xor(hN, hg);
digest.update(ctx.userID.getBytes(StandardCharsets.UTF_8));
byte[] hu = digest.digest();
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.S));
byte[] hS = digest.digest();
digest.update(hNhg);
digest.update(hu);
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.s));
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.A));
digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.B));
digest.update(hS);
BigInteger ret = new BigInteger(1, digest.digest());
return ret;
} | [
"@",
"Override",
"public",
"BigInteger",
"computeClientEvidence",
"(",
"SRP6CryptoParams",
"cryptoParams",
",",
"SRP6ClientEvidenceContext",
"ctx",
")",
"{",
"MessageDigest",
"digest",
";",
"try",
"{",
"digest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"cryptoPa... | Calculates M1 according to the following formula:
<p>M1 = H(H(N) xor H(g) || H(username) || s || A || B || H(S)) | [
"Calculates",
"M1",
"according",
"to",
"the",
"following",
"formula",
":"
] | train | https://github.com/hap-java/HAP-Java/blob/d2b2f4f1579580a2b5958af3a192128345843db9/src/main/java/io/github/hapjava/impl/pairing/ClientEvidenceRoutineImpl.java#L20-L52 |
xqbase/util | util-jdk17/src/main/java/com/xqbase/util/Time.java | Time.toTimeString | public static String toTimeString(long time, boolean millis) {
GregorianCalendar cal = new GregorianCalendar(0, 0, 0);
cal.setTimeInMillis(time);
return toTimeString(cal, millis);
} | java | public static String toTimeString(long time, boolean millis) {
GregorianCalendar cal = new GregorianCalendar(0, 0, 0);
cal.setTimeInMillis(time);
return toTimeString(cal, millis);
} | [
"public",
"static",
"String",
"toTimeString",
"(",
"long",
"time",
",",
"boolean",
"millis",
")",
"{",
"GregorianCalendar",
"cal",
"=",
"new",
"GregorianCalendar",
"(",
"0",
",",
"0",
",",
"0",
")",
";",
"cal",
".",
"setTimeInMillis",
"(",
"time",
")",
"... | Convert a Unix time (in milliseconds) to a time string
@param millis <code>true</code> to show milliseconds in decimal and
<code>false</code> to round to the second | [
"Convert",
"a",
"Unix",
"time",
"(",
"in",
"milliseconds",
")",
"to",
"a",
"time",
"string"
] | train | https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Time.java#L99-L103 |
find-sec-bugs/find-sec-bugs | findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/common/ByteCode.java | ByteCode.getPrevInstruction | public static <T> T getPrevInstruction(InstructionHandle startHandle, Class<T> clazz) {
InstructionHandle curHandle = startHandle;
while (curHandle != null) {
curHandle = curHandle.getPrev();
if (curHandle != null && clazz.isInstance(curHandle.getInstruction())) {
return clazz.cast(curHandle.getInstruction());
}
}
return null;
} | java | public static <T> T getPrevInstruction(InstructionHandle startHandle, Class<T> clazz) {
InstructionHandle curHandle = startHandle;
while (curHandle != null) {
curHandle = curHandle.getPrev();
if (curHandle != null && clazz.isInstance(curHandle.getInstruction())) {
return clazz.cast(curHandle.getInstruction());
}
}
return null;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getPrevInstruction",
"(",
"InstructionHandle",
"startHandle",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"InstructionHandle",
"curHandle",
"=",
"startHandle",
";",
"while",
"(",
"curHandle",
"!=",
"null",
")",
"{... | Get the previous instruction matching the given type of instruction (second parameter)
@param startHandle Location to start from
@param clazz Type of instruction to look for
@return The instruction found (null if not found) | [
"Get",
"the",
"previous",
"instruction",
"matching",
"the",
"given",
"type",
"of",
"instruction",
"(",
"second",
"parameter",
")"
] | train | https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/common/ByteCode.java#L155-L165 |
alkacon/opencms-core | src-gwt/org/opencms/acacia/client/CmsEditorBase.java | CmsEditorBase.addEntityChangeHandler | public void addEntityChangeHandler(String entityId, ValueChangeHandler<CmsEntity> handler) {
CmsEntity entity = m_entityBackend.getEntity(entityId);
if (entity != null) {
entity.addValueChangeHandler(handler);
}
} | java | public void addEntityChangeHandler(String entityId, ValueChangeHandler<CmsEntity> handler) {
CmsEntity entity = m_entityBackend.getEntity(entityId);
if (entity != null) {
entity.addValueChangeHandler(handler);
}
} | [
"public",
"void",
"addEntityChangeHandler",
"(",
"String",
"entityId",
",",
"ValueChangeHandler",
"<",
"CmsEntity",
">",
"handler",
")",
"{",
"CmsEntity",
"entity",
"=",
"m_entityBackend",
".",
"getEntity",
"(",
"entityId",
")",
";",
"if",
"(",
"entity",
"!=",
... | Adds the value change handler to the entity with the given id.<p>
@param entityId the entity id
@param handler the change handler | [
"Adds",
"the",
"value",
"change",
"handler",
"to",
"the",
"entity",
"with",
"the",
"given",
"id",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsEditorBase.java#L267-L273 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/writer/JsniCodeBlockBuilder.java | JsniCodeBlockBuilder.addStatement | public JsniCodeBlockBuilder addStatement( String format, Object... args ) {
builder.addStatement( format, args );
return this;
} | java | public JsniCodeBlockBuilder addStatement( String format, Object... args ) {
builder.addStatement( format, args );
return this;
} | [
"public",
"JsniCodeBlockBuilder",
"addStatement",
"(",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"builder",
".",
"addStatement",
"(",
"format",
",",
"args",
")",
";",
"return",
"this",
";",
"}"
] | <p>addStatement</p>
@param format a {@link java.lang.String} object.
@param args a {@link java.lang.Object} object.
@return a {@link com.github.nmorel.gwtjackson.rebind.writer.JsniCodeBlockBuilder} object. | [
"<p",
">",
"addStatement<",
"/",
"p",
">"
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/writer/JsniCodeBlockBuilder.java#L63-L66 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java | PublicIPAddressesInner.beginCreateOrUpdateAsync | public Observable<PublicIPAddressInner> beginCreateOrUpdateAsync(String resourceGroupName, String publicIpAddressName, PublicIPAddressInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpAddressName, parameters).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | java | public Observable<PublicIPAddressInner> beginCreateOrUpdateAsync(String resourceGroupName, String publicIpAddressName, PublicIPAddressInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpAddressName, parameters).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PublicIPAddressInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"publicIpAddressName",
",",
"PublicIPAddressInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"... | Creates or updates a static or dynamic public IP address.
@param resourceGroupName The name of the resource group.
@param publicIpAddressName The name of the public IP address.
@param parameters Parameters supplied to the create or update public IP address operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PublicIPAddressInner object | [
"Creates",
"or",
"updates",
"a",
"static",
"or",
"dynamic",
"public",
"IP",
"address",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java#L566-L573 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Callstacks.java | Callstacks.printCallstack | public static void printCallstack(final Level logLevel, final String[] carePackages, final String[] exceptablePackages) {
if (null == logLevel) {
LOGGER.log(Level.WARN, "Requires parameter [logLevel]");
return;
}
final Throwable throwable = new Throwable();
final StackTraceElement[] stackElements = throwable.getStackTrace();
if (null == stackElements) {
LOGGER.log(Level.WARN, "Empty call stack");
return;
}
final long tId = Thread.currentThread().getId();
final StringBuilder stackBuilder = new StringBuilder("CallStack [tId=").append(tId).append(Strings.LINE_SEPARATOR);
for (int i = 1; i < stackElements.length; i++) {
final String stackElemClassName = stackElements[i].getClassName();
if (!StringUtils.startsWithAny(stackElemClassName, carePackages)
|| StringUtils.startsWithAny(stackElemClassName, exceptablePackages)) {
continue;
}
stackBuilder.append(" [className=").append(stackElements[i].getClassName()).append(", fileName=").append(stackElements[i].getFileName()).append(", lineNumber=").append(stackElements[i].getLineNumber()).append(", methodName=").append(stackElements[i].getMethodName()).append(']').append(
Strings.LINE_SEPARATOR);
}
stackBuilder.append("], full depth [").append(stackElements.length).append("]");
LOGGER.log(logLevel, stackBuilder.toString());
} | java | public static void printCallstack(final Level logLevel, final String[] carePackages, final String[] exceptablePackages) {
if (null == logLevel) {
LOGGER.log(Level.WARN, "Requires parameter [logLevel]");
return;
}
final Throwable throwable = new Throwable();
final StackTraceElement[] stackElements = throwable.getStackTrace();
if (null == stackElements) {
LOGGER.log(Level.WARN, "Empty call stack");
return;
}
final long tId = Thread.currentThread().getId();
final StringBuilder stackBuilder = new StringBuilder("CallStack [tId=").append(tId).append(Strings.LINE_SEPARATOR);
for (int i = 1; i < stackElements.length; i++) {
final String stackElemClassName = stackElements[i].getClassName();
if (!StringUtils.startsWithAny(stackElemClassName, carePackages)
|| StringUtils.startsWithAny(stackElemClassName, exceptablePackages)) {
continue;
}
stackBuilder.append(" [className=").append(stackElements[i].getClassName()).append(", fileName=").append(stackElements[i].getFileName()).append(", lineNumber=").append(stackElements[i].getLineNumber()).append(", methodName=").append(stackElements[i].getMethodName()).append(']').append(
Strings.LINE_SEPARATOR);
}
stackBuilder.append("], full depth [").append(stackElements.length).append("]");
LOGGER.log(logLevel, stackBuilder.toString());
} | [
"public",
"static",
"void",
"printCallstack",
"(",
"final",
"Level",
"logLevel",
",",
"final",
"String",
"[",
"]",
"carePackages",
",",
"final",
"String",
"[",
"]",
"exceptablePackages",
")",
"{",
"if",
"(",
"null",
"==",
"logLevel",
")",
"{",
"LOGGER",
".... | Prints call stack with the specified logging level.
@param logLevel the specified logging level
@param carePackages the specified packages to print, for example, ["org.b3log.latke", "org.b3log.solo"], {@code null} to care
nothing
@param exceptablePackages the specified packages to skip, for example, ["com.sun", "java.io", "org.b3log.solo.filter"],
{@code null} to skip nothing | [
"Prints",
"call",
"stack",
"with",
"the",
"specified",
"logging",
"level",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Callstacks.java#L72-L105 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/FilenameUtils.java | FilenameUtils.getUniqueFile | public static File getUniqueFile(File srcFile, char extSeparator) throws IOException {
if (srcFile == null) {
throw new IllegalArgumentException("srcFile must not be null");
}
String path = getFullPath(srcFile.getCanonicalPath());
String name = removeExtension(srcFile.getName());
String ext = getExtension(srcFile.getName());
String newName;
if (ext != null && !ext.isEmpty()) {
newName = name + extSeparator + ext;
} else {
newName = name;
}
int count = 0;
File destFile = new File(path, newName);
while (destFile.exists()) {
count++;
if (ext != null && !ext.isEmpty()) {
newName = name + "-" + count + extSeparator + ext;
} else {
newName = name + "-" + count;
}
destFile = new File(path, newName);
}
return (count == 0 ? srcFile : destFile);
} | java | public static File getUniqueFile(File srcFile, char extSeparator) throws IOException {
if (srcFile == null) {
throw new IllegalArgumentException("srcFile must not be null");
}
String path = getFullPath(srcFile.getCanonicalPath());
String name = removeExtension(srcFile.getName());
String ext = getExtension(srcFile.getName());
String newName;
if (ext != null && !ext.isEmpty()) {
newName = name + extSeparator + ext;
} else {
newName = name;
}
int count = 0;
File destFile = new File(path, newName);
while (destFile.exists()) {
count++;
if (ext != null && !ext.isEmpty()) {
newName = name + "-" + count + extSeparator + ext;
} else {
newName = name + "-" + count;
}
destFile = new File(path, newName);
}
return (count == 0 ? srcFile : destFile);
} | [
"public",
"static",
"File",
"getUniqueFile",
"(",
"File",
"srcFile",
",",
"char",
"extSeparator",
")",
"throws",
"IOException",
"{",
"if",
"(",
"srcFile",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"srcFile must not be null\"",
")",... | Returns a file name that does not overlap in the specified directory.
If a duplicate file name exists, it is returned by appending a number after the file name.
@param srcFile the file to seek
@param extSeparator the extension separator
@return an unique file
@throws IOException if failed to obtain an unique file | [
"Returns",
"a",
"file",
"name",
"that",
"does",
"not",
"overlap",
"in",
"the",
"specified",
"directory",
".",
"If",
"a",
"duplicate",
"file",
"name",
"exists",
"it",
"is",
"returned",
"by",
"appending",
"a",
"number",
"after",
"the",
"file",
"name",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/FilenameUtils.java#L300-L330 |
geomajas/geomajas-project-client-gwt | plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java | MultiLayerFeaturesList.setFeatures | public void setFeatures(Map<String, List<org.geomajas.layer.feature.Feature>> featureMap) {
MapModel mapModel = mapWidget.getMapModel();
for (Entry<String, List<org.geomajas.layer.feature.Feature>> clientLayerId : featureMap.entrySet()) {
Layer<?> layer = mapModel.getLayer(clientLayerId.getKey());
if (null != layer) {
List<org.geomajas.layer.feature.Feature> orgFeatures = clientLayerId.getValue();
if (!orgFeatures.isEmpty()) {
addFeatures(layer, orgFeatures);
}
}
}
} | java | public void setFeatures(Map<String, List<org.geomajas.layer.feature.Feature>> featureMap) {
MapModel mapModel = mapWidget.getMapModel();
for (Entry<String, List<org.geomajas.layer.feature.Feature>> clientLayerId : featureMap.entrySet()) {
Layer<?> layer = mapModel.getLayer(clientLayerId.getKey());
if (null != layer) {
List<org.geomajas.layer.feature.Feature> orgFeatures = clientLayerId.getValue();
if (!orgFeatures.isEmpty()) {
addFeatures(layer, orgFeatures);
}
}
}
} | [
"public",
"void",
"setFeatures",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"org",
".",
"geomajas",
".",
"layer",
".",
"feature",
".",
"Feature",
">",
">",
"featureMap",
")",
"{",
"MapModel",
"mapModel",
"=",
"mapWidget",
".",
"getMapModel",
"(",
")",
... | Feed a map of features to the widget, so it can be built.
@param featureMap feature map | [
"Feed",
"a",
"map",
"of",
"features",
"to",
"the",
"widget",
"so",
"it",
"can",
"be",
"built",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java#L100-L112 |
Stratio/deep-spark | deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java | RangeUtils.fetchTokens | static Map<String, Iterable<Comparable>> fetchTokens(String query, final Pair<Session, String> sessionWithHost,
IPartitioner partitioner) {
ResultSet rSet = sessionWithHost.left.execute(query);
final AbstractType tkValidator = partitioner.getTokenValidator();
final Map<String, Iterable<Comparable>> tokens = Maps.newHashMap();
Iterable<Pair<String, Iterable<Comparable>>> pairs =
transform(rSet.all(), new FetchTokensRowPairFunction(sessionWithHost, tkValidator));
for (Pair<String, Iterable<Comparable>> pair : pairs) {
tokens.put(pair.left, pair.right);
}
return tokens;
} | java | static Map<String, Iterable<Comparable>> fetchTokens(String query, final Pair<Session, String> sessionWithHost,
IPartitioner partitioner) {
ResultSet rSet = sessionWithHost.left.execute(query);
final AbstractType tkValidator = partitioner.getTokenValidator();
final Map<String, Iterable<Comparable>> tokens = Maps.newHashMap();
Iterable<Pair<String, Iterable<Comparable>>> pairs =
transform(rSet.all(), new FetchTokensRowPairFunction(sessionWithHost, tkValidator));
for (Pair<String, Iterable<Comparable>> pair : pairs) {
tokens.put(pair.left, pair.right);
}
return tokens;
} | [
"static",
"Map",
"<",
"String",
",",
"Iterable",
"<",
"Comparable",
">",
">",
"fetchTokens",
"(",
"String",
"query",
",",
"final",
"Pair",
"<",
"Session",
",",
"String",
">",
"sessionWithHost",
",",
"IPartitioner",
"partitioner",
")",
"{",
"ResultSet",
"rSet... | Gets the list of token for each cluster machine.<br/>
The concrete class of the token depends on the partitioner used.<br/>
@param query the query to execute against the given session to obtain the list of tokens.
@param sessionWithHost the pair object containing both the session and the name of the machine to which we're connected to.
@param partitioner the partitioner used in the cluster.
@return a map containing, for each cluster machine, the list of tokens. Tokens are not returned in any particular
order. | [
"Gets",
"the",
"list",
"of",
"token",
"for",
"each",
"cluster",
"machine",
".",
"<br",
"/",
">",
"The",
"concrete",
"class",
"of",
"the",
"token",
"depends",
"on",
"the",
"partitioner",
"used",
".",
"<br",
"/",
">"
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java#L80-L96 |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java | NorwegianDateUtil.addWorkingDaysToDate | public static Date addWorkingDaysToDate(Date date, int days) {
Calendar cal = dateToCalendar(date);
for (int i = 0; i < days; i++) {
cal.add(Calendar.DATE, 1);
while (!isWorkingDay(cal)) {
cal.add(Calendar.DATE, 1);
}
}
return cal.getTime();
} | java | public static Date addWorkingDaysToDate(Date date, int days) {
Calendar cal = dateToCalendar(date);
for (int i = 0; i < days; i++) {
cal.add(Calendar.DATE, 1);
while (!isWorkingDay(cal)) {
cal.add(Calendar.DATE, 1);
}
}
return cal.getTime();
} | [
"public",
"static",
"Date",
"addWorkingDaysToDate",
"(",
"Date",
"date",
",",
"int",
"days",
")",
"{",
"Calendar",
"cal",
"=",
"dateToCalendar",
"(",
"date",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"days",
";",
"i",
"++",
")",
"{... | Adds the given number of working days to the given date. A working day is
specified as a regular Norwegian working day, excluding weekends and all
national holidays.
<p/>
Example 1:<br/>
- Add 5 working days to Wednesday 21.03.2007 -> Yields Wednesday
28.03.2007. (skipping saturday and sunday)<br/>
<p/>
Example 2:<br/>
- Add 5 working days to Wednesday 04.04.2007 (day before
easter-long-weekend) -> yields Monday 16.04.2007 (skipping 2 weekends and
3 weekday holidays).
@param date
The original date.
@param days
The number of working days to add.
@return The new date. | [
"Adds",
"the",
"given",
"number",
"of",
"working",
"days",
"to",
"the",
"given",
"date",
".",
"A",
"working",
"day",
"is",
"specified",
"as",
"a",
"regular",
"Norwegian",
"working",
"day",
"excluding",
"weekends",
"and",
"all",
"national",
"holidays",
".",
... | train | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L39-L50 |
rometools/rome | rome/src/main/java/com/rometools/rome/io/WireFeedInput.java | WireFeedInput.createSAXBuilder | protected SAXBuilder createSAXBuilder() {
SAXBuilder saxBuilder;
if (validate) {
saxBuilder = new SAXBuilder(XMLReaders.DTDVALIDATING);
} else {
saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING);
}
saxBuilder.setEntityResolver(RESOLVER);
//
// This code is needed to fix the security problem outlined in
// http://www.securityfocus.com/archive/1/297714
//
// Unfortunately there isn't an easy way to check if an XML parser
// supports a particular feature, so
// we need to set it and catch the exception if it fails. We also need
// to subclass the JDom SAXBuilder
// class in order to get access to the underlying SAX parser - otherwise
// the features don't get set until
// we are already building the document, by which time it's too late to
// fix the problem.
//
// Crimson is one parser which is known not to support these features.
try {
final XMLReader parser = saxBuilder.createParser();
setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-general-entities", false);
setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-parameter-entities", false);
setFeature(saxBuilder, parser, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
if(!allowDoctypes) {
setFeature(saxBuilder, parser, "http://apache.org/xml/features/disallow-doctype-decl", true);
}
} catch (final JDOMException e) {
throw new IllegalStateException("JDOM could not create a SAX parser", e);
}
saxBuilder.setExpandEntities(false);
return saxBuilder;
} | java | protected SAXBuilder createSAXBuilder() {
SAXBuilder saxBuilder;
if (validate) {
saxBuilder = new SAXBuilder(XMLReaders.DTDVALIDATING);
} else {
saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING);
}
saxBuilder.setEntityResolver(RESOLVER);
//
// This code is needed to fix the security problem outlined in
// http://www.securityfocus.com/archive/1/297714
//
// Unfortunately there isn't an easy way to check if an XML parser
// supports a particular feature, so
// we need to set it and catch the exception if it fails. We also need
// to subclass the JDom SAXBuilder
// class in order to get access to the underlying SAX parser - otherwise
// the features don't get set until
// we are already building the document, by which time it's too late to
// fix the problem.
//
// Crimson is one parser which is known not to support these features.
try {
final XMLReader parser = saxBuilder.createParser();
setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-general-entities", false);
setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-parameter-entities", false);
setFeature(saxBuilder, parser, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
if(!allowDoctypes) {
setFeature(saxBuilder, parser, "http://apache.org/xml/features/disallow-doctype-decl", true);
}
} catch (final JDOMException e) {
throw new IllegalStateException("JDOM could not create a SAX parser", e);
}
saxBuilder.setExpandEntities(false);
return saxBuilder;
} | [
"protected",
"SAXBuilder",
"createSAXBuilder",
"(",
")",
"{",
"SAXBuilder",
"saxBuilder",
";",
"if",
"(",
"validate",
")",
"{",
"saxBuilder",
"=",
"new",
"SAXBuilder",
"(",
"XMLReaders",
".",
"DTDVALIDATING",
")",
";",
"}",
"else",
"{",
"saxBuilder",
"=",
"n... | Creates and sets up a org.jdom2.input.SAXBuilder for parsing.
@return a new org.jdom2.input.SAXBuilder object | [
"Creates",
"and",
"sets",
"up",
"a",
"org",
".",
"jdom2",
".",
"input",
".",
"SAXBuilder",
"for",
"parsing",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/WireFeedInput.java#L322-L365 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java | CPDefinitionOptionValueRelPersistenceImpl.findByKey | @Override
public List<CPDefinitionOptionValueRel> findByKey(String key, int start,
int end, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) {
return findByKey(key, start, end, orderByComparator, true);
} | java | @Override
public List<CPDefinitionOptionValueRel> findByKey(String key, int start,
int end, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) {
return findByKey(key, start, end, orderByComparator, true);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionOptionValueRel",
">",
"findByKey",
"(",
"String",
"key",
",",
"int",
"start",
",",
"int",
"end",
",",
"OrderByComparator",
"<",
"CPDefinitionOptionValueRel",
">",
"orderByComparator",
")",
"{",
"return",
"findBy... | Returns an ordered range of all the cp definition option value rels where key = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionOptionValueRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param key the key
@param start the lower bound of the range of cp definition option value rels
@param end the upper bound of the range of cp definition option value rels (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching cp definition option value rels | [
"Returns",
"an",
"ordered",
"range",
"of",
"all",
"the",
"cp",
"definition",
"option",
"value",
"rels",
"where",
"key",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java#L3133-L3137 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/error/SingleError.java | SingleError.hashCodeLinkedException | @OverrideOnDemand
protected void hashCodeLinkedException (@Nonnull final HashCodeGenerator aHCG, @Nullable final Throwable t)
{
if (t == null)
aHCG.append (HashCodeCalculator.HASHCODE_NULL);
else
aHCG.append (t.getClass ()).append (t.getMessage ());
} | java | @OverrideOnDemand
protected void hashCodeLinkedException (@Nonnull final HashCodeGenerator aHCG, @Nullable final Throwable t)
{
if (t == null)
aHCG.append (HashCodeCalculator.HASHCODE_NULL);
else
aHCG.append (t.getClass ()).append (t.getMessage ());
} | [
"@",
"OverrideOnDemand",
"protected",
"void",
"hashCodeLinkedException",
"(",
"@",
"Nonnull",
"final",
"HashCodeGenerator",
"aHCG",
",",
"@",
"Nullable",
"final",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"aHCG",
".",
"append",
"(",
"Has... | Overridable implementation of Throwable for the Linked exception field.
This can be overridden to implement a different algorithm. This is
customizable because there is no default way of hashing Exceptions in Java.
If you override this method you must also override
{@link #equalsLinkedException(Throwable, Throwable)}!
@param aHCG
The hash code generator to append to. Never <code>null</code>.
@param t
The Throwable to append. May be <code>null</code>. | [
"Overridable",
"implementation",
"of",
"Throwable",
"for",
"the",
"Linked",
"exception",
"field",
".",
"This",
"can",
"be",
"overridden",
"to",
"implement",
"a",
"different",
"algorithm",
".",
"This",
"is",
"customizable",
"because",
"there",
"is",
"no",
"defaul... | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/error/SingleError.java#L164-L171 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/sequences/LVMorphologyReaderAndWriter.java | LVMorphologyReaderAndWriter.applyLVmorphoanalysis | private static void applyLVmorphoanalysis(CoreLabel wi, Collection<String> answerAttributes) {
Word analysis = analyzer.analyze(wi.word());
applyLVmorphoanalysis(wi, analysis, answerAttributes);
} | java | private static void applyLVmorphoanalysis(CoreLabel wi, Collection<String> answerAttributes) {
Word analysis = analyzer.analyze(wi.word());
applyLVmorphoanalysis(wi, analysis, answerAttributes);
} | [
"private",
"static",
"void",
"applyLVmorphoanalysis",
"(",
"CoreLabel",
"wi",
",",
"Collection",
"<",
"String",
">",
"answerAttributes",
")",
"{",
"Word",
"analysis",
"=",
"analyzer",
".",
"analyze",
"(",
"wi",
".",
"word",
"(",
")",
")",
";",
"applyLVmorpho... | Performs LV morphology analysis of the token wi, adds the possible readins and marks the most likely one.
If an AnswerAnnotation exists, then it is considered to be a morphosyntactic tag, and the attributes are filtered for the training.
@param wi
@param answerAttributes | [
"Performs",
"LV",
"morphology",
"analysis",
"of",
"the",
"token",
"wi",
"adds",
"the",
"possible",
"readins",
"and",
"marks",
"the",
"most",
"likely",
"one",
".",
"If",
"an",
"AnswerAnnotation",
"exists",
"then",
"it",
"is",
"considered",
"to",
"be",
"a",
... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/sequences/LVMorphologyReaderAndWriter.java#L185-L188 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java | ArrayList.set | public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
} | java | public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
} | [
"public",
"E",
"set",
"(",
"int",
"index",
",",
"E",
"element",
")",
"{",
"if",
"(",
"index",
">=",
"size",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"outOfBoundsMsg",
"(",
"index",
")",
")",
";",
"E",
"oldValue",
"=",
"(",
"E",
")",
"el... | Replaces the element at the specified position in this list with
the specified element.
@param index index of the element to replace
@param element element to be stored at the specified position
@return the element previously at the specified position
@throws IndexOutOfBoundsException {@inheritDoc} | [
"Replaces",
"the",
"element",
"at",
"the",
"specified",
"position",
"in",
"this",
"list",
"with",
"the",
"specified",
"element",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java#L451-L458 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.getTime | public Time getTime(int columnIndex, Calendar cal) throws SQLException {
TimeData t = (TimeData) getColumnInType(columnIndex, Type.SQL_TIME);
if (t == null) {
return null;
}
long millis = t.getSeconds() * 1000;
if (resultMetaData.columnTypes[--columnIndex]
.isDateTimeTypeWithZone()) {}
else {
// UTC - calZO == (UTC - sessZO) + (sessionZO - calZO)
if (cal != null) {
int zoneOffset = HsqlDateTime.getZoneMillis(cal, millis);
millis += session.getZoneSeconds() * 1000 - zoneOffset;
}
}
return new Time(millis);
} | java | public Time getTime(int columnIndex, Calendar cal) throws SQLException {
TimeData t = (TimeData) getColumnInType(columnIndex, Type.SQL_TIME);
if (t == null) {
return null;
}
long millis = t.getSeconds() * 1000;
if (resultMetaData.columnTypes[--columnIndex]
.isDateTimeTypeWithZone()) {}
else {
// UTC - calZO == (UTC - sessZO) + (sessionZO - calZO)
if (cal != null) {
int zoneOffset = HsqlDateTime.getZoneMillis(cal, millis);
millis += session.getZoneSeconds() * 1000 - zoneOffset;
}
}
return new Time(millis);
} | [
"public",
"Time",
"getTime",
"(",
"int",
"columnIndex",
",",
"Calendar",
"cal",
")",
"throws",
"SQLException",
"{",
"TimeData",
"t",
"=",
"(",
"TimeData",
")",
"getColumnInType",
"(",
"columnIndex",
",",
"Type",
".",
"SQL_TIME",
")",
";",
"if",
"(",
"t",
... | <!-- start generic documentation -->
Retrieves the value of the designated column in the current row
of this <code>ResultSet</code> object as a <code>java.sql.Time</code>
object in the Java programming language.
This method uses the given calendar to construct an appropriate millisecond
value for the time if the underlying database does not store
timezone information.
<!-- end generic documentation -->
<h3>HSQLDB-Specific Information:</h3> <p>
The JDBC specification for this method is vague. HSQLDB interprets the
specification as follows:
<ol>
<li>If the SQL type of the column is WITH TIME ZONE, then the UTC value
of the returned java.sql.Time object is the UTC of the SQL value without
modification. In other words, the Calendar object is not used.</li>
<li>If the SQL type of the column is WITHOUT TIME ZONE, then the UTC
value of the returned java.sql.Time is correct for the given Calendar
object.</li>
<li>If the cal argument is null, it it ignored and the method returns
the same Object as the method without the Calendar parameter.</li>
</ol>
</div>
@param columnIndex the first column is 1, the second is 2, ...
@param cal the <code>java.util.Calendar</code> object
to use in constructing the time
@return the column value as a <code>java.sql.Time</code> object;
if the value is SQL <code>NULL</code>,
the value returned is <code>null</code> in the Java programming language
@exception SQLException if a database access error occurs
or this method is called on a closed result set
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Retrieves",
"the",
"value",
"of",
"the",
"designated",
"column",
"in",
"the",
"current",
"row",
"of",
"this",
"<code",
">",
"ResultSet<",
"/",
"code",
">",
"object",
"as",
"a",
"<code",
">",
"j... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L4573-L4596 |
killbill/killbill | catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java | DefaultCatalogCache.initializeCacheLoaderArgument | private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) {
final LoaderCallback loaderCallback = new LoaderCallback() {
@Override
public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException {
return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId);
}
};
final Object[] args = new Object[1];
args[0] = loaderCallback;
final ObjectType irrelevant = null;
final InternalTenantContext notUsed = null;
return new CacheLoaderArgument(irrelevant, args, notUsed);
} | java | private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) {
final LoaderCallback loaderCallback = new LoaderCallback() {
@Override
public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException {
return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId);
}
};
final Object[] args = new Object[1];
args[0] = loaderCallback;
final ObjectType irrelevant = null;
final InternalTenantContext notUsed = null;
return new CacheLoaderArgument(irrelevant, args, notUsed);
} | [
"private",
"CacheLoaderArgument",
"initializeCacheLoaderArgument",
"(",
"final",
"boolean",
"filterTemplateCatalog",
")",
"{",
"final",
"LoaderCallback",
"loaderCallback",
"=",
"new",
"LoaderCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"Catalog",
"loadCatalog",
... | This is a contract between the TenantCatalogCacheLoader and the DefaultCatalogCache | [
"This",
"is",
"a",
"contract",
"between",
"the",
"TenantCatalogCacheLoader",
"and",
"the",
"DefaultCatalogCache"
] | train | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java#L214-L226 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java | DurationFormatUtils.paddedValue | private static String paddedValue(final long value, final boolean padWithZeros, final int count) {
final String longString = Long.toString(value);
return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString;
} | java | private static String paddedValue(final long value, final boolean padWithZeros, final int count) {
final String longString = Long.toString(value);
return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString;
} | [
"private",
"static",
"String",
"paddedValue",
"(",
"final",
"long",
"value",
",",
"final",
"boolean",
"padWithZeros",
",",
"final",
"int",
"count",
")",
"{",
"final",
"String",
"longString",
"=",
"Long",
".",
"toString",
"(",
"value",
")",
";",
"return",
"... | <p>Converts a {@code long} to a {@code String} with optional
zero padding.</p>
@param value the value to convert
@param padWithZeros whether to pad with zeroes
@param count the size to pad to (ignored if {@code padWithZeros} is false)
@return the string result | [
"<p",
">",
"Converts",
"a",
"{",
"@code",
"long",
"}",
"to",
"a",
"{",
"@code",
"String",
"}",
"with",
"optional",
"zero",
"padding",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java#L480-L483 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.